blob: 0778d091b74bc361fca844b5ddf0f992bdb2ac64 [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 Sharkey21c9c452011-06-07 12:26:43 -0700116import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700117import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700118import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700119import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700120import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700121import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700122import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700123import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600124import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700125import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700126import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700127import android.net.NetworkTemplate;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600128import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700129import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700130import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700131import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700132import android.os.Environment;
133import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700134import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700135import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700136import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700137import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700138import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700139import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700140import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700141import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600142import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800143import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700144import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700145import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600146import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700147import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700148import android.os.ShellCallback;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600149import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700150import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700151import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700152import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700153import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100154import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700155import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600156import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800157import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600158import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700159import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400160import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700161import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700162import android.util.ArrayMap;
163import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700164import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700165import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700166import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700167import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600168import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700169import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600170import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700171import android.util.SparseBooleanArray;
172import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700173import android.util.TrustedTime;
174import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700175
Jeff Sharkey497e4432011-06-14 17:27:29 -0700176import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700177import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800178import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400179import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500180import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700181import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800182import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600183import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700184import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700185import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600186import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700187import com.android.server.DeviceIdleController;
188import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700189import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700190import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800191import com.android.server.SystemConfig;
jackqdyulei455e90a2017-02-09 15:29:16 -0800192import com.android.server.power.BatterySaverPolicy.ServiceType;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600193
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600194import libcore.io.IoUtils;
195
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700196import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700197import org.xmlpull.v1.XmlSerializer;
198
199import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700200import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700201import java.io.FileInputStream;
202import java.io.FileNotFoundException;
203import java.io.FileOutputStream;
204import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700205import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700206import java.lang.annotation.Retention;
207import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100208import java.nio.charset.StandardCharsets;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600209import java.time.ZoneId;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600210import java.time.ZonedDateTime;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700211import java.util.ArrayList;
212import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700213import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600214import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400215import java.util.Objects;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800216import java.util.concurrent.CountDownLatch;
217import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700218
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700219/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700220 * Service that maintains low-level network policy rules, using
221 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700222 * <p>
223 * Derives active rules by combining a given policy with other system status,
224 * and delivers to listeners, such as {@link ConnectivityManager}, for
225 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700226 *
227 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000228 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700229 * <ul>
230 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
231 * rules).
232 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
233 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000234 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
235 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700236 * </ul>
237 *
238 * <p>
239 * As such, methods that require synchronization have the following prefixes:
240 * <ul>
241 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
242 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000243 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
244 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700245 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700246 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700247public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800248 static final String TAG = "NetworkPolicy";
Hugo Benichi5d2f2b52017-04-07 08:53:25 +0900249 private static final boolean LOGD = false;
250 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700251
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700252 private static final int VERSION_INIT = 1;
253 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700254 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800255 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800256 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800257 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700258 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700259 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700260 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700261 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600262 private static final int VERSION_ADDED_CYCLE = 11;
263 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700264
Sudheer Shankae7361852017-03-07 11:51:46 -0800265 /**
266 * Max items written to {@link #ProcStateSeqHistory}.
267 */
268 @VisibleForTesting
269 public static final int MAX_PROC_STATE_SEQ_HISTORY =
270 ActivityManager.isLowRamDeviceStatic() ? 50 : 200;
271
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800272 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400273 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800274 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400275 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800276 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400277 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700278
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700279 private static final String TAG_POLICY_LIST = "policy-list";
280 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600281 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700282 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700283 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800284 private static final String TAG_WHITELIST = "whitelist";
285 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800286 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700287
288 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700289 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700290 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
291 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700292 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600293 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
294 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
295 private static final String ATTR_CYCLE_START = "cycleStart";
296 private static final String ATTR_CYCLE_END = "cycleEnd";
297 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700298 private static final String ATTR_WARNING_BYTES = "warningBytes";
299 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700300 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800301 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
302 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800303 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700304 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700305 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700306 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700307 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600308 private static final String ATTR_SUB_ID = "subId";
309 private static final String ATTR_TITLE = "title";
310 private static final String ATTR_SUMMARY = "summary";
311 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
312 private static final String ATTR_USAGE_BYTES = "usageBytes";
313 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600314 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700315
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800316 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800317 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800318 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800319 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700320
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700321 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
322
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700323 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700324 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800325 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800326 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700327 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700328 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
329 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700330 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700331 private static final int MSG_SET_FIREWALL_RULES = 14;
Felipe Leme03e95e22016-09-09 09:25:31 -0700332 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700333
Makoto Onuki8e777332017-03-28 11:25:47 -0700334 private static final int UID_MSG_STATE_CHANGED = 100;
335 private static final int UID_MSG_GONE = 101;
336
Jeff Sharkey75279902011-05-24 18:39:45 -0700337 private final Context mContext;
338 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700339 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700340 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700341 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700342 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700343 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700344 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700345
346 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700347 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700348 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700349 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800350 @GuardedBy("mUidRulesFirstLock")
351 private PowerSaveState mRestrictBackgroundPowerState;
352
353 // Store the status of restrict background before turning on battery saver.
354 // Used to restore mRestrictBackground when battery saver is turned off.
355 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700356
Felipe Lemef0823852016-06-08 13:43:08 -0700357 // See main javadoc for instructions on how to use these locks.
358 final Object mUidRulesFirstLock = new Object();
359 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700360
Felipe Lemef0823852016-06-08 13:43:08 -0700361 @GuardedBy("allLocks") volatile boolean mSystemReady;
362
Felipe Lemef0823852016-06-08 13:43:08 -0700363 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
364 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
365 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800366 // Store whether user flipped restrict background in battery saver mode
367 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700368
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700369 private final boolean mSuppressDefaultPolicy;
370
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700371 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800372 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700373
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600374 /** Map from subId to subscription plans. */
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600375 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600376 /** Map from subId to package name that owns subscription plans. */
377 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600378
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700379 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700380 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700381 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700382 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700383
Felipe Lemef0823852016-06-08 13:43:08 -0700384 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700385 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700386 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700387 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700388 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800389 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700390
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700391 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700392 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700393 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
394
Jeff Sharkey32566012014-12-02 18:30:14 -0800395 /**
396 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700397 * in power save mode, except device idle (doze) still applies.
398 * TODO: An int array might be sufficient
399 */
Felipe Lemef0823852016-06-08 13:43:08 -0700400 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700401 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
402
403 /**
404 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800405 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700406 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800407 */
Felipe Lemef0823852016-06-08 13:43:08 -0700408 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700409 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700410
Felipe Lemef0823852016-06-08 13:43:08 -0700411 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700412 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
413
Felipe Lemeb85a6372016-01-14 16:16:16 -0800414 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800415 * UIDs that have been initially white-listed by system to avoid restricted background.
416 */
Felipe Lemef0823852016-06-08 13:43:08 -0700417 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800418 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
419 new SparseBooleanArray();
420
421 /**
422 * UIDs that have been initially white-listed by system to avoid restricted background,
423 * but later revoked by user.
424 */
Felipe Lemef0823852016-06-08 13:43:08 -0700425 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800426 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
427 new SparseBooleanArray();
428
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700429 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700430 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800431 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700432 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700433 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800434 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700435
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700436 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700437 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400438 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700439
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700440 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700441 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800442 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700443
Jeff Sharkey32566012014-12-02 18:30:14 -0800444 private final RemoteCallbackList<INetworkPolicyListener>
445 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700446
Dianne Hackborn497175b2014-07-01 12:56:08 -0700447 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700448 @VisibleForTesting
449 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700450
451 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700452
Felipe Lemef0823852016-06-08 13:43:08 -0700453 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700454 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700455
Svet Ganov16a16892015-04-16 10:32:04 -0700456 private final AppOpsManager mAppOps;
457
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800458 private final IPackageManager mIPm;
459
Sudheer Shankae7361852017-03-07 11:51:46 -0800460 private ActivityManagerInternal mActivityManagerInternal;
461
462 /**
463 * This is used for debugging purposes. Whenever the IUidObserver.onUidStateChanged is called,
464 * the uid and procStateSeq will be written to this and will be printed as part of dump.
465 */
466 @VisibleForTesting
467 public ProcStateSeqHistory mObservedHistory
468 = new ProcStateSeqHistory(MAX_PROC_STATE_SEQ_HISTORY);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800469
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700470 // TODO: keep whitelist of system-critical services that should never have
471 // rules enforced, such as system, phone, and radio UIDs.
472
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700473 // TODO: migrate notifications to SystemUI
474
Jeff Sharkey75279902011-05-24 18:39:45 -0700475 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700476 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
477 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700478 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
479 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700480 }
481
482 private static File getSystemDir() {
483 return new File(Environment.getDataDirectory(), "system");
484 }
485
486 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700487 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700488 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700489 mContext = checkNotNull(context, "missing context");
490 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700491 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700492 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700493 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700494 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700495 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700496 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700497 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700498 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700499
Amith Yamasani450a16b2013-09-18 16:28:50 -0700500 HandlerThread thread = new HandlerThread(TAG);
501 thread.start();
502 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700503
Makoto Onuki8e777332017-03-28 11:25:47 -0700504 // We create another thread for the UID events, which are more time-critical.
505 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
506 /*allowIo=*/ false);
507 mUidEventThread.start();
508 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
509
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700510 mSuppressDefaultPolicy = suppressDefaultPolicy;
511
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700512 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700513
514 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800515
Felipe Lemed17fda42016-04-29 11:12:45 -0700516 // Expose private service for system components to use.
517 LocalServices.addService(NetworkPolicyManagerInternal.class,
518 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700519 }
520
521 public void bindConnectivityManager(IConnectivityManager connManager) {
522 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700523 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700524
Jeff Sharkey497e4432011-06-14 17:27:29 -0700525 public void bindNotificationManager(INotificationManager notifManager) {
526 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
527 }
528
Felipe Lemef0823852016-06-08 13:43:08 -0700529 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700530 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700531 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
532 mPowerSaveWhitelistExceptIdleAppIds.clear();
533 if (whitelist != null) {
534 for (int uid : whitelist) {
535 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
536 }
537 }
538 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700539 mPowerSaveWhitelistAppIds.clear();
540 if (whitelist != null) {
541 for (int uid : whitelist) {
542 mPowerSaveWhitelistAppIds.put(uid, true);
543 }
544 }
545 } catch (RemoteException e) {
546 }
547 }
548
Felipe Lemea9505cc2016-02-26 10:28:41 -0800549 /**
550 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
551 * revoke the whitelist.
552 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700553 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800554 */
Felipe Lemef0823852016-06-08 13:43:08 -0700555 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800556 final List<UserInfo> users = mUserManager.getUsers();
557 final int numberUsers = users.size();
558
Felipe Lemea110eec2016-04-29 09:58:06 -0700559 boolean changed = false;
560 for (int i = 0; i < numberUsers; i++) {
561 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700562 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700563 }
564 return changed;
565 }
566
Felipe Lemef0823852016-06-08 13:43:08 -0700567 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700568 final SystemConfig sysConfig = SystemConfig.getInstance();
569 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800570 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
571 boolean changed = false;
572 for (int i = 0; i < allowDataUsage.size(); i++) {
573 final String pkg = allowDataUsage.valueAt(i);
574 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700575 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
576 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800577 final ApplicationInfo app;
578 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700579 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800580 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700581 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
582 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800583 continue;
584 }
585 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700586 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
587 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800588 continue;
589 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700590 final int uid = UserHandle.getUid(userId, app.uid);
591 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
592 if (LOGD)
593 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
594 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800595 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700596 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700597 if (LOGD)
598 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
599 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700600 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700601 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800602 }
603 }
604 return changed;
605 }
606
Felipe Lemef0823852016-06-08 13:43:08 -0700607 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700608 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700609 // Clear the states of the current whitelist
610 final int N = mPowerSaveTempWhitelistAppIds.size();
611 for (int i = 0; i < N; i++) {
612 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
613 }
614 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700615 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700616 if (whitelist != null) {
617 for (int uid : whitelist) {
618 mPowerSaveTempWhitelistAppIds.put(uid, true);
619 }
620 }
621 } catch (RemoteException e) {
622 }
623 }
624
Amith Yamasani06f08062015-06-12 13:23:33 -0700625 /**
626 * Remove unnecessary entries in the temp whitelist
627 */
Felipe Lemef0823852016-06-08 13:43:08 -0700628 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700629 final int N = mPowerSaveTempWhitelistAppIds.size();
630 for (int i = N - 1; i >= 0; i--) {
631 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
632 mPowerSaveTempWhitelistAppIds.removeAt(i);
633 }
634 }
635 }
636
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800637 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700638 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800639 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700640 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800641 // Boost thread's priority during system server init
642 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700643 if (!isBandwidthControlEnabled()) {
644 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
645 return;
646 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700647
Felipe Leme873a83a2016-09-07 11:34:10 -0700648 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700649
Felipe Leme873a83a2016-09-07 11:34:10 -0700650 synchronized (mUidRulesFirstLock) {
651 synchronized (mNetworkPoliciesSecondLock) {
652 updatePowerSaveWhitelistUL();
653 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
654 mPowerManagerInternal.registerLowPowerModeObserver(
655 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800656 @Override
657 public int getServiceType() {
658 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700659 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800660
661 @Override
662 public void onLowPowerModeChanged(PowerSaveState result) {
663 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800664 if (LOGD) {
665 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
666 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800667 synchronized (mUidRulesFirstLock) {
668 if (mRestrictPower != enabled) {
669 mRestrictPower = enabled;
670 updateRulesForRestrictPowerUL();
671 }
672 }
673 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800674 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800675 mRestrictPower = mPowerManagerInternal.getLowPowerState(
676 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700677
678 mSystemReady = true;
679
680 // read policy from disk
681 readPolicyAL();
682
jackqdyulei29c82ab2017-03-10 14:09:16 -0800683 // Update the restrictBackground if battery saver is turned on
684 mRestrictBackgroundBeforeBsm = mRestrictBackground;
685 mRestrictBackgroundPowerState = mPowerManagerInternal
686 .getLowPowerState(ServiceType.DATA_SAVER);
687 final boolean localRestrictBackground =
688 mRestrictBackgroundPowerState.batterySaverEnabled;
689 if (localRestrictBackground && localRestrictBackground != mRestrictBackground) {
690 mRestrictBackground = localRestrictBackground;
691 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
692 mRestrictBackground ? 1 : 0, 0).sendToTarget();
693 }
694 mPowerManagerInternal.registerLowPowerModeObserver(
695 new PowerManagerInternal.LowPowerModeListener() {
696 @Override
697 public int getServiceType() {
698 return ServiceType.DATA_SAVER;
699 }
700
701 @Override
702 public void onLowPowerModeChanged(PowerSaveState result) {
703 synchronized (mUidRulesFirstLock) {
704 updateRestrictBackgroundByLowPowerModeUL(result);
705 }
706 }
707 });
708
Felipe Leme873a83a2016-09-07 11:34:10 -0700709 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
710 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700711 }
Felipe Lemef0823852016-06-08 13:43:08 -0700712
Felipe Leme873a83a2016-09-07 11:34:10 -0700713 setRestrictBackgroundUL(mRestrictBackground);
714 updateRulesForGlobalChangeAL(false);
715 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700716 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800717 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700718
Sudheer Shankae7361852017-03-07 11:51:46 -0800719 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700720 try {
721 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000722 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800723 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700724 mNetworkManager.registerObserver(mAlertObserver);
725 } catch (RemoteException e) {
726 // ignored; both services live in system_server
727 }
728
729 // listen for changes to power save whitelist
730 final IntentFilter whitelistFilter = new IntentFilter(
731 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
732 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
733
734 DeviceIdleController.LocalService deviceIdleService
735 = LocalServices.getService(DeviceIdleController.LocalService.class);
736 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
737
738 // watch for network interfaces to be claimed
739 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
740 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
741
742 // listen for package changes to update policy
743 final IntentFilter packageFilter = new IntentFilter();
744 packageFilter.addAction(ACTION_PACKAGE_ADDED);
745 packageFilter.addDataScheme("package");
746 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
747
748 // listen for UID changes to update policy
749 mContext.registerReceiver(
750 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
751
752 // listen for user changes to update policy
753 final IntentFilter userFilter = new IntentFilter();
754 userFilter.addAction(ACTION_USER_ADDED);
755 userFilter.addAction(ACTION_USER_REMOVED);
756 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
757
758 // listen for stats update events
759 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
760 mContext.registerReceiver(
761 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
762
763 // listen for restrict background changes from notifications
764 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
765 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
766
767 // listen for snooze warning from notifications
768 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
769 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
770 MANAGE_NETWORK_POLICY, mHandler);
771
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600772 // listen for configured wifi networks to be loaded
773 final IntentFilter wifiFilter =
774 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
775 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700776
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700777 // listen for carrier config changes to update data cycle information
778 final IntentFilter carrierConfigFilter = new IntentFilter(
779 ACTION_CARRIER_CONFIG_CHANGED);
780 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
781
Felipe Leme873a83a2016-09-07 11:34:10 -0700782 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800783 // tell systemReady() that the service has been initialized
784 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700785 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800786 // Restore the default priority after init is done
787 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700788 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700789 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700790 }
791
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800792 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
793 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
794 mHandler.post(() -> initService(initCompleteSignal));
795 return initCompleteSignal;
796 }
797
798 public void systemReady(CountDownLatch initCompleteSignal) {
799 // wait for initService to complete
800 try {
801 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
802 throw new IllegalStateException("Service " + TAG +" init timeout");
803 }
804 } catch (InterruptedException e) {
805 Thread.currentThread().interrupt();
806 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
807 }
808 }
809
Sudheer Shankac9d94072017-02-22 22:13:55 +0000810 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700811 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700812 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
813 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700814 }
815
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700816 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700817 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700818 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700819
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700820 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700821 }
822
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700823 @Override public void onUidIdle(int uid, boolean disabled) {
824 }
825
826 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700827 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700828 };
829
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700830 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700831 @Override
832 public void onReceive(Context context, Intent intent) {
833 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700834 synchronized (mUidRulesFirstLock) {
835 updatePowerSaveWhitelistUL();
836 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700837 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700838 }
839 }
840 };
841
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700842 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
843 @Override
844 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700845 synchronized (mUidRulesFirstLock) {
846 updatePowerSaveTempWhitelistUL();
847 updateRulesForTempWhitelistChangeUL();
848 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700849 }
850 }
851 };
852
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700853 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700854 @Override
855 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700856 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700857
858 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700859 final int uid = intent.getIntExtra(EXTRA_UID, -1);
860 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700861
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700862 if (ACTION_PACKAGE_ADDED.equals(action)) {
863 // update rules for UID, since it might be subject to
864 // global background data policy
865 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700866 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700867 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700868 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700869 }
870 }
871 };
872
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700873 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700874 @Override
875 public void onReceive(Context context, Intent intent) {
876 // on background handler thread, and UID_REMOVED is protected
877
878 final int uid = intent.getIntExtra(EXTRA_UID, -1);
879 if (uid == -1) return;
880
881 // remove any policy and update rules to clean up
882 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700883 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700884 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700885 synchronized (mNetworkPoliciesSecondLock) {
886 writePolicyAL();
887 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700888 }
889 }
890 };
891
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700892 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700893 @Override
894 public void onReceive(Context context, Intent intent) {
895 // on background handler thread, and USER_ADDED and USER_REMOVED
896 // broadcasts are protected
897
898 final String action = intent.getAction();
899 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
900 if (userId == -1) return;
901
Amith Yamasani15e472352015-04-24 19:06:07 -0700902 switch (action) {
903 case ACTION_USER_REMOVED:
904 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700905 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800906 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700907 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700908 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700909 if (action == ACTION_USER_ADDED) {
910 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700911 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700912 }
913 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700914 synchronized (mNetworkPoliciesSecondLock) {
915 updateRulesForGlobalChangeAL(true);
916 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700917 }
918 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700919 }
920 }
921 };
922
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700923 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700924 * Receiver that watches for {@link INetworkStatsService} updates, which we
925 * use to check against {@link NetworkPolicy#warningBytes}.
926 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700927 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700928 @Override
929 public void onReceive(Context context, Intent intent) {
930 // on background handler thread, and verified
931 // READ_NETWORK_USAGE_HISTORY permission above.
932
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800933 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700934 synchronized (mNetworkPoliciesSecondLock) {
935 updateNetworkEnabledNL();
936 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700937 }
938 }
939 };
940
941 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700942 * Receiver that watches for {@link Notification} control of
943 * {@link #mRestrictBackground}.
944 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700945 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700946 @Override
947 public void onReceive(Context context, Intent intent) {
948 // on background handler thread, and verified MANAGE_NETWORK_POLICY
949 // permission above.
950
951 setRestrictBackground(false);
952 }
953 };
954
955 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800956 * Receiver that watches for {@link Notification} control of
957 * {@link NetworkPolicy#lastWarningSnooze}.
958 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700959 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800960 @Override
961 public void onReceive(Context context, Intent intent) {
962 // on background handler thread, and verified MANAGE_NETWORK_POLICY
963 // permission above.
964
965 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
966 performSnooze(template, TYPE_WARNING);
967 }
968 };
969
970 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600971 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -0600972 * we can perform upgrade logic. After initial upgrade logic, it updates
973 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700974 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600975 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700976 @Override
977 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900978 synchronized (mUidRulesFirstLock) {
979 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600980 upgradeWifiMeteredOverrideAL();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -0600981 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700982 }
983 }
984 }
985 };
986
987 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700988 * Observer that watches for {@link INetworkManagementService} alerts.
989 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700990 final private INetworkManagementEventObserver mAlertObserver
991 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700992 @Override
993 public void limitReached(String limitName, String iface) {
994 // only someone like NMS should be calling us
995 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
996
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800997 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
998 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700999 }
1000 }
1001 };
1002
1003 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001004 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1005 * to show visible notifications as needed.
1006 */
Felipe Lemef0823852016-06-08 13:43:08 -07001007 void updateNotificationsNL() {
1008 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001009
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001010 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001011 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001012 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001013
1014 // TODO: when switching to kernel notifications, compute next future
1015 // cycle boundary to recompute notifications.
1016
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001017 // examine stats for each active policy
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001018 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1019 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001020 // ignore policies that aren't relevant to user
1021 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001022 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001023
Jeff Sharkey53313d72017-07-13 16:47:32 -06001024 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1025 .cycleIterator(policy).next();
1026 final long start = cycle.first.toInstant().toEpochMilli();
1027 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001028 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001029
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001030 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001031 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001032 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1033 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001034 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001035 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001036 }
1037
Jeff Sharkey497e4432011-06-14 17:27:29 -07001038 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001039 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001040
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001041 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001042 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001043 }
1044 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001045 }
1046
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001047 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001048 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001049 final NotificationId notificationId = beforeNotifs.valueAt(i);
1050 if (!mActiveNotifs.contains(notificationId)) {
1051 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001052 }
1053 }
1054 }
1055
1056 /**
1057 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001058 * current device state, such as when
1059 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1060 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001061 */
1062 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001063 if (template.isMatchRuleMobile()) {
1064 final TelephonyManager tele = TelephonyManager.from(mContext);
1065 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001066
Jeff Sharkey32566012014-12-02 18:30:14 -08001067 // Mobile template is relevant when any active subscriber matches
1068 final int[] subIds = sub.getActiveSubscriptionIdList();
1069 for (int subId : subIds) {
1070 final String subscriberId = tele.getSubscriberId(subId);
1071 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001072 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001073 if (template.matches(probeIdent)) {
1074 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001075 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001076 }
1077 return false;
1078 } else {
1079 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001080 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001081 }
1082
1083 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001084 * Notify that given {@link NetworkTemplate} is over
1085 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1086 */
Felipe Lemef0823852016-06-08 13:43:08 -07001087 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001088 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001089 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001090 mOverLimitNotified.add(template);
1091 }
1092 }
1093
Felipe Lemef0823852016-06-08 13:43:08 -07001094 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001095 mOverLimitNotified.remove(template);
1096 }
1097
1098 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001099 * Show notification for combined {@link NetworkPolicy} and specific type,
1100 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1101 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001102 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001103 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001104 final Notification.Builder builder =
1105 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001106 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001107 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001108 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001109 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001110
1111 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001112 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001113 switch (type) {
1114 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001115 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001116 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001117
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001118 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001119 builder.setTicker(title);
1120 builder.setContentTitle(title);
1121 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001122 builder.setDefaults(Notification.DEFAULT_ALL);
Julia Reynoldsbad42972017-04-25 13:52:49 -04001123 builder.setChannelId(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001124
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001125 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1126 builder.setDeleteIntent(PendingIntent.getBroadcast(
1127 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1128
Wei Liu546cb772016-07-21 16:19:01 -07001129 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001130 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001131 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1132
Jeff Sharkey497e4432011-06-14 17:27:29 -07001133 break;
1134 }
1135 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001136 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001137
1138 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001139 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001140 switch (policy.template.getMatchRule()) {
1141 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001142 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001143 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001144 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001145 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001146 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001147 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001148 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001149 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001150 case MATCH_WIFI:
1151 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001152 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001153 break;
1154 default:
1155 title = null;
1156 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001157 }
1158
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001159 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001160 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001161 builder.setTicker(title);
1162 builder.setContentTitle(title);
1163 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001164
Wei Liu546cb772016-07-21 16:19:01 -07001165 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001166 builder.setContentIntent(PendingIntent.getActivity(
1167 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1168 break;
1169 }
1170 case TYPE_LIMIT_SNOOZED: {
1171 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001172 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001173 Formatter.formatFileSize(mContext, overBytes));
1174
1175 final CharSequence title;
1176 switch (policy.template.getMatchRule()) {
1177 case MATCH_MOBILE_3G_LOWER:
1178 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1179 break;
1180 case MATCH_MOBILE_4G:
1181 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1182 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001183 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001184 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1185 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001186 case MATCH_WIFI:
1187 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1188 break;
1189 default:
1190 title = null;
1191 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001192 }
1193
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001194 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001195 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001196 builder.setTicker(title);
1197 builder.setContentTitle(title);
1198 builder.setContentText(body);
1199
Wei Liu546cb772016-07-21 16:19:01 -07001200 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001201 builder.setContentIntent(PendingIntent.getActivity(
1202 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001203 break;
1204 }
1205 }
1206
1207 // TODO: move to NotificationManager once we can mock it
1208 try {
1209 final String packageName = mContext.getPackageName();
Chris Wren193ae6b2017-03-31 15:17:11 -04001210 if (!TextUtils.isEmpty(body)) {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001211 builder.setStyle(new Notification.BigTextStyle()
1212 .bigText(body));
1213 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001214 mNotifManager.enqueueNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001215 packageName, packageName, notificationId.getTag(), notificationId.getId(),
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001216 builder.build(), UserHandle.USER_ALL);
Chris Wren193ae6b2017-03-31 15:17:11 -04001217 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001218 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001219 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001220 }
1221 }
1222
Chris Wren193ae6b2017-03-31 15:17:11 -04001223 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001224 // TODO: move to NotificationManager once we can mock it
1225 try {
1226 final String packageName = mContext.getPackageName();
1227 mNotifManager.cancelNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001228 packageName, notificationId.getTag(), notificationId.getId(),
1229 UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001230 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001231 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001232 }
1233 }
1234
1235 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001236 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001237 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001238 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001239 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001240 @Override
1241 public void onReceive(Context context, Intent intent) {
1242 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1243 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001244
1245 maybeRefreshTrustedTime();
Hugo Benichi446c9c92017-04-10 09:41:10 +09001246 synchronized (mUidRulesFirstLock) {
1247 synchronized (mNetworkPoliciesSecondLock) {
1248 ensureActiveMobilePolicyAL();
1249 normalizePoliciesNL();
1250 updateNetworkEnabledNL();
1251 updateNetworkRulesNL();
1252 updateNotificationsNL();
1253 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001254 }
1255 }
1256 };
1257
1258 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001259 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1260 * if necessary.
1261 *
1262 * @param subId that has its associated NetworkPolicy updated if necessary
1263 * @return if any policies were updated
1264 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001265 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1266 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001267
1268 boolean policyUpdated = false;
1269 final String subscriberId = TelephonyManager.from(mContext).getSubscriberId(subId);
1270
1271 // find and update the mobile NetworkPolicy for this subscriber id
1272 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1273 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1274 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1275 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1276 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001277 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1278 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001279 }
1280 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001281 return policyUpdated;
1282 }
1283
1284 /**
1285 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1286 *
1287 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1288 * to do so, it returns the fallback value.
1289 *
1290 * @param config The CarrierConfig to read the value from.
1291 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1292 * @return cycleDay to use in the mobile NetworkPolicy.
1293 */
1294 @VisibleForTesting
1295 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1296 int fallbackCycleDay) {
1297 if (config == null) {
1298 return fallbackCycleDay;
1299 }
1300 int cycleDay =
1301 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1302 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1303 return fallbackCycleDay;
1304 }
1305 // validate cycleDay value
1306 final Calendar cal = Calendar.getInstance();
1307 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1308 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1309 Slog.e(TAG, "Invalid date in "
1310 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1311 return fallbackCycleDay;
1312 }
1313 return cycleDay;
1314 }
1315
1316 /**
1317 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1318 *
1319 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1320 * to do so, it returns the fallback value.
1321 *
1322 * @param config The CarrierConfig to read the value from.
1323 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1324 * @return warningBytes to use in the mobile NetworkPolicy.
1325 */
1326 @VisibleForTesting
1327 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1328 long fallbackWarningBytes) {
1329 if (config == null) {
1330 return fallbackWarningBytes;
1331 }
1332 long warningBytes =
1333 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1334
1335 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1336 return WARNING_DISABLED;
1337 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1338 return getPlatformDefaultWarningBytes();
1339 } else if (warningBytes < 0) {
1340 Slog.e(TAG, "Invalid value in "
1341 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1342 + "non-negative value but got: " + warningBytes);
1343 return fallbackWarningBytes;
1344 }
1345
1346 return warningBytes;
1347 }
1348
1349 /**
1350 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1351 *
1352 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1353 * to do so, it returns the fallback value.
1354 *
1355 * @param config The CarrierConfig to read the value from.
1356 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1357 * @return limitBytes to use in the mobile NetworkPolicy.
1358 */
1359 @VisibleForTesting
1360 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1361 long fallbackLimitBytes) {
1362 if (config == null) {
1363 return fallbackLimitBytes;
1364 }
1365 long limitBytes =
1366 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1367
1368 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1369 return LIMIT_DISABLED;
1370 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1371 return getPlatformDefaultLimitBytes();
1372 } else if (limitBytes < 0) {
1373 Slog.e(TAG, "Invalid value in "
1374 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1375 + "non-negative value but got: " + limitBytes);
1376 return fallbackLimitBytes;
1377 }
1378 return limitBytes;
1379 }
1380
1381 /**
1382 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1383 */
1384 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1385 @Override
1386 public void onReceive(Context context, Intent intent) {
1387 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1388 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1389
1390 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1391 return;
1392 }
1393 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
1394 final TelephonyManager tele = TelephonyManager.from(mContext);
1395 final String subscriberId = tele.getSubscriberId(subId);
1396
1397 maybeRefreshTrustedTime();
1398 synchronized (mUidRulesFirstLock) {
1399 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001400 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001401 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001402 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001403 if (!updated) return;
1404 // update network and notification rules, as the data cycle changed and it's
1405 // possible that we should be triggering warnings/limits now
1406 handleNetworkPoliciesUpdateAL(true);
1407 }
1408 }
1409 }
1410 };
1411
1412 /**
1413 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1414 * one has been updated.
1415 *
1416 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1417 * update.
1418 */
1419 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1420 if (shouldNormalizePolicies) {
1421 normalizePoliciesNL();
1422 }
1423 updateNetworkEnabledNL();
1424 updateNetworkRulesNL();
1425 updateNotificationsNL();
1426 writePolicyAL();
1427 }
1428
1429 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001430 * Proactively control network data connections when they exceed
1431 * {@link NetworkPolicy#limitBytes}.
1432 */
Felipe Lemef0823852016-06-08 13:43:08 -07001433 void updateNetworkEnabledNL() {
1434 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001435
1436 // TODO: reset any policy-disabled networks when any policy is removed
1437 // completely, which is currently rare case.
1438
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001439 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1440 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001441 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001442 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001443 setNetworkTemplateEnabled(policy.template, true);
1444 continue;
1445 }
1446
Jeff Sharkey53313d72017-07-13 16:47:32 -06001447 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1448 .cycleIterator(policy).next();
1449 final long start = cycle.first.toInstant().toEpochMilli();
1450 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001451 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001452
1453 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001454 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1455 && policy.lastLimitSnooze < start;
1456 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001457
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001458 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001459 }
1460 }
1461
1462 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001463 * Proactively disable networks that match the given
1464 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001465 */
1466 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001467 // TODO: reach into ConnectivityManager to proactively disable bringing
1468 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001469
1470 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1471 // If mobile data usage hits the limit or if the user resumes the data, we need to
1472 // notify telephony.
1473 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1474 final TelephonyManager tm = TelephonyManager.from(mContext);
1475
1476 final int[] subIds = sm.getActiveSubscriptionIdList();
1477 for (int subId : subIds) {
1478 final String subscriberId = tm.getSubscriberId(subId);
1479 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1480 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1481 // Template is matched when subscriber id matches.
1482 if (template.matches(probeIdent)) {
1483 tm.setPolicyDataEnabled(enabled, subId);
1484 }
1485 }
1486 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001487 }
1488
1489 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001490 * Collect all ifaces from a {@link NetworkState} into the given set.
1491 */
1492 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1493 final String baseIface = state.linkProperties.getInterfaceName();
1494 if (baseIface != null) {
1495 ifaces.add(baseIface);
1496 }
1497 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1498 final String stackedIface = stackedLink.getInterfaceName();
1499 if (stackedIface != null) {
1500 ifaces.add(stackedIface);
1501 }
1502 }
1503 }
1504
1505 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001506 * Examine all connected {@link NetworkState}, looking for
1507 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1508 * remaining quota based on usage cycle and historical stats.
1509 */
Felipe Lemef0823852016-06-08 13:43:08 -07001510 void updateNetworkRulesNL() {
1511 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001512
1513 final NetworkState[] states;
1514 try {
1515 states = mConnManager.getAllNetworkState();
1516 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001517 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001518 return;
1519 }
1520
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001521 // First, generate identities of all connected networks so we can
1522 // quickly compare them against all defined policies below.
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001523 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001524 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001525 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001526 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001527 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001528 }
1529 }
1530
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001531 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001532 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001533
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001534 // For every well-defined policy, compute remaining data based on
1535 // current cycle and historical stats, and push to kernel.
1536 final ArraySet<String> matchingIfaces = new ArraySet<>();
1537 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1538 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1539
1540 // Collect all ifaces that match this policy
1541 matchingIfaces.clear();
1542 for (int j = identified.size() - 1; j >= 0; j--) {
1543 if (policy.template.matches(identified.valueAt(j))) {
1544 collectIfaces(matchingIfaces, identified.keyAt(j));
1545 }
1546 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001547
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001548 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001549 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001550 }
1551
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001552 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001553 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001554 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001555 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001556 if (hasLimit && policy.hasCycle()) {
1557 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1558 .cycleIterator(policy).next();
1559 final long start = cycle.first.toInstant().toEpochMilli();
1560 final long end = cycle.second.toInstant().toEpochMilli();
1561 final long totalBytes = getTotalBytes(policy.template, start, end);
1562
1563 if (policy.lastLimitSnooze >= start) {
1564 // snoozing past quota, but we still need to restrict apps,
1565 // so push really high quota.
1566 quotaBytes = Long.MAX_VALUE;
1567 } else {
1568 // remaining "quota" bytes are based on total usage in
1569 // current cycle. kernel doesn't like 0-byte rules, so we
1570 // set 1-byte quota and disable the radio later.
1571 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1572 }
1573 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001574 // metered network, but no policy limit; we still need to
1575 // restrict apps, so push really high quota.
1576 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001577 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001578
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001579 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001580 // TODO: switch to shared quota once NMS supports
1581 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001582 }
1583
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001584 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1585 final String iface = matchingIfaces.valueAt(j);
1586 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001587 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001588 }
1589 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001590
1591 // keep track of lowest warning or limit of active policies
1592 if (hasWarning && policy.warningBytes < lowestRule) {
1593 lowestRule = policy.warningBytes;
1594 }
1595 if (hasLimit && policy.limitBytes < lowestRule) {
1596 lowestRule = policy.limitBytes;
1597 }
1598 }
1599
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001600 // One final pass to catch any metered ifaces that don't have explicitly
1601 // defined policies; typically Wi-Fi networks.
1602 for (NetworkState state : states) {
1603 if (state.networkInfo != null && state.networkInfo.isConnected()
1604 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1605 matchingIfaces.clear();
1606 collectIfaces(matchingIfaces, state);
1607 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1608 final String iface = matchingIfaces.valueAt(j);
1609 if (!newMeteredIfaces.contains(iface)) {
1610 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1611 newMeteredIfaces.add(iface);
1612 }
1613 }
1614 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001615 }
1616
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001617 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001618 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1619 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001620 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001621 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001622 }
1623 }
1624 mMeteredIfaces = newMeteredIfaces;
1625
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001626 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001627 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001628
1629 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001630 }
1631
1632 /**
1633 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1634 * have at least a default mobile policy defined.
1635 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001636 private void ensureActiveMobilePolicyAL() {
1637 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001638 if (mSuppressDefaultPolicy) return;
1639
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001640 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001641 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001642
Jeff Sharkey32566012014-12-02 18:30:14 -08001643 final int[] subIds = sub.getActiveSubscriptionIdList();
1644 for (int subId : subIds) {
1645 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001646 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001647 }
1648 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001649
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001650 /**
1651 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1652 * have at least a default mobile policy defined.
1653 *
1654 * @param subId to build a default policy for
1655 * @param subscriberId that we check for an existing policy
1656 * @return true if a mobile network policy was added, or false one already existed.
1657 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001658 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001659 // Poke around to see if we already have a policy
1660 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001661 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001662 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1663 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1664 if (template.matches(probeIdent)) {
1665 if (LOGD) {
1666 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1667 + NetworkIdentity.scrubSubscriberId(subscriberId));
1668 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001669 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001670 }
1671 }
1672
Jeff Sharkey32566012014-12-02 18:30:14 -08001673 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1674 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001675 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001676 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001677 return true;
1678 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001679
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001680 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001681 final int dataWarningConfig = mContext.getResources().getInteger(
1682 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001683 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001684 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001685 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001686 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001687 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001688 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001689
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001690 private long getPlatformDefaultLimitBytes() {
1691 return LIMIT_DISABLED;
1692 }
1693
1694 @VisibleForTesting
1695 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001696 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001697 final RecurrenceRule cycleRule = NetworkPolicy
1698 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001699 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001700 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1701 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1702 synchronized (mUidRulesFirstLock) {
1703 synchronized (mNetworkPoliciesSecondLock) {
1704 updateDefaultMobilePolicyAL(subId, policy);
1705 }
1706 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001707 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001708 }
1709
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001710 /**
1711 * Update the given {@link NetworkPolicy} based on any carrier-provided
1712 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1713 * Leaves policy untouched if the user has modified it.
1714 *
1715 * @return if the policy was modified
1716 */
1717 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1718 if (!policy.inferred) {
1719 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1720 return false;
1721 }
1722
1723 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1724 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1725 policy.lastLimitSnooze, policy.metered, policy.inferred);
1726
1727 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1728 if (!ArrayUtils.isEmpty(plans)) {
1729 final SubscriptionPlan plan = plans[0];
1730 policy.cycleRule = plan.getCycleRule();
1731 final long planLimitBytes = plan.getDataLimitBytes();
1732 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1733 policy.warningBytes = getPlatformDefaultWarningBytes();
1734 policy.limitBytes = getPlatformDefaultLimitBytes();
1735 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1736 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1737 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1738 } else {
1739 policy.warningBytes = (planLimitBytes * 9) / 10;
1740 switch (plan.getDataLimitBehavior()) {
1741 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1742 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1743 policy.limitBytes = planLimitBytes;
1744 break;
1745 default:
1746 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1747 break;
1748 }
1749 }
1750 } else {
1751 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1752 final int currentCycleDay;
1753 if (policy.cycleRule.isMonthly()) {
1754 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1755 } else {
1756 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1757 }
1758 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1759 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1760 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1761 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1762 }
1763
1764 if (policy.equals(original)) {
1765 return false;
1766 } else {
1767 Slog.d(TAG, "Updated " + original + " to " + policy);
1768 return true;
1769 }
1770 }
1771
Felipe Lemef0823852016-06-08 13:43:08 -07001772 private void readPolicyAL() {
1773 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001774
1775 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001776 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001777 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001778 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001779 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001780
1781 FileInputStream fis = null;
1782 try {
1783 fis = mPolicyFile.openRead();
1784 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001785 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001786
Felipe Leme46b451f2016-08-19 08:46:17 -07001787 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1788 // to skip UIDs that were explicitly blacklisted.
1789 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1790
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001791 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001792 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001793 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001794 while ((type = in.next()) != END_DOCUMENT) {
1795 final String tag = in.getName();
1796 if (type == START_TAG) {
1797 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001798 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001799 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001800 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1801 mRestrictBackground = readBooleanAttribute(
1802 in, ATTR_RESTRICT_BACKGROUND);
1803 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001804 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001805 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001806 if (mRestrictBackground != oldValue) {
1807 // Some early services may have read the default value,
1808 // so notify them that it's changed
1809 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1810 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1811 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001812
1813 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1814 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1815 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001816 final String networkId;
1817 if (version >= VERSION_ADDED_NETWORK_ID) {
1818 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1819 } else {
1820 networkId = null;
1821 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001822 final RecurrenceRule cycleRule;
1823 if (version >= VERSION_ADDED_CYCLE) {
1824 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1825 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1826 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1827 cycleRule = new RecurrenceRule(
1828 RecurrenceRule.convertZonedDateTime(start),
1829 RecurrenceRule.convertZonedDateTime(end),
1830 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001831 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001832 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1833 final String cycleTimezone;
1834 if (version >= VERSION_ADDED_TIMEZONE) {
1835 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1836 } else {
1837 cycleTimezone = "UTC";
1838 }
1839 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001840 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001841 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1842 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001843 final long lastLimitSnooze;
1844 if (version >= VERSION_SPLIT_SNOOZE) {
1845 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1846 } else if (version >= VERSION_ADDED_SNOOZE) {
1847 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001848 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001849 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001850 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001851 final boolean metered;
1852 if (version >= VERSION_ADDED_METERED) {
1853 metered = readBooleanAttribute(in, ATTR_METERED);
1854 } else {
1855 switch (networkTemplate) {
1856 case MATCH_MOBILE_3G_LOWER:
1857 case MATCH_MOBILE_4G:
1858 case MATCH_MOBILE_ALL:
1859 metered = true;
1860 break;
1861 default:
1862 metered = false;
1863 }
1864 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001865 final long lastWarningSnooze;
1866 if (version >= VERSION_SPLIT_SNOOZE) {
1867 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1868 } else {
1869 lastWarningSnooze = SNOOZE_NEVER;
1870 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001871 final boolean inferred;
1872 if (version >= VERSION_ADDED_INFERRED) {
1873 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1874 } else {
1875 inferred = false;
1876 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001877
Jeff Sharkey32566012014-12-02 18:30:14 -08001878 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1879 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001880 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001881 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
1882 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001883 lastLimitSnooze, metered, inferred));
1884 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001885
1886 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
1887 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1888 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1889 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1890 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
1891 RecurrenceRule.convertZonedDateTime(start),
1892 RecurrenceRule.convertZonedDateTime(end),
1893 RecurrenceRule.convertPeriod(period));
1894 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
1895 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
1896
1897 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
1898 SubscriptionPlan.BYTES_UNKNOWN);
1899 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
1900 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
1901 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
1902 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
1903 builder.setDataLimit(limitBytes, limitBehavior);
1904 }
1905
1906 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
1907 SubscriptionPlan.BYTES_UNKNOWN);
1908 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
1909 SubscriptionPlan.TIME_UNKNOWN);
1910 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
1911 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
1912 builder.setDataUsage(usageBytes, usageTime);
1913 }
1914
1915 final int subId = readIntAttribute(in, ATTR_SUB_ID);
1916 final SubscriptionPlan plan = builder.build();
1917 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
1918 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
1919
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001920 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
1921 mSubscriptionPlansOwner.put(subId, ownerPackage);
1922
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001923 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001924 final int uid = readIntAttribute(in, ATTR_UID);
1925 final int policy = readIntAttribute(in, ATTR_POLICY);
1926
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001927 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001928 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001929 } else {
1930 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1931 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001932 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001933 final int appId = readIntAttribute(in, ATTR_APP_ID);
1934 final int policy = readIntAttribute(in, ATTR_POLICY);
1935
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001936 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001937 // app policy is deprecated so this is only used in pre system user split.
1938 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001939 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001940 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001941 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001942 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001943 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001944 } else if (TAG_WHITELIST.equals(tag)) {
1945 insideWhitelist = true;
1946 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1947 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001948 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001949 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1950 final int uid = readIntAttribute(in, ATTR_UID);
1951 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001952 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001953 } else if (type == END_TAG) {
1954 if (TAG_WHITELIST.equals(tag)) {
1955 insideWhitelist = false;
1956 }
1957
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001958 }
1959 }
1960
Felipe Leme46b451f2016-08-19 08:46:17 -07001961 final int size = whitelistedRestrictBackground.size();
1962 for (int i = 0; i < size; i++) {
1963 final int uid = whitelistedRestrictBackground.keyAt(i);
1964 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1965 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1966 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1967 + " because its policy is " + uidPoliciesToString(policy));
1968 continue;
1969 }
1970 if (UserHandle.isApp(uid)) {
1971 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1972 if (LOGV)
1973 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1974 setUidPolicyUncheckedUL(uid, newPolicy, false);
1975 } else {
1976 Slog.w(TAG, "unable to update policy on UID " + uid);
1977 }
1978 }
1979
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001980 } catch (FileNotFoundException e) {
1981 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001982 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001983 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001984 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001985 } finally {
1986 IoUtils.closeQuietly(fis);
1987 }
1988 }
1989
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001990 /**
1991 * Upgrade legacy background data flags, notifying listeners of one last
1992 * change to always-true.
1993 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001994 private void upgradeDefaultBackgroundDataUL() {
1995 // This method is only called when we're unable to find the network policy flag, which
1996 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001997
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001998 // Seed from the default value configured for this device.
1999 mRestrictBackground = Settings.Global.getInt(
2000 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2001
2002 // NOTE: We used to read the legacy setting here :
2003 //
2004 // final int legacyFlagValue = Settings.Secure.getInt(
2005 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2006 //
2007 // This is no longer necessary because we will never upgrade directly from Gingerbread
2008 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2009 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002010 }
2011
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002012 /**
2013 * Perform upgrade step of moving any user-defined meterness overrides over
2014 * into {@link WifiConfiguration}.
2015 */
2016 private void upgradeWifiMeteredOverrideAL() {
2017 boolean modified = false;
2018 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2019 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2020 for (int i = 0; i < mNetworkPolicy.size(); ) {
2021 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2022 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2023 && !policy.inferred) {
2024 mNetworkPolicy.removeAt(i);
2025 modified = true;
2026
2027 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2028 for (WifiConfiguration config : configs) {
2029 if (Objects.equals(resolveNetworkId(config), networkId)) {
2030 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2031 config.meteredOverride = policy.metered
2032 ? WifiConfiguration.METERED_OVERRIDE_METERED
2033 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2034 wm.updateNetwork(config);
2035 }
2036 }
2037 } else {
2038 i++;
2039 }
2040 }
2041 if (modified) {
2042 writePolicyAL();
2043 }
2044 }
2045
Felipe Lemef0823852016-06-08 13:43:08 -07002046 void writePolicyAL() {
2047 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002048
2049 FileOutputStream fos = null;
2050 try {
2051 fos = mPolicyFile.startWrite();
2052
2053 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002054 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002055 out.startDocument(null, true);
2056
2057 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002058 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002059 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002060
2061 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002062 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2063 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002064 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002065 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002066
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002067 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002068 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2069 final String subscriberId = template.getSubscriberId();
2070 if (subscriberId != null) {
2071 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002072 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002073 final String networkId = template.getNetworkId();
2074 if (networkId != null) {
2075 out.attribute(null, ATTR_NETWORK_ID, networkId);
2076 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002077 writeStringAttribute(out, ATTR_CYCLE_START,
2078 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2079 writeStringAttribute(out, ATTR_CYCLE_END,
2080 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2081 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2082 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002083 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2084 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002085 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2086 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002087 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002088 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002089 out.endTag(null, TAG_NETWORK_POLICY);
2090 }
2091
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002092 // write all known subscription plans
2093 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2094 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002095 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002096 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2097 if (ArrayUtils.isEmpty(plans)) continue;
2098
2099 for (SubscriptionPlan plan : plans) {
2100 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2101 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002102 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002103 final RecurrenceRule cycleRule = plan.getCycleRule();
2104 writeStringAttribute(out, ATTR_CYCLE_START,
2105 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2106 writeStringAttribute(out, ATTR_CYCLE_END,
2107 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2108 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2109 RecurrenceRule.convertPeriod(cycleRule.period));
2110 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2111 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2112 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2113 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2114 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2115 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2116 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2117 }
2118 }
2119
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002120 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002121 for (int i = 0; i < mUidPolicy.size(); i++) {
2122 final int uid = mUidPolicy.keyAt(i);
2123 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002124
Jeff Sharkey497e4432011-06-14 17:27:29 -07002125 // skip writing empty policies
2126 if (policy == POLICY_NONE) continue;
2127
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002128 out.startTag(null, TAG_UID_POLICY);
2129 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002130 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002131 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002132 }
2133
2134 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002135
2136 // write all whitelists
2137 out.startTag(null, TAG_WHITELIST);
2138
Felipe Lemea9505cc2016-02-26 10:28:41 -08002139 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002140 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002141 for (int i = 0; i < size; i++) {
2142 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2143 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2144 writeIntAttribute(out, ATTR_UID, uid);
2145 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2146 }
2147
Felipe Lemeb85a6372016-01-14 16:16:16 -08002148 out.endTag(null, TAG_WHITELIST);
2149
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002150 out.endDocument();
2151
2152 mPolicyFile.finishWrite(fos);
2153 } catch (IOException e) {
2154 if (fos != null) {
2155 mPolicyFile.failWrite(fos);
2156 }
2157 }
2158 }
2159
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002160 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002161 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002162 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002163
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002164 if (!UserHandle.isApp(uid)) {
2165 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002166 }
Felipe Lemef0823852016-06-08 13:43:08 -07002167 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002168 final long token = Binder.clearCallingIdentity();
2169 try {
2170 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2171 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002172 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002173 }
2174 } finally {
2175 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002176 }
2177 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002178 }
2179
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002180 @Override
2181 public void addUidPolicy(int uid, int policy) {
2182 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002183
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002184 if (!UserHandle.isApp(uid)) {
2185 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2186 }
2187
Felipe Lemef0823852016-06-08 13:43:08 -07002188 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002189 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2190 policy |= oldPolicy;
2191 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002192 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002193 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002194 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002195 }
2196
2197 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002198 public void removeUidPolicy(int uid, int policy) {
2199 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2200
2201 if (!UserHandle.isApp(uid)) {
2202 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2203 }
2204
Felipe Lemef0823852016-06-08 13:43:08 -07002205 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002206 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2207 policy = oldPolicy & ~policy;
2208 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002209 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002210 }
2211 }
2212 }
2213
Felipe Lemef0823852016-06-08 13:43:08 -07002214 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2215 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002216
Felipe Leme57e3d312016-08-23 14:42:52 -07002217 final boolean notifyApp;
2218 if (!isUidValidForWhitelistRules(uid)) {
2219 notifyApp = false;
2220 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002221 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2222 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2223 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2224 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002225 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2226 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002227 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2228 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2229 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2230 if (LOGD)
2231 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2232 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2233 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002234 notifyApp = wasBlocked != isBlocked;
2235 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002236 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2237 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002238 }
2239
Felipe Lemef0823852016-06-08 13:43:08 -07002240 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002241 if (policy == POLICY_NONE) {
2242 mUidPolicy.delete(uid);
2243 } else {
2244 mUidPolicy.put(uid, policy);
2245 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002246
2247 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002248 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002249 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002250 synchronized (mNetworkPoliciesSecondLock) {
2251 writePolicyAL();
2252 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002253 }
2254 }
2255
2256 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002257 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002258 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2259
Felipe Lemef0823852016-06-08 13:43:08 -07002260 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002261 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002262 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002263 }
2264
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002265 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002266 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002267 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2268
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002269 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002270 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002271 for (int i = 0; i < mUidPolicy.size(); i++) {
2272 final int uid = mUidPolicy.keyAt(i);
2273 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002274 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2275 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002276 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002277 }
2278 }
2279 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002280 return uids;
2281 }
2282
2283 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002284 * Removes any persistable state associated with given {@link UserHandle}, persisting
2285 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002286 */
Felipe Lemef0823852016-06-08 13:43:08 -07002287 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002288
Felipe Lemef0823852016-06-08 13:43:08 -07002289 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07002290 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002291
Felipe Lemea110eec2016-04-29 09:58:06 -07002292 // Remove entries from revoked default restricted background UID whitelist
2293 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2294 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2295 if (UserHandle.getUserId(uid) == userId) {
2296 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002297 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002298 }
2299 }
2300
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002301 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002302 int[] uids = new int[0];
2303 for (int i = 0; i < mUidPolicy.size(); i++) {
2304 final int uid = mUidPolicy.keyAt(i);
2305 if (UserHandle.getUserId(uid) == userId) {
2306 uids = appendInt(uids, uid);
2307 }
2308 }
2309
2310 if (uids.length > 0) {
2311 for (int uid : uids) {
2312 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002313 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002314 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002315 }
Felipe Lemef0823852016-06-08 13:43:08 -07002316 synchronized (mNetworkPoliciesSecondLock) {
2317 updateRulesForGlobalChangeAL(true);
2318 if (writePolicy && changed) {
2319 writePolicyAL();
2320 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002321 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002322 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002323 }
2324
2325 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002326 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002327 // TODO: create permission for observing network policy
2328 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002329 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002330 }
2331
2332 @Override
2333 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002334 // TODO: create permission for observing network policy
2335 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002336 mListeners.unregister(listener);
2337 }
2338
Jeff Sharkey1b861272011-05-22 00:34:52 -07002339 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002340 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002341 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2342
Felipe Leme6a05eee2016-02-19 14:43:51 -08002343 final long token = Binder.clearCallingIdentity();
2344 try {
2345 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002346 synchronized (mUidRulesFirstLock) {
2347 synchronized (mNetworkPoliciesSecondLock) {
2348 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002349 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002350 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002351 }
2352 } finally {
2353 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002354 }
2355 }
2356
Hugo Benichi446c9c92017-04-10 09:41:10 +09002357 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002358 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002359 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2360 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002361 }
2362
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002363 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002364 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002365 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002366 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002367 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2368 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2369 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002370 } catch (SecurityException e) {
2371 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002372
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002373 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2374 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2375 return new NetworkPolicy[0];
2376 }
Svet Ganov16a16892015-04-16 10:32:04 -07002377 }
2378
Felipe Lemef0823852016-06-08 13:43:08 -07002379 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002380 final int size = mNetworkPolicy.size();
2381 final NetworkPolicy[] policies = new NetworkPolicy[size];
2382 for (int i = 0; i < size; i++) {
2383 policies[i] = mNetworkPolicy.valueAt(i);
2384 }
2385 return policies;
2386 }
2387 }
2388
Felipe Lemef0823852016-06-08 13:43:08 -07002389 private void normalizePoliciesNL() {
2390 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002391 }
2392
Felipe Lemef0823852016-06-08 13:43:08 -07002393 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002394 final TelephonyManager tele = TelephonyManager.from(mContext);
2395 final String[] merged = tele.getMergedSubscriberIds();
2396
2397 mNetworkPolicy.clear();
2398 for (NetworkPolicy policy : policies) {
2399 // When two normalized templates conflict, prefer the most
2400 // restrictive policy
2401 policy.template = NetworkTemplate.normalize(policy.template, merged);
2402 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2403 if (existing == null || existing.compareTo(policy) > 0) {
2404 if (existing != null) {
2405 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2406 }
2407 mNetworkPolicy.put(policy.template, policy);
2408 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002409 }
2410 }
2411
2412 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002413 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002414 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002415
2416 final long token = Binder.clearCallingIdentity();
2417 try {
2418 performSnooze(template, TYPE_LIMIT);
2419 } finally {
2420 Binder.restoreCallingIdentity(token);
2421 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002422 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002423
Dianne Hackborn497175b2014-07-01 12:56:08 -07002424 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002425 maybeRefreshTrustedTime();
2426 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002427 synchronized (mUidRulesFirstLock) {
2428 synchronized (mNetworkPoliciesSecondLock) {
2429 // find and snooze local policy that matches
2430 final NetworkPolicy policy = mNetworkPolicy.get(template);
2431 if (policy == null) {
2432 throw new IllegalArgumentException("unable to find policy for " + template);
2433 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002434
Felipe Lemef0823852016-06-08 13:43:08 -07002435 switch (type) {
2436 case TYPE_WARNING:
2437 policy.lastWarningSnooze = currentTime;
2438 break;
2439 case TYPE_LIMIT:
2440 policy.lastLimitSnooze = currentTime;
2441 break;
2442 default:
2443 throw new IllegalArgumentException("unexpected type");
2444 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002445
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002446 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002447 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002448 }
2449 }
2450
2451 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002452 public void onTetheringChanged(String iface, boolean tethering) {
2453 // No need to enforce permission because setRestrictBackground() will do it.
2454 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002455 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002456 if (mRestrictBackground && tethering) {
2457 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2458 setRestrictBackground(false);
2459 }
2460 }
2461 }
2462
2463 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002464 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002465 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002466 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002467 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2468 final long token = Binder.clearCallingIdentity();
2469 try {
2470 maybeRefreshTrustedTime();
2471 synchronized (mUidRulesFirstLock) {
2472 if (restrictBackground == mRestrictBackground) {
2473 // Ideally, UI should never allow this scenario...
2474 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2475 return;
2476 }
2477 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002478 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002479
2480 } finally {
2481 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002482 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002483
Felipe Leme29e72ea2016-09-08 13:26:55 -07002484 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2485 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002486 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002487 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002488 }
2489 }
2490
Felipe Lemef0823852016-06-08 13:43:08 -07002491 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002492 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002493 final boolean oldRestrictBackground = mRestrictBackground;
2494 mRestrictBackground = restrictBackground;
2495 // Must whitelist foreground apps before turning data saver mode on.
2496 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2497 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002498 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002499 try {
2500 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2501 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2502 mRestrictBackground = oldRestrictBackground;
2503 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002504 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002505 return;
2506 }
2507 } catch (RemoteException e) {
2508 // ignored; service lives in system_server
2509 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002510
2511 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2512 mRestrictBackgroundChangedInBsm = true;
2513 }
Felipe Lemef0823852016-06-08 13:43:08 -07002514 synchronized (mNetworkPoliciesSecondLock) {
2515 updateNotificationsNL();
2516 writePolicyAL();
2517 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002518 }
2519
Felipe Lemeb85a6372016-01-14 16:16:16 -08002520 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002521 public int getRestrictBackgroundByCaller() {
2522 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2523 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002524
Felipe Lemef0823852016-06-08 13:43:08 -07002525 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002526 // Must clear identity because getUidPolicy() is restricted to system.
2527 final long token = Binder.clearCallingIdentity();
2528 final int policy;
2529 try {
2530 policy = getUidPolicy(uid);
2531 } finally {
2532 Binder.restoreCallingIdentity(token);
2533 }
2534 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2535 // App is blacklisted.
2536 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2537 }
Felipe Leme1b103232016-01-22 09:44:57 -08002538 if (!mRestrictBackground) {
2539 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2540 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002541 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002542 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2543 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2544 }
2545 }
2546
2547 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002548 public boolean getRestrictBackground() {
2549 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2550
Felipe Lemef0823852016-06-08 13:43:08 -07002551 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002552 return mRestrictBackground;
2553 }
2554 }
2555
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002556 @Override
2557 public void setDeviceIdleMode(boolean enabled) {
2558 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002559 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2560 try {
2561 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002562 if (mDeviceIdleMode == enabled) {
2563 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002564 }
Felipe Lemeea014392016-09-06 13:59:54 -07002565 mDeviceIdleMode = enabled;
2566 if (mSystemReady) {
2567 // Device idle change means we need to rebuild rules for all
2568 // known apps, so do a global refresh.
2569 updateRulesForRestrictPowerUL();
2570 }
2571 }
2572 if (enabled) {
2573 EventLogTags.writeDeviceIdleOnPhase("net");
2574 } else {
2575 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002576 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002577 } finally {
2578 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002579 }
2580 }
2581
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002582 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002583 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2584 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002585 final long token = Binder.clearCallingIdentity();
2586 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002587 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2588 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2589 for (WifiConfiguration config : configs) {
2590 if (Objects.equals(resolveNetworkId(config), networkId)) {
2591 config.meteredOverride = meteredOverride;
2592 wm.updateNetwork(config);
2593 }
2594 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002595 } finally {
2596 Binder.restoreCallingIdentity(token);
2597 }
2598 }
2599
Jeff Sharkey46645002011-07-27 21:11:21 -07002600 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002601 @Deprecated
2602 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2603 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2604 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2605 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002606 }
2607
Jeff Sharkey53313d72017-07-13 16:47:32 -06002608 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2609 // Verify they're not lying about package name
2610 mAppOps.checkPackage(callingUid, callingPackage);
2611
Jeff Sharkey53313d72017-07-13 16:47:32 -06002612 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002613 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002614 final long token = Binder.clearCallingIdentity();
2615 try {
2616 si = mContext.getSystemService(SubscriptionManager.class)
2617 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002618 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002619 } finally {
2620 Binder.restoreCallingIdentity(token);
2621 }
2622
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002623 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002624 if (si != null) {
2625 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2626 return;
2627 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002628 }
2629
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002630 // Second check: has the CarrierService delegated access?
2631 if (config != null) {
2632 final String overridePackage = config
2633 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2634 if (!TextUtils.isEmpty(overridePackage)
2635 && Objects.equals(overridePackage, callingPackage)) {
2636 return;
2637 }
2638 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002639
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002640 // Third check: is caller the fallback/default CarrierService?
2641 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2642 if (!TextUtils.isEmpty(defaultPackage)
2643 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002644 return;
2645 }
2646
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002647 // Final check: does the caller hold a permission?
2648 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002649 }
2650
2651 @Override
2652 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2653 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2654
Jeff Sharkey53313d72017-07-13 16:47:32 -06002655 final String fake = SystemProperties.get("fw.fake_plan");
2656 if (!TextUtils.isEmpty(fake)) {
2657 final List<SubscriptionPlan> plans = new ArrayList<>();
2658 if ("month_hard".equals(fake)) {
2659 plans.add(SubscriptionPlan.Builder
2660 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2661 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002662 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2663 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2664 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2665 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2666 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002667 plans.add(SubscriptionPlan.Builder
2668 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2669 .setTitle("G-Mobile Happy")
2670 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2671 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2672 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2673 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2674 .build());
2675 plans.add(SubscriptionPlan.Builder
2676 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2677 .setTitle("G-Mobile, Charged after limit")
2678 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2679 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2680 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2681 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2682 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002683 } else if ("month_soft".equals(fake)) {
2684 plans.add(SubscriptionPlan.Builder
2685 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2686 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2687 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2688 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002689 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2690 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2691 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2692 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2693 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002694 plans.add(SubscriptionPlan.Builder
2695 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2696 .setTitle("G-Mobile, Throttled after limit")
2697 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2698 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2699 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2700 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2701 .build());
2702 plans.add(SubscriptionPlan.Builder
2703 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2704 .setTitle("G-Mobile, No data connection after limit")
2705 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2706 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2707 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2708 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2709 .build());
2710
Jeff Sharkey53313d72017-07-13 16:47:32 -06002711 } else if ("month_none".equals(fake)) {
2712 plans.add(SubscriptionPlan.Builder
2713 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2714 .setTitle("G-Mobile")
2715 .build());
2716 } else if ("prepaid".equals(fake)) {
2717 plans.add(SubscriptionPlan.Builder
2718 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2719 ZonedDateTime.now().plusDays(10))
2720 .setTitle("G-Mobile")
2721 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2722 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2723 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2724 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2725 .build());
2726 } else if ("prepaid_crazy".equals(fake)) {
2727 plans.add(SubscriptionPlan.Builder
2728 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2729 ZonedDateTime.now().plusDays(10))
2730 .setTitle("G-Mobile Anytime")
2731 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2732 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2733 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2734 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2735 .build());
2736 plans.add(SubscriptionPlan.Builder
2737 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2738 ZonedDateTime.now().plusDays(20))
2739 .setTitle("G-Mobile Nickel Nights")
2740 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002741 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2742 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002743 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2744 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2745 .build());
2746 plans.add(SubscriptionPlan.Builder
2747 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2748 ZonedDateTime.now().plusDays(20))
2749 .setTitle("G-Mobile Bonus 3G")
2750 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002751 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002752 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2753 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2754 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2755 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002756 } else if ("unlimited".equals(fake)) {
2757 plans.add(SubscriptionPlan.Builder
2758 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2759 ZonedDateTime.now().plusDays(10))
2760 .setTitle("G-Mobile Awesome")
2761 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2762 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2763 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2764 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2765 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002766 }
2767 return plans.toArray(new SubscriptionPlan[plans.size()]);
2768 }
2769
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002770 synchronized (mUidRulesFirstLock) {
2771 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002772 // Only give out plan details to the package that defined them,
2773 // so that we don't risk leaking plans between apps. We always
2774 // let in core system components (like the Settings app).
2775 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2776 if (Objects.equals(ownerPackage, callingPackage)
2777 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2778 return mSubscriptionPlans.get(subId);
2779 } else {
2780 Log.w(TAG, "Not returning plans because caller " + callingPackage
2781 + " doesn't match owner " + ownerPackage);
2782 return null;
2783 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002784 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002785 }
2786 }
2787
2788 @Override
2789 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2790 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2791
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002792 for (SubscriptionPlan plan : plans) {
2793 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002794 }
2795
2796 final long token = Binder.clearCallingIdentity();
2797 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002798 maybeRefreshTrustedTime();
2799 synchronized (mUidRulesFirstLock) {
2800 synchronized (mNetworkPoliciesSecondLock) {
2801 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002802 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002803
2804 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
2805 .getSubscriberId(subId);
2806 ensureActiveMobilePolicyAL(subId, subscriberId);
2807 maybeUpdateMobilePolicyCycleAL(subId);
2808 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002809 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002810 }
2811 } finally {
2812 Binder.restoreCallingIdentity(token);
2813 }
2814 }
2815
2816 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002817 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002818 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002819
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002820 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2821
Dianne Hackborn497175b2014-07-01 12:56:08 -07002822 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002823 for (String arg : args) {
2824 argSet.add(arg);
2825 }
2826
Felipe Lemef0823852016-06-08 13:43:08 -07002827 synchronized (mUidRulesFirstLock) {
2828 synchronized (mNetworkPoliciesSecondLock) {
2829 if (argSet.contains("--unsnooze")) {
2830 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2831 mNetworkPolicy.valueAt(i).clearSnooze();
2832 }
2833
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002834 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002835
2836 fout.println("Cleared snooze timestamps");
2837 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002838 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002839
Felipe Lemef0823852016-06-08 13:43:08 -07002840 fout.print("System ready: "); fout.println(mSystemReady);
2841 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2842 fout.print("Restrict power: "); fout.println(mRestrictPower);
2843 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002844 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2845
2846 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07002847 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002848 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002849 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2850 fout.println(mNetworkPolicy.valueAt(i).toString());
2851 }
2852 fout.decreaseIndent();
2853
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002854 fout.println();
2855 fout.println("Subscription plans:");
2856 fout.increaseIndent();
2857 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2858 final int subId = mSubscriptionPlans.keyAt(i);
2859 fout.println("Subscriber ID " + subId + ":");
2860 fout.increaseIndent();
2861 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2862 if (!ArrayUtils.isEmpty(plans)) {
2863 for (SubscriptionPlan plan : plans) {
2864 fout.println(plan);
2865 }
2866 }
2867 fout.decreaseIndent();
2868 }
2869 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002870
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002871 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07002872 fout.println("Policy for UIDs:");
2873 fout.increaseIndent();
2874 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002875 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002876 final int uid = mUidPolicy.keyAt(i);
2877 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002878 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002879 fout.print(uid);
2880 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002881 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002882 fout.println();
2883 }
2884 fout.decreaseIndent();
2885
2886 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2887 if (size > 0) {
2888 fout.println("Power save whitelist (except idle) app ids:");
2889 fout.increaseIndent();
2890 for (int i = 0; i < size; i++) {
2891 fout.print("UID=");
2892 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2893 fout.print(": ");
2894 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2895 fout.println();
2896 }
2897 fout.decreaseIndent();
2898 }
2899
2900 size = mPowerSaveWhitelistAppIds.size();
2901 if (size > 0) {
2902 fout.println("Power save whitelist app ids:");
2903 fout.increaseIndent();
2904 for (int i = 0; i < size; i++) {
2905 fout.print("UID=");
2906 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2907 fout.print(": ");
2908 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2909 fout.println();
2910 }
2911 fout.decreaseIndent();
2912 }
2913
Felipe Lemef0823852016-06-08 13:43:08 -07002914 size = mDefaultRestrictBackgroundWhitelistUids.size();
2915 if (size > 0) {
2916 fout.println("Default restrict background whitelist uids:");
2917 fout.increaseIndent();
2918 for (int i = 0; i < size; i++) {
2919 fout.print("UID=");
2920 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2921 fout.println();
2922 }
2923 fout.decreaseIndent();
2924 }
2925
2926 size = mRestrictBackgroundWhitelistRevokedUids.size();
2927 if (size > 0) {
2928 fout.println("Default restrict background whitelist uids revoked by users:");
2929 fout.increaseIndent();
2930 for (int i = 0; i < size; i++) {
2931 fout.print("UID=");
2932 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2933 fout.println();
2934 }
2935 fout.decreaseIndent();
2936 }
2937
2938 final SparseBooleanArray knownUids = new SparseBooleanArray();
2939 collectKeys(mUidState, knownUids);
2940 collectKeys(mUidRules, knownUids);
2941
2942 fout.println("Status for all known UIDs:");
2943 fout.increaseIndent();
2944 size = knownUids.size();
2945 for (int i = 0; i < size; i++) {
2946 final int uid = knownUids.keyAt(i);
2947 fout.print("UID=");
2948 fout.print(uid);
2949
2950 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2951 fout.print(" state=");
2952 fout.print(state);
2953 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2954 fout.print(" (fg)");
2955 } else {
2956 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2957 ? " (fg svc)" : " (bg)");
2958 }
2959
2960 final int uidRules = mUidRules.get(uid, RULE_NONE);
2961 fout.print(" rules=");
2962 fout.print(uidRulesToString(uidRules));
2963 fout.println();
2964 }
2965 fout.decreaseIndent();
2966
2967 fout.println("Status for just UIDs with rules:");
2968 fout.increaseIndent();
2969 size = mUidRules.size();
2970 for (int i = 0; i < size; i++) {
2971 final int uid = mUidRules.keyAt(i);
2972 fout.print("UID=");
2973 fout.print(uid);
2974 final int uidRules = mUidRules.get(uid, RULE_NONE);
2975 fout.print(" rules=");
2976 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002977 fout.println();
2978 }
2979 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08002980
2981 fout.println("Observed uid state changes:");
2982 fout.increaseIndent();
2983 mObservedHistory.dumpUL(fout);
2984 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002985 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002986 }
2987 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002988
2989 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002990 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002991 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002992 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002993 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002994 }
2995
2996 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002997 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002998 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2999
Felipe Lemef0823852016-06-08 13:43:08 -07003000 synchronized (mUidRulesFirstLock) {
3001 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003002 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003003 }
3004
Felipe Lemef0823852016-06-08 13:43:08 -07003005 private boolean isUidForegroundUL(int uid) {
3006 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07003007 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
3008 }
3009
Felipe Lemef0823852016-06-08 13:43:08 -07003010 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003011 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003012 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003013 }
3014
Felipe Lemef0823852016-06-08 13:43:08 -07003015 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003016 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3017 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3018 }
3019
Felipe Lemef0823852016-06-08 13:43:08 -07003020 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003021 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07003022 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003023 }
3024
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003025 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003026 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003027 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3028 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003029 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003030 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003031 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3032 try {
3033 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3034 if (oldUidState != uidState) {
3035 // state changed, push updated rules
3036 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003037 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3038 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3039 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003040 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003041 if (mDeviceIdleMode) {
3042 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003043 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003044 if (mRestrictPower) {
3045 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003046 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003047 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003048 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003049 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003050 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003051 } finally {
3052 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003053 }
3054 }
3055
Felipe Lemef0823852016-06-08 13:43:08 -07003056 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003057 final int index = mUidState.indexOfKey(uid);
3058 if (index >= 0) {
3059 final int oldUidState = mUidState.valueAt(index);
3060 mUidState.removeAt(index);
3061 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003062 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003063 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003064 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003065 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003066 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003067 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003068 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003069 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003070 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003071 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003072 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003073 }
3074 }
3075
Felipe Lemef28983d2016-03-25 12:18:23 -07003076 // adjust stats accounting based on foreground status
3077 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003078 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3079 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3080 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3081 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003082 try {
3083 mNetworkStats.setUidForeground(uid, uidForeground);
3084 } catch (RemoteException e) {
3085 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003086 } finally {
3087 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003088 }
3089 }
3090
Sudheer Shankac9d94072017-02-22 22:13:55 +00003091 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3092 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003093 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003094 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003095 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003096 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003097 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003098 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003099 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003100 }
3101
Felipe Lemef0823852016-06-08 13:43:08 -07003102 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003103 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3104 try {
3105 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3106 mUidFirewallPowerSaveRules);
3107 } finally {
3108 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3109 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003110 }
3111
Felipe Lemef0823852016-06-08 13:43:08 -07003112 void updateRuleForRestrictPowerUL(int uid) {
3113 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003114 }
3115
Felipe Lemef0823852016-06-08 13:43:08 -07003116 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003117 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3118 try {
3119 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3120 mUidFirewallDozableRules);
3121 } finally {
3122 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3123 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003124 }
3125
Felipe Lemef0823852016-06-08 13:43:08 -07003126 void updateRuleForDeviceIdleUL(int uid) {
3127 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003128 }
3129
Felipe Lemef28983d2016-03-25 12:18:23 -07003130 // NOTE: since both fw_dozable and fw_powersave uses the same map
3131 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003132 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003133 SparseIntArray rules) {
3134 if (enabled) {
3135 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003136 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003137 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003138 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003139 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003140 for (int ui = users.size() - 1; ui >= 0; ui--) {
3141 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003142 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3143 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3144 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3145 updateRulesForWhitelistedAppIds(uidRules,
3146 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003147 }
3148 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003149 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003150 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003151 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3152 }
3153 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003154 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
3155 } else {
3156 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003157 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003158 }
3159
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003160 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3161 final SparseBooleanArray whitelistedAppIds, int userId) {
3162 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3163 if (whitelistedAppIds.valueAt(i)) {
3164 final int appId = whitelistedAppIds.keyAt(i);
3165 final int uid = UserHandle.getUid(userId, appId);
3166 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3167 }
3168 }
3169 }
3170
3171 /**
3172 * @param deviceIdleMode if true then we don't consider
3173 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3174 * whitelisted.
3175 */
3176 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003177 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003178 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3179 || mPowerSaveWhitelistAppIds.get(appId);
3180 if (!deviceIdleMode) {
3181 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3182 }
3183 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003184 }
3185
Felipe Lemef28983d2016-03-25 12:18:23 -07003186 // NOTE: since both fw_dozable and fw_powersave uses the same map
3187 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003188 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003189 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003190 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3191 chain == FIREWALL_CHAIN_DOZABLE);
3192 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003193 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003194 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003195 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003196 }
3197 }
3198 }
3199
Felipe Lemef0823852016-06-08 13:43:08 -07003200 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003201 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3202 try {
3203 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3204 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003205
Felipe Leme873a83a2016-09-07 11:34:10 -07003206 // Fully update the app idle firewall chain.
3207 final List<UserInfo> users = mUserManager.getUsers();
3208 for (int ui = users.size() - 1; ui >= 0; ui--) {
3209 UserInfo user = users.get(ui);
3210 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3211 for (int uid : idleUids) {
3212 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3213 // quick check: if this uid doesn't have INTERNET permission, it
3214 // doesn't have network access anyway, so it is a waste to mess
3215 // with it here.
3216 if (hasInternetPermissions(uid)) {
3217 uidRules.put(uid, FIREWALL_RULE_DENY);
3218 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003219 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003220 }
3221 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003222
Felipe Lemebc853dd2016-09-08 13:26:55 -07003223 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003224 } finally {
3225 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3226 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003227 }
3228
Felipe Lemef0823852016-06-08 13:43:08 -07003229 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003230 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003231
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003232 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3233 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3234 }
3235 try {
3236 int appId = UserHandle.getAppId(uid);
3237 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3238 && !isUidForegroundOnRestrictPowerUL(uid)) {
3239 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3240 } else {
3241 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3242 }
3243 } finally {
3244 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003245 }
3246 }
3247
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003248 /**
3249 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3250 * changed.
3251 */
Felipe Lemef0823852016-06-08 13:43:08 -07003252 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003253 boolean paroled = mUsageStats.isAppIdleParoleOn();
3254 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003255 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003256
3257 int ruleCount = mUidFirewallStandbyRules.size();
3258 for (int i = 0; i < ruleCount; i++) {
3259 int uid = mUidFirewallStandbyRules.keyAt(i);
3260 int oldRules = mUidRules.get(uid);
3261 if (enableChain) {
3262 // Chain wasn't enabled before and the other power-related
3263 // chains are whitelists, so we can clear the
3264 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3265 // the effective rules result in blocking network access.
3266 oldRules &= MASK_METERED_NETWORKS;
3267 } else {
3268 // Skip if it had no restrictions to begin with
3269 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3270 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003271 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3272 if (newUidRules == RULE_NONE) {
3273 mUidRules.delete(uid);
3274 } else {
3275 mUidRules.put(uid, newUidRules);
3276 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003277 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003278 }
3279
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003280 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003281 * Update rules that might be changed by {@link #mRestrictBackground},
3282 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003283 */
Felipe Lemef0823852016-06-08 13:43:08 -07003284 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003285 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3286 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3287 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3288 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003289 try {
Felipe Leme09700462016-09-08 09:33:48 -07003290 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003291 updateRulesForRestrictPowerUL();
3292 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003293
Felipe Leme873a83a2016-09-07 11:34:10 -07003294 // If the set of restricted networks may have changed, re-evaluate those.
3295 if (restrictedNetworksChanged) {
3296 normalizePoliciesNL();
3297 updateNetworkRulesNL();
3298 }
3299 } finally {
3300 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003301 }
3302 }
3303
Felipe Leme09700462016-09-08 09:33:48 -07003304 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003305 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003306 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3307 try {
3308 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003309 updateRulesForPowerSaveUL();
3310 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3311 } finally {
3312 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3313 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003314 }
3315
Felipe Lemef0823852016-06-08 13:43:08 -07003316 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003317 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3318 try {
3319 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3320 } finally {
3321 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3322 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003323 }
3324
3325 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3326 private static final int TYPE_RESTRICT_POWER = 2;
3327 @Retention(RetentionPolicy.SOURCE)
3328 @IntDef(flag = false, value = {
3329 TYPE_RESTRICT_BACKGROUND,
3330 TYPE_RESTRICT_POWER,
3331 })
3332 public @interface RestrictType {
3333 }
3334
3335 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003336 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003337 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3338 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3339 }
3340 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003341 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003342
3343 final PackageManager pm = mContext.getPackageManager();
3344 final List<UserInfo> users;
3345 final List<ApplicationInfo> apps;
3346
3347 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3348 try {
3349 users = mUserManager.getUsers();
3350 } finally {
3351 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3352 }
3353 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3354 try {
3355 apps = pm.getInstalledApplications(
3356 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3357 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3358 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3359 } finally {
3360 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3361 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003362
Felipe Leme873a83a2016-09-07 11:34:10 -07003363 final int usersSize = users.size();
3364 final int appsSize = apps.size();
3365 for (int i = 0; i < usersSize; i++) {
3366 final UserInfo user = users.get(i);
3367 for (int j = 0; j < appsSize; j++) {
3368 final ApplicationInfo app = apps.get(j);
3369 final int uid = UserHandle.getUid(user.id, app.uid);
3370 switch (type) {
3371 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003372 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003373 break;
3374 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003375 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003376 break;
3377 default:
3378 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3379 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003380 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003381 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003382 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003383 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003384 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003385 }
3386
Felipe Lemef0823852016-06-08 13:43:08 -07003387 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003388 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08003389 for (int i = 0; i < users.size(); i++) {
3390 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08003391 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003392 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003393 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07003394 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07003395 updateRuleForAppIdleUL(uid);
3396 updateRuleForDeviceIdleUL(uid);
3397 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003398 // Update internal rules.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003399 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003400 }
3401 }
3402 }
3403
Felipe Leme70c57c22016-03-29 10:45:13 -07003404 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3405 // methods below could be merged into a isUidValidForRules() method.
3406 private boolean isUidValidForBlacklistRules(int uid) {
3407 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003408 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003409 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003410 return true;
3411 }
3412
3413 return false;
3414 }
3415
Felipe Leme70c57c22016-03-29 10:45:13 -07003416 private boolean isUidValidForWhitelistRules(int uid) {
3417 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3418 }
3419
Amith Yamasani15e472352015-04-24 19:06:07 -07003420 private boolean isUidIdle(int uid) {
3421 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3422 final int userId = UserHandle.getUserId(uid);
3423
songjinshi0655edd2016-05-18 19:55:32 +08003424 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003425 for (String packageName : packages) {
3426 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3427 return false;
3428 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003429 }
3430 }
3431 return true;
3432 }
3433
3434 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003435 * Checks if an uid has INTERNET permissions.
3436 * <p>
3437 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003438 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003439 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003440 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003441 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003442 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003443 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003444 }
3445 } catch (RemoteException e) {
3446 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003447 return true;
3448 }
3449
3450 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003451 * Clears all state - internal and external - associated with an UID.
3452 */
3453 private void onUidDeletedUL(int uid) {
3454 // First cleanup in-memory state synchronously...
3455 mUidRules.delete(uid);
3456 mUidPolicy.delete(uid);
3457 mUidFirewallStandbyRules.delete(uid);
3458 mUidFirewallDozableRules.delete(uid);
3459 mUidFirewallPowerSaveRules.delete(uid);
3460 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3461 mPowerSaveWhitelistAppIds.delete(uid);
3462 mPowerSaveTempWhitelistAppIds.delete(uid);
3463
3464 // ...then update iptables asynchronously.
3465 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3466 }
3467
3468 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003469 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003470 *
Felipe Leme781ba142016-05-09 16:24:48 -07003471 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003472 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003473 * <li>Doze mode
3474 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003475 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003476 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003477 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003478 *
3479 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003480 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003481 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003482 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003483 updateRuleForDeviceIdleUL(uid);
3484 updateRuleForAppIdleUL(uid);
3485 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003486
3487 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003488 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003489
3490 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003491 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003492 }
3493
Felipe Leme70c57c22016-03-29 10:45:13 -07003494 /**
3495 * Applies network rules to bandwidth controllers based on process state and user-defined
3496 * restrictions (blacklist / whitelist).
3497 *
3498 * <p>
3499 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3500 * networks:
3501 * <ul>
3502 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3503 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3504 * also blacklisted.
3505 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3506 * no UIDs other those whitelisted will have access.
3507 * <ul>
3508 *
3509 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3510 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3511 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3512 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003513 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003514 * {@link INetworkManagementService}, but this method should also be called in events (like
3515 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3516 * following rules should also be applied:
3517 *
3518 * <ul>
3519 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3520 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3521 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3522 * {@code bw_penalty_box}.
3523 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3524 * </ul>
3525 *
3526 * <p>For optimization, the rules are only applied on user apps that have internet access
3527 * permission, since there is no need to change the {@code iptables} rule if the app does not
3528 * have permission to use the internet.
3529 *
3530 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003531 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003532 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003533 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003534 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3535 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3536 "updateRulesForDataUsageRestrictionsUL: " + uid);
3537 }
3538 try {
3539 updateRulesForDataUsageRestrictionsULInner(uid);
3540 } finally {
3541 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3542 }
3543 }
3544
3545 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003546 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003547 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003548 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003549 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003550
Dianne Hackborn497175b2014-07-01 12:56:08 -07003551 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003552 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003553 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003554
Felipe Leme781ba142016-05-09 16:24:48 -07003555 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003556 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003557 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3558 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003559
Felipe Leme70c57c22016-03-29 10:45:13 -07003560 // First step: define the new rule based on user restrictions and foreground state.
3561 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003562 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3563 newRule = RULE_TEMPORARY_ALLOW_METERED;
3564 } else if (isWhitelisted) {
3565 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003566 }
3567 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003568 if (isBlacklisted) {
3569 newRule = RULE_REJECT_METERED;
3570 } else if (mRestrictBackground && isWhitelisted) {
3571 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003572 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003573 }
Felipe Leme781ba142016-05-09 16:24:48 -07003574 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003575
Felipe Lemef28983d2016-03-25 12:18:23 -07003576 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003577 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003578 + ": isForeground=" +isForeground
3579 + ", isBlacklisted=" + isBlacklisted
3580 + ", isWhitelisted=" + isWhitelisted
3581 + ", oldRule=" + uidRulesToString(oldRule)
3582 + ", newRule=" + uidRulesToString(newRule)
3583 + ", newUidRules=" + uidRulesToString(newUidRules)
3584 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003585 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003586
Felipe Leme46c4fc32016-05-04 09:21:43 -07003587 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003588 mUidRules.delete(uid);
3589 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003590 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003591 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003592
Felipe Leme70c57c22016-03-29 10:45:13 -07003593 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003594 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003595 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003596 // Temporarily whitelist foreground app, removing from blacklist if necessary
3597 // (since bw_penalty_box prevails over bw_happy_box).
3598
3599 setMeteredNetworkWhitelist(uid, true);
3600 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3601 // but ideally it should be just:
3602 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003603 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003604 setMeteredNetworkBlacklist(uid, false);
3605 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003606 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003607 // Remove temporary whitelist from app that is not on foreground anymore.
3608
3609 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3610 // but ideally they should be just:
3611 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3612 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003613 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003614 setMeteredNetworkWhitelist(uid, false);
3615 }
Felipe Leme781ba142016-05-09 16:24:48 -07003616 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003617 setMeteredNetworkBlacklist(uid, true);
3618 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003619 } else if (hasRule(newRule, RULE_REJECT_METERED)
3620 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003621 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003622 setMeteredNetworkBlacklist(uid, isBlacklisted);
Hugo Benichi2966c182017-03-28 17:17:13 +09003623 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003624 // Since blacklist prevails over whitelist, we need to handle the special case
3625 // where app is whitelisted and blacklisted at the same time (although such
3626 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003627 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003628 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003629 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3630 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003631 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003632 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003633 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003634 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003635 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3636 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003637 + ", whitelisted=" + isWhitelisted
3638 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003639 + ", newRule=" + uidRulesToString(newUidRules)
3640 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003641 }
Felipe Leme781ba142016-05-09 16:24:48 -07003642
Sudheer Shankac9d94072017-02-22 22:13:55 +00003643 // Dispatch changed rule to existing listeners.
3644 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003645 }
3646 }
3647
3648 /**
3649 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3650 * listeners in case of change.
3651 * <p>
3652 * There are 3 power-related rules that affects whether an app has background access on
3653 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3654 * restriction, it's added to the equivalent firewall chain:
3655 * <ul>
3656 * <li>App is idle: {@code fw_standby} firewall chain.
3657 * <li>Device is idle: {@code fw_dozable} firewall chain.
3658 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3659 * </ul>
3660 * <p>
3661 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3662 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3663 * <p>
3664 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3665 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003666 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003667 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3668
Sudheer Shankac9d94072017-02-22 22:13:55 +00003669 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003670
Sudheer Shankac9d94072017-02-22 22:13:55 +00003671 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003672 mUidRules.delete(uid);
3673 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003674 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003675 }
3676 }
3677
3678 /**
3679 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3680 *
3681 * @param uid the uid of the app to update rules for
3682 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3683 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3684 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003685 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003686 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003687 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003688 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3689 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3690 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3691 + (paroled ? "P" : "-"));
3692 }
3693 try {
3694 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3695 } finally {
3696 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3697 }
3698 }
3699
3700 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003701 if (!isUidValidForBlacklistRules(uid)) {
3702 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003703 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003704 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003705
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003706 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003707 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003708 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003709
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003710 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003711 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3712 int newRule = RULE_NONE;
3713
3714 // First step: define the new rule based on user restrictions and foreground state.
3715
3716 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3717 // by considering the foreground and non-foreground states.
3718 if (isForeground) {
3719 if (restrictMode) {
3720 newRule = RULE_ALLOW_ALL;
3721 }
3722 } else if (restrictMode) {
3723 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3724 }
3725
3726 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3727
3728 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003729 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003730 + ", isIdle: " + isIdle
3731 + ", mRestrictPower: " + mRestrictPower
3732 + ", mDeviceIdleMode: " + mDeviceIdleMode
3733 + ", isForeground=" + isForeground
3734 + ", isWhitelisted=" + isWhitelisted
3735 + ", oldRule=" + uidRulesToString(oldRule)
3736 + ", newRule=" + uidRulesToString(newRule)
3737 + ", newUidRules=" + uidRulesToString(newUidRules)
3738 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3739 }
3740
Felipe Leme781ba142016-05-09 16:24:48 -07003741 // Second step: notify listeners if state changed.
3742 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003743 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003744 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003745 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003746 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3747 } else {
3748 // All scenarios should have been covered above
3749 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3750 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003751 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003752 + ", newRule=" + uidRulesToString(newUidRules)
3753 + ", oldRule=" + uidRulesToString(oldUidRules));
3754 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003755 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003756 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003757
Sudheer Shankac9d94072017-02-22 22:13:55 +00003758 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003759 }
3760
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003761 private class AppIdleStateChangeListener
3762 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3763
3764 @Override
3765 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3766 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003767 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3768 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003769 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003770 synchronized (mUidRulesFirstLock) {
3771 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003772 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003773 }
3774 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003775 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003776 }
3777
3778 @Override
3779 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003780 synchronized (mUidRulesFirstLock) {
3781 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003782 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003783 }
3784 }
3785
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003786 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3787 if (listener != null) {
3788 try {
3789 listener.onUidRulesChanged(uid, uidRules);
3790 } catch (RemoteException ignored) {
3791 }
3792 }
3793 }
3794
3795 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3796 String[] meteredIfaces) {
3797 if (listener != null) {
3798 try {
3799 listener.onMeteredIfacesChanged(meteredIfaces);
3800 } catch (RemoteException ignored) {
3801 }
3802 }
3803 }
3804
3805 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3806 boolean restrictBackground) {
3807 if (listener != null) {
3808 try {
3809 listener.onRestrictBackgroundChanged(restrictBackground);
3810 } catch (RemoteException ignored) {
3811 }
3812 }
3813 }
3814
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003815 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3816 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003817 if (listener != null) {
3818 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003819 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003820 } catch (RemoteException ignored) {
3821 }
3822 }
3823 }
3824
Makoto Onuki8e777332017-03-28 11:25:47 -07003825 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003826 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003827 public boolean handleMessage(Message msg) {
3828 switch (msg.what) {
3829 case MSG_RULES_CHANGED: {
3830 final int uid = msg.arg1;
3831 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003832 final int length = mListeners.beginBroadcast();
3833 for (int i = 0; i < length; i++) {
3834 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3835 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003836 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003837 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003838 return true;
3839 }
3840 case MSG_METERED_IFACES_CHANGED: {
3841 final String[] meteredIfaces = (String[]) msg.obj;
3842 final int length = mListeners.beginBroadcast();
3843 for (int i = 0; i < length; i++) {
3844 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003845 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003846 }
3847 mListeners.finishBroadcast();
3848 return true;
3849 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003850 case MSG_LIMIT_REACHED: {
3851 final String iface = (String) msg.obj;
3852
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003853 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003854 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003855 if (mMeteredIfaces.contains(iface)) {
3856 try {
3857 // force stats update to make sure we have
3858 // numbers that caused alert to trigger.
3859 mNetworkStats.forceUpdate();
3860 } catch (RemoteException e) {
3861 // ignored; service lives in system_server
3862 }
3863
Felipe Lemef0823852016-06-08 13:43:08 -07003864 updateNetworkEnabledNL();
3865 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003866 }
3867 }
3868 return true;
3869 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003870 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3871 final boolean restrictBackground = msg.arg1 != 0;
3872 final int length = mListeners.beginBroadcast();
3873 for (int i = 0; i < length; i++) {
3874 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003875 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003876 }
3877 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003878 final Intent intent =
3879 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3880 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3881 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3882 return true;
3883 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003884 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003885 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003886 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003887 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003888 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07003889 final int length = mListeners.beginBroadcast();
3890 for (int i = 0; i < length; i++) {
3891 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003892 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003893 }
3894 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003895 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3896 if (notifyApp.booleanValue()) {
3897 broadcastRestrictBackgroundChanged(uid, notifyApp);
3898 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003899 return true;
3900 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003901 case MSG_ADVISE_PERSIST_THRESHOLD: {
3902 final long lowestRule = (Long) msg.obj;
3903 try {
3904 // make sure stats are recorded frequently enough; we aim
3905 // for 2MB threshold for 2GB/month rules.
3906 final long persistThreshold = lowestRule / 1000;
3907 mNetworkStats.advisePersistThreshold(persistThreshold);
3908 } catch (RemoteException e) {
3909 // ignored; service lives in system_server
3910 }
3911 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003912 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003913 case MSG_UPDATE_INTERFACE_QUOTA: {
3914 removeInterfaceQuota((String) msg.obj);
3915 // int params need to be stitched back into a long
3916 setInterfaceQuota((String) msg.obj,
3917 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3918 return true;
3919 }
3920 case MSG_REMOVE_INTERFACE_QUOTA: {
3921 removeInterfaceQuota((String) msg.obj);
3922 return true;
3923 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003924 case MSG_SET_FIREWALL_RULES: {
3925 final int chain = msg.arg1;
3926 final int toggle = msg.arg2;
3927 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3928 if (uidRules != null) {
3929 setUidFirewallRules(chain, uidRules);
3930 }
3931 if (toggle != CHAIN_TOGGLE_NONE) {
3932 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3933 }
3934 return true;
3935 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003936 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3937 resetUidFirewallRules(msg.arg1);
3938 return true;
3939 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003940 default: {
3941 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003942 }
3943 }
3944 }
Makoto Onuki8e777332017-03-28 11:25:47 -07003945 };
3946
3947 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
3948 @Override
3949 public boolean handleMessage(Message msg) {
3950 switch (msg.what) {
3951 case UID_MSG_STATE_CHANGED: {
3952 final int uid = msg.arg1;
3953 final int procState = msg.arg2;
3954 final long procStateSeq = (Long) msg.obj;
3955
3956 handleUidChanged(uid, procState, procStateSeq);
3957 return true;
3958 }
3959 case UID_MSG_GONE: {
3960 final int uid = msg.arg1;
3961 handleUidGone(uid);
3962 return true;
3963 }
3964 default: {
3965 return false;
3966 }
3967 }
3968 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003969
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003970 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003971
Makoto Onuki8e777332017-03-28 11:25:47 -07003972 void handleUidChanged(int uid, int procState, long procStateSeq) {
3973 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
3974 try {
3975 synchronized (mUidRulesFirstLock) {
3976 // We received a uid state change callback, add it to the history so that it
3977 // will be useful for debugging.
3978 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
3979 // Now update the network policy rules as per the updated uid state.
3980 updateUidStateUL(uid, procState);
3981 // Updating the network rules is done, so notify AMS about this.
3982 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
3983 }
3984 } finally {
3985 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3986 }
3987 }
3988
3989 void handleUidGone(int uid) {
3990 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
3991 try {
3992 synchronized (mUidRulesFirstLock) {
3993 removeUidStateUL(uid);
3994 }
3995 } finally {
3996 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3997 }
3998 }
3999
Felipe Leme57e3d312016-08-23 14:42:52 -07004000 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4001 final PackageManager pm = mContext.getPackageManager();
4002 final String[] packages = pm.getPackagesForUid(uid);
4003 if (packages != null) {
4004 final int userId = UserHandle.getUserId(uid);
4005 for (String packageName : packages) {
4006 final Intent intent =
4007 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4008 intent.setPackage(packageName);
4009 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4010 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4011 }
4012 }
4013 }
4014
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004015 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4016 // long quotaBytes split up into two ints to fit in message
4017 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4018 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4019 }
4020
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004021 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004022 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004023 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004024 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004025 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004026 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004027 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004028 }
4029 }
4030
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004031 private void removeInterfaceQuotaAsync(String iface) {
4032 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4033 }
4034
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004035 private void removeInterfaceQuota(String iface) {
4036 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004037 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004038 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004039 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004040 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004041 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004042 }
4043 }
4044
Felipe Leme70c57c22016-03-29 10:45:13 -07004045 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4046 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004047 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004048 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004049 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004050 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4051 } catch (RemoteException e) {
4052 // ignored; service lives in system_server
4053 }
4054 }
4055
4056 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4057 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4058 try {
4059 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4060 } catch (IllegalStateException e) {
4061 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004062 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004063 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004064 }
4065 }
4066
Felipe Lemebc853dd2016-09-08 13:26:55 -07004067 private static final int CHAIN_TOGGLE_NONE = 0;
4068 private static final int CHAIN_TOGGLE_ENABLE = 1;
4069 private static final int CHAIN_TOGGLE_DISABLE = 2;
4070 @Retention(RetentionPolicy.SOURCE)
4071 @IntDef(flag = false, value = {
4072 CHAIN_TOGGLE_NONE,
4073 CHAIN_TOGGLE_ENABLE,
4074 CHAIN_TOGGLE_DISABLE
4075 })
4076 public @interface ChainToggleType {
4077 }
4078
4079 /**
4080 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
4081 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
4082 *
4083 * @param chain firewall chain.
4084 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4085 * @param toggle whether the chain should be enabled, disabled, or not changed.
4086 */
4087 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
4088 @ChainToggleType int toggle) {
4089 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
4090 }
4091
Amith Yamasani15e472352015-04-24 19:06:07 -07004092 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004093 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4094 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4095 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004096 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004097 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004098 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004099 int size = uidRules.size();
4100 int[] uids = new int[size];
4101 int[] rules = new int[size];
4102 for(int index = size - 1; index >= 0; --index) {
4103 uids[index] = uidRules.keyAt(index);
4104 rules[index] = uidRules.valueAt(index);
4105 }
4106 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004107 } catch (IllegalStateException e) {
4108 Log.wtf(TAG, "problem setting firewall uid rules", e);
4109 } catch (RemoteException e) {
4110 // ignored; service lives in system_server
4111 }
4112 }
4113
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004114 /**
4115 * Add or remove a uid to the firewall blacklist for all network ifaces.
4116 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004117 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004118 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4119 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4120 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004121 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004122 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004123 if (chain == FIREWALL_CHAIN_DOZABLE) {
4124 mUidFirewallDozableRules.put(uid, rule);
4125 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4126 mUidFirewallStandbyRules.put(uid, rule);
4127 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4128 mUidFirewallPowerSaveRules.put(uid, rule);
4129 }
4130
4131 try {
4132 mNetworkManager.setFirewallUidRule(chain, uid, rule);
4133 } catch (IllegalStateException e) {
4134 Log.wtf(TAG, "problem setting firewall uid rules", e);
4135 } catch (RemoteException e) {
4136 // ignored; service lives in system_server
4137 }
4138 } finally {
4139 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004140 }
4141 }
4142
4143 /**
4144 * Add or remove a uid to the firewall blacklist for all network ifaces.
4145 */
Felipe Lemef0823852016-06-08 13:43:08 -07004146 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004147 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4148 mFirewallChainStates.get(chain) == enable) {
4149 // All is the same, nothing to do.
4150 return;
4151 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004152 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004153 try {
4154 mNetworkManager.setFirewallChainEnabled(chain, enable);
4155 } catch (IllegalStateException e) {
4156 Log.wtf(TAG, "problem enable firewall chain", e);
4157 } catch (RemoteException e) {
4158 // ignored; service lives in system_server
4159 }
4160 }
4161
Felipe Leme03e95e22016-09-09 09:25:31 -07004162 /**
4163 * Resets all firewall rules associated with an UID.
4164 */
4165 private void resetUidFirewallRules(int uid) {
4166 try {
4167 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4168 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4169 mNetworkManager
4170 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4171 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4172 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4173 } catch (IllegalStateException e) {
4174 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4175 } catch (RemoteException e) {
4176 // ignored; service lives in system_server
4177 }
4178 }
4179
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004180 private long getTotalBytes(NetworkTemplate template, long start, long end) {
4181 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004182 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004183 } catch (RuntimeException e) {
4184 Slog.w(TAG, "problem reading network stats: " + e);
4185 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004186 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004187 // ignored; service lives in system_server
4188 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004189 }
4190 }
4191
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004192 private boolean isBandwidthControlEnabled() {
4193 final long token = Binder.clearCallingIdentity();
4194 try {
4195 return mNetworkManager.isBandwidthControlEnabled();
4196 } catch (RemoteException e) {
4197 // ignored; service lives in system_server
4198 return false;
4199 } finally {
4200 Binder.restoreCallingIdentity(token);
4201 }
4202 }
4203
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004204 /**
4205 * Try refreshing {@link #mTime} when stale.
4206 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07004207 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004208 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004209 mTime.forceRefresh();
4210 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004211 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004212
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004213 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004214 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
4215 }
4216
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004217 private static Intent buildAllowBackgroundDataIntent() {
4218 return new Intent(ACTION_ALLOW_BACKGROUND);
4219 }
4220
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004221 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4222 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
4223 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4224 return intent;
4225 }
4226
Wei Liu546cb772016-07-21 16:19:01 -07004227 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004228 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004229 intent.setComponent(ComponentName.unflattenFromString(
4230 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004231 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4232 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4233 return intent;
4234 }
4235
Wei Liu546cb772016-07-21 16:19:01 -07004236 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004237 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004238 intent.setComponent(ComponentName.unflattenFromString(
4239 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004240 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4241 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4242 return intent;
4243 }
4244
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004245 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004246 public void addIdleHandler(IdleHandler handler) {
4247 mHandler.getLooper().getQueue().addIdleHandler(handler);
4248 }
4249
jackqdyulei29c82ab2017-03-10 14:09:16 -08004250 @VisibleForTesting
4251 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4252 mRestrictBackgroundPowerState = result;
4253
4254 boolean restrictBackground = result.batterySaverEnabled;
4255 boolean shouldInvokeRestrictBackground;
4256 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4257 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4258
4259 if (result.globalBatterySaverEnabled) {
4260 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4261 // turn it on.
4262 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4263 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4264 localRestrictBgChangedInBsm = false;
4265 } else {
4266 // Try to restore the restrictBackground if it doesn't change in bsm
4267 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4268 restrictBackground = mRestrictBackgroundBeforeBsm;
4269 }
4270
4271 if (shouldInvokeRestrictBackground) {
4272 setRestrictBackground(restrictBackground);
4273 }
4274
4275 // Change it at last so setRestrictBackground() won't affect this variable
4276 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4277 }
4278
Jeff Sharkey1b861272011-05-22 00:34:52 -07004279 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4280 final int size = source.size();
4281 for (int i = 0; i < size; i++) {
4282 target.put(source.keyAt(i), true);
4283 }
4284 }
4285
Stuart Scottf1fb3972015-04-02 18:00:02 -07004286 @Override
4287 public void factoryReset(String subscriber) {
4288 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4289
Stuart Scotte3e314d2015-04-20 14:07:45 -07004290 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4291 return;
4292 }
4293
Stuart Scottf1fb3972015-04-02 18:00:02 -07004294 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004295 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004296 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4297 for (NetworkPolicy policy : policies) {
4298 if (policy.template.equals(template)) {
4299 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4300 policy.inferred = false;
4301 policy.clearSnooze();
4302 }
4303 }
4304 setNetworkPolicies(policies);
4305
4306 // Turn restrict background data off
4307 setRestrictBackground(false);
4308
Stuart Scotte3e314d2015-04-20 14:07:45 -07004309 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4310 // Remove app's "restrict background data" flag
4311 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4312 setUidPolicy(uid, POLICY_NONE);
4313 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004314 }
4315 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004316
Sudheer Shankab8f23162017-08-04 13:30:10 -07004317 @Override
4318 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4319 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4320 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4321 }
4322
4323 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4324 final int uidRules;
4325 final boolean isBackgroundRestricted;
4326 synchronized (mUidRulesFirstLock) {
4327 uidRules = mUidRules.get(uid, RULE_NONE);
4328 isBackgroundRestricted = mRestrictBackground;
4329 }
4330 if (hasRule(uidRules, RULE_REJECT_ALL)) {
4331 if (LOGV) logUidStatus(uid, "blocked by power restrictions");
4332 return true;
4333 }
4334 if (!isNetworkMetered) {
4335 if (LOGV) logUidStatus(uid, "allowed on unmetered network");
4336 return false;
4337 }
4338 if (hasRule(uidRules, RULE_REJECT_METERED)) {
4339 if (LOGV) logUidStatus(uid, "blacklisted on metered network");
4340 return true;
4341 }
4342 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4343 if (LOGV) logUidStatus(uid, "whitelisted on metered network");
4344 return false;
4345 }
4346 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4347 if (LOGV) logUidStatus(uid, "temporary whitelisted on metered network");
4348 return false;
4349 }
4350 if (isBackgroundRestricted) {
4351 if (LOGV) logUidStatus(uid, "blocked when background is restricted");
4352 return true;
4353 }
4354 if (LOGV) logUidStatus(uid, "allowed by default");
4355 return false;
4356 }
4357
Felipe Lemed17fda42016-04-29 11:12:45 -07004358 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4359
4360 @Override
4361 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004362 synchronized (mUidRulesFirstLock) {
4363 boolean changed = removeUserStateUL(userId, false);
4364 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004365 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004366 synchronized (mNetworkPoliciesSecondLock) {
4367 writePolicyAL();
4368 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004369 }
4370 }
4371 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004372
4373 /**
4374 * @return true if the given uid is restricted from doing networking on metered networks.
4375 */
4376 @Override
4377 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4378 final int uidRules;
4379 final boolean isBackgroundRestricted;
4380 synchronized (mUidRulesFirstLock) {
4381 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4382 isBackgroundRestricted = mRestrictBackground;
4383 }
4384 return isBackgroundRestricted
4385 && !hasRule(uidRules, RULE_ALLOW_METERED)
4386 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4387 }
4388
4389 /**
4390 * @return true if networking is blocked on the given interface for the given uid according
4391 * to current networking policies.
4392 */
4393 @Override
4394 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004395 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004396 synchronized (mNetworkPoliciesSecondLock) {
4397 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004398 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004399 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004400 }
4401 }
4402
4403 private static boolean hasRule(int uidRules, int rule) {
4404 return (uidRules & rule) != 0;
4405 }
4406
4407 private static void logUidStatus(int uid, String descr) {
4408 Slog.d(TAG, String.format("uid %d is %s", uid, descr));
Felipe Lemed17fda42016-04-29 11:12:45 -07004409 }
Sudheer Shankae7361852017-03-07 11:51:46 -08004410
4411 /**
4412 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
4413 * (uid, procStateSeq) pairs.
4414 */
4415 @VisibleForTesting
4416 public static final class ProcStateSeqHistory {
4417 private static final int INVALID_UID = -1;
4418
4419 /**
4420 * Denotes maximum number of items this history can hold.
4421 */
4422 private final int mMaxCapacity;
4423 /**
4424 * Used for storing the uid information.
4425 */
4426 private final int[] mUids;
4427 /**
4428 * Used for storing the sequence numbers associated with {@link #mUids}.
4429 */
4430 private final long[] mProcStateSeqs;
4431 /**
4432 * Points to the next available slot for writing (uid, procStateSeq) pair.
4433 */
4434 private int mHistoryNext;
4435
4436 public ProcStateSeqHistory(int maxCapacity) {
4437 mMaxCapacity = maxCapacity;
4438 mUids = new int[mMaxCapacity];
4439 Arrays.fill(mUids, INVALID_UID);
4440 mProcStateSeqs = new long[mMaxCapacity];
4441 }
4442
4443 @GuardedBy("mUidRulesFirstLock")
4444 public void addProcStateSeqUL(int uid, long procStateSeq) {
4445 mUids[mHistoryNext] = uid;
4446 mProcStateSeqs[mHistoryNext] = procStateSeq;
4447 mHistoryNext = increaseNext(mHistoryNext, 1);
4448 }
4449
4450 @GuardedBy("mUidRulesFirstLock")
4451 public void dumpUL(IndentingPrintWriter fout) {
4452 if (mUids[0] == INVALID_UID) {
4453 fout.println("NONE");
4454 return;
4455 }
4456 int index = mHistoryNext;
4457 do {
4458 index = increaseNext(index, -1);
4459 if (mUids[index] == INVALID_UID) {
4460 break;
4461 }
4462 fout.println(getString(mUids[index], mProcStateSeqs[index]));
4463 } while (index != mHistoryNext);
4464 }
4465
4466 public static String getString(int uid, long procStateSeq) {
Sudheer Shankadb9aaf032017-06-19 19:05:31 -07004467 return "UID=" + uid + " Seq=" + procStateSeq;
Sudheer Shankae7361852017-03-07 11:51:46 -08004468 }
4469
4470 private int increaseNext(int next, int increment) {
4471 next += increment;
4472 if (next >= mMaxCapacity) {
4473 next = 0;
4474 } else if (next < 0) {
4475 next = mMaxCapacity - 1;
4476 }
4477 return next;
4478 }
4479 }
Chris Wren193ae6b2017-03-31 15:17:11 -04004480
4481 private class NotificationId {
4482 private final String mTag;
4483 private final int mId;
4484
4485 NotificationId(NetworkPolicy policy, int type) {
4486 mTag = buildNotificationTag(policy, type);
4487 mId = type;
4488 }
4489
4490 @Override
4491 public boolean equals(Object o) {
4492 if (this == o) return true;
4493 if (!(o instanceof NotificationId)) return false;
4494 NotificationId that = (NotificationId) o;
4495 return Objects.equals(mTag, that.mTag);
4496 }
4497
4498 @Override
4499 public int hashCode() {
4500 return Objects.hash(mTag);
4501 }
4502
4503 /**
4504 * Build unique tag that identifies an active {@link NetworkPolicy}
4505 * notification of a specific type, like {@link #TYPE_LIMIT}.
4506 */
4507 private String buildNotificationTag(NetworkPolicy policy, int type) {
4508 return TAG + ":" + policy.template.hashCode() + ":" + type;
4509 }
4510
4511 public String getTag() {
4512 return mTag;
4513 }
4514
4515 public int getId() {
4516 return mId;
4517 }
4518 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004519}