blob: b4056b333fe5114edb78d0404ab2bbfb9be013f0 [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070021import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkeyb74799882017-07-28 16:55:41 -060022import static android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080032import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060035import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey64c96ec2017-08-30 16:28:26 -060036import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070037import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070038import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070039import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070040import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070041import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080042import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
44import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070045import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070046import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060047import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
48import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
Felipe Leme46b451f2016-08-19 08:46:17 -070049import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070050import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070051import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070053import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070054import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070055import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070056import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070057import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080058import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
59import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060060import static android.net.NetworkPolicyManager.resolveNetworkId;
Felipe Lemeb146f762016-08-19 09:52:16 -070061import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070062import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070063import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
64import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070065import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
66import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070067import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080068import static android.net.TrafficStats.MB_IN_BYTES;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070069import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070070import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060071import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070072import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080073
Jeff Sharkey854b2b12012-04-13 16:03:40 -070074import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070075import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070076import static com.android.internal.util.XmlUtils.readBooleanAttribute;
77import static com.android.internal.util.XmlUtils.readIntAttribute;
78import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060079import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070080import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
81import static com.android.internal.util.XmlUtils.writeIntAttribute;
82import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060083import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070084import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070085import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060086
Jeff Sharkey21c9c452011-06-07 12:26:43 -070087import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080088import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070089import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070090
Dianne Hackborn88e98df2015-03-23 13:29:14 -070091import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070092import android.annotation.IntDef;
Felipe Lemebc853dd2016-09-08 13:26:55 -070093import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -070094import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -080095import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070096import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070097import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070098import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070099import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700100import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700101import android.app.Notification;
102import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700103import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700104import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700105import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700106import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700107import android.content.Intent;
108import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700109import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700110import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700111import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700112import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700113import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700114import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700115import android.net.ConnectivityManager;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600116import android.net.ConnectivityManager.NetworkCallback;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700117import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700118import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700119import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700120import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700121import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700122import android.net.LinkProperties;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600123import android.net.Network;
124import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700125import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700126import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600127import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700128import android.net.NetworkQuotaInfo;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600129import android.net.NetworkRequest;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700130import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700131import android.net.NetworkTemplate;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600132import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700133import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700134import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700135import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700136import android.os.Environment;
137import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700138import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700139import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700140import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700141import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700142import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700143import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700144import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700145import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600146import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800147import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700148import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700149import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600150import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700151import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700152import android.os.ShellCallback;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600153import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700154import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700155import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700156import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700157import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100158import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700159import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600160import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800161import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600162import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700163import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400164import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700165import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700166import android.util.ArrayMap;
167import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700168import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700169import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700170import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700171import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600172import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700173import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600174import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700175import android.util.SparseBooleanArray;
176import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700177import android.util.TrustedTime;
178import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700179
Jeff Sharkey497e4432011-06-14 17:27:29 -0700180import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700181import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800182import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400183import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500184import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700185import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800186import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600187import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700188import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700189import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600190import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700191import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700192import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700193import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800194import com.android.server.SystemConfig;
jackqdyulei455e90a2017-02-09 15:29:16 -0800195import com.android.server.power.BatterySaverPolicy.ServiceType;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600196
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600197import libcore.io.IoUtils;
198
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700199import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700200import org.xmlpull.v1.XmlSerializer;
201
202import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700203import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700204import java.io.FileInputStream;
205import java.io.FileNotFoundException;
206import java.io.FileOutputStream;
207import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700208import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700209import java.lang.annotation.Retention;
210import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100211import java.nio.charset.StandardCharsets;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600212import java.time.ZoneId;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600213import java.time.ZonedDateTime;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700214import java.util.ArrayList;
215import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700216import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600217import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400218import java.util.Objects;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800219import java.util.concurrent.CountDownLatch;
220import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700221
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700222/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700223 * Service that maintains low-level network policy rules, using
224 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700225 * <p>
226 * Derives active rules by combining a given policy with other system status,
227 * and delivers to listeners, such as {@link ConnectivityManager}, for
228 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700229 *
230 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000231 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700232 * <ul>
233 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
234 * rules).
235 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
236 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000237 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
238 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700239 * </ul>
240 *
241 * <p>
242 * As such, methods that require synchronization have the following prefixes:
243 * <ul>
244 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
245 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000246 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
247 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700248 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700249 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700250public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800251 static final String TAG = "NetworkPolicy";
Hugo Benichi5d2f2b52017-04-07 08:53:25 +0900252 private static final boolean LOGD = false;
253 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700254
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700255 private static final int VERSION_INIT = 1;
256 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700257 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800258 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800259 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800260 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700261 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700262 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700263 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700264 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600265 private static final int VERSION_ADDED_CYCLE = 11;
266 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700267
Sudheer Shankae7361852017-03-07 11:51:46 -0800268 /**
269 * Max items written to {@link #ProcStateSeqHistory}.
270 */
271 @VisibleForTesting
272 public static final int MAX_PROC_STATE_SEQ_HISTORY =
273 ActivityManager.isLowRamDeviceStatic() ? 50 : 200;
274
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800275 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400276 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800277 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400278 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800279 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400280 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700281
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700282 private static final String TAG_POLICY_LIST = "policy-list";
283 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600284 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700285 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700286 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800287 private static final String TAG_WHITELIST = "whitelist";
288 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800289 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700290
291 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700292 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700293 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
294 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700295 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600296 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
297 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
298 private static final String ATTR_CYCLE_START = "cycleStart";
299 private static final String ATTR_CYCLE_END = "cycleEnd";
300 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700301 private static final String ATTR_WARNING_BYTES = "warningBytes";
302 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700303 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800304 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
305 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800306 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700307 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700308 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700309 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700310 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600311 private static final String ATTR_SUB_ID = "subId";
312 private static final String ATTR_TITLE = "title";
313 private static final String ATTR_SUMMARY = "summary";
314 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
315 private static final String ATTR_USAGE_BYTES = "usageBytes";
316 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600317 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700318
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800319 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800320 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800321 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800322 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700323
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700324 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
325
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700326 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700327 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800328 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800329 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700330 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700331 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
332 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700333 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700334 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700335
Makoto Onuki8e777332017-03-28 11:25:47 -0700336 private static final int UID_MSG_STATE_CHANGED = 100;
337 private static final int UID_MSG_GONE = 101;
338
Jeff Sharkey75279902011-05-24 18:39:45 -0700339 private final Context mContext;
340 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700341 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700342 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700343 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700344 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700345 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700346 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700347
348 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700349 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700350 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700351 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800352 @GuardedBy("mUidRulesFirstLock")
353 private PowerSaveState mRestrictBackgroundPowerState;
354
355 // Store the status of restrict background before turning on battery saver.
356 // Used to restore mRestrictBackground when battery saver is turned off.
357 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700358
Sudheer Shanka543339f2017-07-28 15:18:07 -0700359 // Denotes the status of restrict background read from disk.
360 private boolean mLoadedRestrictBackground;
361
Felipe Lemef0823852016-06-08 13:43:08 -0700362 // See main javadoc for instructions on how to use these locks.
363 final Object mUidRulesFirstLock = new Object();
364 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700365
Felipe Lemef0823852016-06-08 13:43:08 -0700366 @GuardedBy("allLocks") volatile boolean mSystemReady;
367
Felipe Lemef0823852016-06-08 13:43:08 -0700368 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
369 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
370 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800371 // Store whether user flipped restrict background in battery saver mode
372 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700373
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700374 private final boolean mSuppressDefaultPolicy;
375
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700376 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600377 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800378 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700379
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600380 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600381 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600382 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600383 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600384 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600385 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600386
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700387 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700388 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700389 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700390 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700391
Felipe Lemef0823852016-06-08 13:43:08 -0700392 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700393 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700394 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700395 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700396 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800397 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700398
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700399 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700400 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700401 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
402
Jeff Sharkey32566012014-12-02 18:30:14 -0800403 /**
404 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700405 * in power save mode, except device idle (doze) still applies.
406 * TODO: An int array might be sufficient
407 */
Felipe Lemef0823852016-06-08 13:43:08 -0700408 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700409 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
410
411 /**
412 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800413 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700414 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800415 */
Felipe Lemef0823852016-06-08 13:43:08 -0700416 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700417 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700418
Felipe Lemef0823852016-06-08 13:43:08 -0700419 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700420 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
421
Felipe Lemeb85a6372016-01-14 16:16:16 -0800422 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800423 * UIDs that have been initially white-listed by system to avoid restricted background.
424 */
Felipe Lemef0823852016-06-08 13:43:08 -0700425 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800426 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
427 new SparseBooleanArray();
428
429 /**
430 * UIDs that have been initially white-listed by system to avoid restricted background,
431 * but later revoked by user.
432 */
Felipe Lemef0823852016-06-08 13:43:08 -0700433 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800434 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
435 new SparseBooleanArray();
436
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700437 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700438 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800439 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700440 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700441 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800442 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700443
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700444 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700445 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400446 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700447
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700448 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700449 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800450 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700451
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600452 /** Map from network ID to last observed meteredness state */
453 @GuardedBy("mNetworkPoliciesSecondLock")
454 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
455
Jeff Sharkey32566012014-12-02 18:30:14 -0800456 private final RemoteCallbackList<INetworkPolicyListener>
457 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700458
Dianne Hackborn497175b2014-07-01 12:56:08 -0700459 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700460 @VisibleForTesting
461 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700462
463 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700464
Felipe Lemef0823852016-06-08 13:43:08 -0700465 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700466 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700467
Svet Ganov16a16892015-04-16 10:32:04 -0700468 private final AppOpsManager mAppOps;
469
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800470 private final IPackageManager mIPm;
471
Sudheer Shankae7361852017-03-07 11:51:46 -0800472 private ActivityManagerInternal mActivityManagerInternal;
473
474 /**
475 * This is used for debugging purposes. Whenever the IUidObserver.onUidStateChanged is called,
476 * the uid and procStateSeq will be written to this and will be printed as part of dump.
477 */
478 @VisibleForTesting
479 public ProcStateSeqHistory mObservedHistory
480 = new ProcStateSeqHistory(MAX_PROC_STATE_SEQ_HISTORY);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800481
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700482 // TODO: keep whitelist of system-critical services that should never have
483 // rules enforced, such as system, phone, and radio UIDs.
484
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700485 // TODO: migrate notifications to SystemUI
486
Jeff Sharkey75279902011-05-24 18:39:45 -0700487 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700488 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
489 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700490 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
491 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700492 }
493
494 private static File getSystemDir() {
495 return new File(Environment.getDataDirectory(), "system");
496 }
497
498 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700499 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700500 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700501 mContext = checkNotNull(context, "missing context");
502 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700503 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700504 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700505 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700506 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700507 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700508 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700509 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700510 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700511
Amith Yamasani450a16b2013-09-18 16:28:50 -0700512 HandlerThread thread = new HandlerThread(TAG);
513 thread.start();
514 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700515
Makoto Onuki8e777332017-03-28 11:25:47 -0700516 // We create another thread for the UID events, which are more time-critical.
517 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
518 /*allowIo=*/ false);
519 mUidEventThread.start();
520 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
521
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700522 mSuppressDefaultPolicy = suppressDefaultPolicy;
523
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700524 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700525
526 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800527
Felipe Lemed17fda42016-04-29 11:12:45 -0700528 // Expose private service for system components to use.
529 LocalServices.addService(NetworkPolicyManagerInternal.class,
530 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700531 }
532
533 public void bindConnectivityManager(IConnectivityManager connManager) {
534 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700535 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700536
Jeff Sharkey497e4432011-06-14 17:27:29 -0700537 public void bindNotificationManager(INotificationManager notifManager) {
538 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
539 }
540
Felipe Lemef0823852016-06-08 13:43:08 -0700541 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700542 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700543 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
544 mPowerSaveWhitelistExceptIdleAppIds.clear();
545 if (whitelist != null) {
546 for (int uid : whitelist) {
547 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
548 }
549 }
550 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700551 mPowerSaveWhitelistAppIds.clear();
552 if (whitelist != null) {
553 for (int uid : whitelist) {
554 mPowerSaveWhitelistAppIds.put(uid, true);
555 }
556 }
557 } catch (RemoteException e) {
558 }
559 }
560
Felipe Lemea9505cc2016-02-26 10:28:41 -0800561 /**
562 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
563 * revoke the whitelist.
564 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700565 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800566 */
Felipe Lemef0823852016-06-08 13:43:08 -0700567 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800568 final List<UserInfo> users = mUserManager.getUsers();
569 final int numberUsers = users.size();
570
Felipe Lemea110eec2016-04-29 09:58:06 -0700571 boolean changed = false;
572 for (int i = 0; i < numberUsers; i++) {
573 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700574 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700575 }
576 return changed;
577 }
578
Felipe Lemef0823852016-06-08 13:43:08 -0700579 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700580 final SystemConfig sysConfig = SystemConfig.getInstance();
581 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800582 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
583 boolean changed = false;
584 for (int i = 0; i < allowDataUsage.size(); i++) {
585 final String pkg = allowDataUsage.valueAt(i);
586 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700587 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
588 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800589 final ApplicationInfo app;
590 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700591 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800592 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700593 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
594 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800595 continue;
596 }
597 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700598 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
599 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800600 continue;
601 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700602 final int uid = UserHandle.getUid(userId, app.uid);
603 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
604 if (LOGD)
605 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
606 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800607 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700608 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700609 if (LOGD)
610 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
611 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700612 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700613 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800614 }
615 }
616 return changed;
617 }
618
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800619 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700620 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800621 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700622 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800623 // Boost thread's priority during system server init
624 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700625 if (!isBandwidthControlEnabled()) {
626 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
627 return;
628 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700629
Felipe Leme873a83a2016-09-07 11:34:10 -0700630 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700631
Felipe Leme873a83a2016-09-07 11:34:10 -0700632 synchronized (mUidRulesFirstLock) {
633 synchronized (mNetworkPoliciesSecondLock) {
634 updatePowerSaveWhitelistUL();
635 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
636 mPowerManagerInternal.registerLowPowerModeObserver(
637 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800638 @Override
639 public int getServiceType() {
640 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700641 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800642
643 @Override
644 public void onLowPowerModeChanged(PowerSaveState result) {
645 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800646 if (LOGD) {
647 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
648 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800649 synchronized (mUidRulesFirstLock) {
650 if (mRestrictPower != enabled) {
651 mRestrictPower = enabled;
652 updateRulesForRestrictPowerUL();
653 }
654 }
655 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800656 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800657 mRestrictPower = mPowerManagerInternal.getLowPowerState(
658 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700659
660 mSystemReady = true;
661
662 // read policy from disk
663 readPolicyAL();
664
jackqdyulei29c82ab2017-03-10 14:09:16 -0800665 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700666 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800667 mRestrictBackgroundPowerState = mPowerManagerInternal
668 .getLowPowerState(ServiceType.DATA_SAVER);
669 final boolean localRestrictBackground =
670 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700671 if (localRestrictBackground && !mLoadedRestrictBackground) {
672 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800673 }
674 mPowerManagerInternal.registerLowPowerModeObserver(
675 new PowerManagerInternal.LowPowerModeListener() {
676 @Override
677 public int getServiceType() {
678 return ServiceType.DATA_SAVER;
679 }
680
681 @Override
682 public void onLowPowerModeChanged(PowerSaveState result) {
683 synchronized (mUidRulesFirstLock) {
684 updateRestrictBackgroundByLowPowerModeUL(result);
685 }
686 }
687 });
688
Felipe Leme873a83a2016-09-07 11:34:10 -0700689 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
690 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700691 }
Felipe Lemef0823852016-06-08 13:43:08 -0700692
Sudheer Shanka543339f2017-07-28 15:18:07 -0700693 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700694 updateRulesForGlobalChangeAL(false);
695 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700696 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800697 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700698
Sudheer Shankae7361852017-03-07 11:51:46 -0800699 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700700 try {
701 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000702 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800703 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700704 mNetworkManager.registerObserver(mAlertObserver);
705 } catch (RemoteException e) {
706 // ignored; both services live in system_server
707 }
708
709 // listen for changes to power save whitelist
710 final IntentFilter whitelistFilter = new IntentFilter(
711 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
712 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
713
Felipe Leme873a83a2016-09-07 11:34:10 -0700714 // watch for network interfaces to be claimed
715 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
716 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
717
718 // listen for package changes to update policy
719 final IntentFilter packageFilter = new IntentFilter();
720 packageFilter.addAction(ACTION_PACKAGE_ADDED);
721 packageFilter.addDataScheme("package");
722 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
723
724 // listen for UID changes to update policy
725 mContext.registerReceiver(
726 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
727
728 // listen for user changes to update policy
729 final IntentFilter userFilter = new IntentFilter();
730 userFilter.addAction(ACTION_USER_ADDED);
731 userFilter.addAction(ACTION_USER_REMOVED);
732 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
733
734 // listen for stats update events
735 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
736 mContext.registerReceiver(
737 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
738
739 // listen for restrict background changes from notifications
740 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
741 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
742
743 // listen for snooze warning from notifications
744 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
745 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
746 MANAGE_NETWORK_POLICY, mHandler);
747
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600748 // listen for configured wifi networks to be loaded
749 final IntentFilter wifiFilter =
750 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
751 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700752
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700753 // listen for carrier config changes to update data cycle information
754 final IntentFilter carrierConfigFilter = new IntentFilter(
755 ACTION_CARRIER_CONFIG_CHANGED);
756 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
757
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600758 // listen for meteredness changes
759 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
760 new NetworkRequest.Builder().build(), mNetworkCallback);
761
Felipe Leme873a83a2016-09-07 11:34:10 -0700762 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800763 // tell systemReady() that the service has been initialized
764 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700765 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800766 // Restore the default priority after init is done
767 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700768 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700769 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700770 }
771
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800772 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
773 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
774 mHandler.post(() -> initService(initCompleteSignal));
775 return initCompleteSignal;
776 }
777
778 public void systemReady(CountDownLatch initCompleteSignal) {
779 // wait for initService to complete
780 try {
781 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
782 throw new IllegalStateException("Service " + TAG +" init timeout");
783 }
784 } catch (InterruptedException e) {
785 Thread.currentThread().interrupt();
786 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
787 }
788 }
789
Sudheer Shankac9d94072017-02-22 22:13:55 +0000790 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700791 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700792 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
793 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700794 }
795
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700796 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700797 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700798 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700799
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700800 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700801 }
802
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700803 @Override public void onUidIdle(int uid, boolean disabled) {
804 }
805
806 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700807 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700808 };
809
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700810 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700811 @Override
812 public void onReceive(Context context, Intent intent) {
813 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700814 synchronized (mUidRulesFirstLock) {
815 updatePowerSaveWhitelistUL();
816 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700817 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700818 }
819 }
820 };
821
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700822 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700823 @Override
824 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700825 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700826
827 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700828 final int uid = intent.getIntExtra(EXTRA_UID, -1);
829 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700830
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700831 if (ACTION_PACKAGE_ADDED.equals(action)) {
832 // update rules for UID, since it might be subject to
833 // global background data policy
834 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700835 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700836 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700837 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700838 }
839 }
840 };
841
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700842 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700843 @Override
844 public void onReceive(Context context, Intent intent) {
845 // on background handler thread, and UID_REMOVED is protected
846
847 final int uid = intent.getIntExtra(EXTRA_UID, -1);
848 if (uid == -1) return;
849
850 // remove any policy and update rules to clean up
851 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700852 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700853 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700854 synchronized (mNetworkPoliciesSecondLock) {
855 writePolicyAL();
856 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700857 }
858 }
859 };
860
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700861 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700862 @Override
863 public void onReceive(Context context, Intent intent) {
864 // on background handler thread, and USER_ADDED and USER_REMOVED
865 // broadcasts are protected
866
867 final String action = intent.getAction();
868 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
869 if (userId == -1) return;
870
Amith Yamasani15e472352015-04-24 19:06:07 -0700871 switch (action) {
872 case ACTION_USER_REMOVED:
873 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700874 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800875 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700876 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700877 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700878 if (action == ACTION_USER_ADDED) {
879 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700880 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700881 }
882 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700883 synchronized (mNetworkPoliciesSecondLock) {
884 updateRulesForGlobalChangeAL(true);
885 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700886 }
887 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700888 }
889 }
890 };
891
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700892 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700893 * Receiver that watches for {@link INetworkStatsService} updates, which we
894 * use to check against {@link NetworkPolicy#warningBytes}.
895 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700896 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700897 @Override
898 public void onReceive(Context context, Intent intent) {
899 // on background handler thread, and verified
900 // READ_NETWORK_USAGE_HISTORY permission above.
901
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800902 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700903 synchronized (mNetworkPoliciesSecondLock) {
904 updateNetworkEnabledNL();
905 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700906 }
907 }
908 };
909
910 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700911 * Receiver that watches for {@link Notification} control of
912 * {@link #mRestrictBackground}.
913 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700914 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700915 @Override
916 public void onReceive(Context context, Intent intent) {
917 // on background handler thread, and verified MANAGE_NETWORK_POLICY
918 // permission above.
919
920 setRestrictBackground(false);
921 }
922 };
923
924 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800925 * Receiver that watches for {@link Notification} control of
926 * {@link NetworkPolicy#lastWarningSnooze}.
927 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700928 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800929 @Override
930 public void onReceive(Context context, Intent intent) {
931 // on background handler thread, and verified MANAGE_NETWORK_POLICY
932 // permission above.
933
934 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
935 performSnooze(template, TYPE_WARNING);
936 }
937 };
938
939 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600940 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -0600941 * we can perform upgrade logic. After initial upgrade logic, it updates
942 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700943 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600944 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700945 @Override
946 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900947 synchronized (mUidRulesFirstLock) {
948 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600949 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600950 }
951 }
952 // Only need to perform upgrade logic once
953 mContext.unregisterReceiver(this);
954 }
955 };
956
957 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
958 @Override
959 public void onCapabilitiesChanged(Network network,
960 NetworkCapabilities networkCapabilities) {
961 if (network == null || networkCapabilities == null) return;
962
963 synchronized (mNetworkPoliciesSecondLock) {
964 final boolean oldMetered = mNetworkMetered.get(network.netId, false);
965 final boolean newMetered = !networkCapabilities
966 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
967
968 if ((oldMetered != newMetered) || mNetworkMetered.indexOfKey(network.netId) < 0) {
969 mNetworkMetered.put(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -0600970 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700971 }
972 }
973 }
974 };
975
976 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700977 * Observer that watches for {@link INetworkManagementService} alerts.
978 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700979 final private INetworkManagementEventObserver mAlertObserver
980 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700981 @Override
982 public void limitReached(String limitName, String iface) {
983 // only someone like NMS should be calling us
984 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
985
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800986 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
987 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700988 }
989 }
990 };
991
992 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700993 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
994 * to show visible notifications as needed.
995 */
Felipe Lemef0823852016-06-08 13:43:08 -0700996 void updateNotificationsNL() {
997 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700998
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700999 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001000 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001001 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001002
1003 // TODO: when switching to kernel notifications, compute next future
1004 // cycle boundary to recompute notifications.
1005
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001006 // examine stats for each active policy
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001007 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1008 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001009 // ignore policies that aren't relevant to user
1010 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001011 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001012
Jeff Sharkey53313d72017-07-13 16:47:32 -06001013 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1014 .cycleIterator(policy).next();
1015 final long start = cycle.first.toInstant().toEpochMilli();
1016 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001017 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001018
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001019 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001020 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001021 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1022 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001023 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001024 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001025 }
1026
Jeff Sharkey497e4432011-06-14 17:27:29 -07001027 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001028 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001029
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001030 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001031 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001032 }
1033 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001034 }
1035
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001036 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001037 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001038 final NotificationId notificationId = beforeNotifs.valueAt(i);
1039 if (!mActiveNotifs.contains(notificationId)) {
1040 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001041 }
1042 }
1043 }
1044
1045 /**
1046 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001047 * current device state, such as when
1048 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1049 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001050 */
1051 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001052 if (template.isMatchRuleMobile()) {
1053 final TelephonyManager tele = TelephonyManager.from(mContext);
1054 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001055
Jeff Sharkey32566012014-12-02 18:30:14 -08001056 // Mobile template is relevant when any active subscriber matches
1057 final int[] subIds = sub.getActiveSubscriptionIdList();
1058 for (int subId : subIds) {
1059 final String subscriberId = tele.getSubscriberId(subId);
1060 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001061 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001062 if (template.matches(probeIdent)) {
1063 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001064 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001065 }
1066 return false;
1067 } else {
1068 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001069 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001070 }
1071
1072 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001073 * Notify that given {@link NetworkTemplate} is over
1074 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1075 */
Felipe Lemef0823852016-06-08 13:43:08 -07001076 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001077 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001078 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001079 mOverLimitNotified.add(template);
1080 }
1081 }
1082
Felipe Lemef0823852016-06-08 13:43:08 -07001083 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001084 mOverLimitNotified.remove(template);
1085 }
1086
1087 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001088 * Show notification for combined {@link NetworkPolicy} and specific type,
1089 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1090 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001091 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001092 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001093 final Notification.Builder builder =
1094 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001095 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001096 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001097 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001098 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001099
1100 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001101 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001102 switch (type) {
1103 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001104 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001105 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001106
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001107 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001108 builder.setTicker(title);
1109 builder.setContentTitle(title);
1110 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001111 builder.setDefaults(Notification.DEFAULT_ALL);
Julia Reynoldsbad42972017-04-25 13:52:49 -04001112 builder.setChannelId(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001113
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001114 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1115 builder.setDeleteIntent(PendingIntent.getBroadcast(
1116 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1117
Wei Liu546cb772016-07-21 16:19:01 -07001118 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001119 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001120 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1121
Jeff Sharkey497e4432011-06-14 17:27:29 -07001122 break;
1123 }
1124 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001125 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001126
1127 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001128 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001129 switch (policy.template.getMatchRule()) {
1130 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001131 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001132 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001133 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001134 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001135 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001136 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001137 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001138 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001139 case MATCH_WIFI:
1140 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001141 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001142 break;
1143 default:
1144 title = null;
1145 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001146 }
1147
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001148 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001149 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001150 builder.setTicker(title);
1151 builder.setContentTitle(title);
1152 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001153
Wei Liu546cb772016-07-21 16:19:01 -07001154 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001155 builder.setContentIntent(PendingIntent.getActivity(
1156 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1157 break;
1158 }
1159 case TYPE_LIMIT_SNOOZED: {
1160 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001161 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001162 Formatter.formatFileSize(mContext, overBytes));
1163
1164 final CharSequence title;
1165 switch (policy.template.getMatchRule()) {
1166 case MATCH_MOBILE_3G_LOWER:
1167 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1168 break;
1169 case MATCH_MOBILE_4G:
1170 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1171 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001172 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001173 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1174 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001175 case MATCH_WIFI:
1176 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1177 break;
1178 default:
1179 title = null;
1180 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001181 }
1182
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001183 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001184 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001185 builder.setTicker(title);
1186 builder.setContentTitle(title);
1187 builder.setContentText(body);
1188
Wei Liu546cb772016-07-21 16:19:01 -07001189 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001190 builder.setContentIntent(PendingIntent.getActivity(
1191 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001192 break;
1193 }
1194 }
1195
1196 // TODO: move to NotificationManager once we can mock it
1197 try {
1198 final String packageName = mContext.getPackageName();
Chris Wren193ae6b2017-03-31 15:17:11 -04001199 if (!TextUtils.isEmpty(body)) {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001200 builder.setStyle(new Notification.BigTextStyle()
1201 .bigText(body));
1202 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001203 mNotifManager.enqueueNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001204 packageName, packageName, notificationId.getTag(), notificationId.getId(),
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001205 builder.build(), UserHandle.USER_ALL);
Chris Wren193ae6b2017-03-31 15:17:11 -04001206 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001207 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001208 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001209 }
1210 }
1211
Chris Wren193ae6b2017-03-31 15:17:11 -04001212 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001213 // TODO: move to NotificationManager once we can mock it
1214 try {
1215 final String packageName = mContext.getPackageName();
1216 mNotifManager.cancelNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001217 packageName, notificationId.getTag(), notificationId.getId(),
1218 UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001219 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001220 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001221 }
1222 }
1223
1224 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001225 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001226 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001227 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001228 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001229 @Override
1230 public void onReceive(Context context, Intent intent) {
1231 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1232 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001233
1234 maybeRefreshTrustedTime();
Hugo Benichi446c9c92017-04-10 09:41:10 +09001235 synchronized (mUidRulesFirstLock) {
1236 synchronized (mNetworkPoliciesSecondLock) {
1237 ensureActiveMobilePolicyAL();
1238 normalizePoliciesNL();
1239 updateNetworkEnabledNL();
1240 updateNetworkRulesNL();
1241 updateNotificationsNL();
1242 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001243 }
1244 }
1245 };
1246
1247 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001248 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1249 * if necessary.
1250 *
1251 * @param subId that has its associated NetworkPolicy updated if necessary
1252 * @return if any policies were updated
1253 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001254 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1255 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001256
1257 boolean policyUpdated = false;
1258 final String subscriberId = TelephonyManager.from(mContext).getSubscriberId(subId);
1259
1260 // find and update the mobile NetworkPolicy for this subscriber id
1261 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1262 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1263 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1264 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1265 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001266 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1267 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001268 }
1269 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001270 return policyUpdated;
1271 }
1272
1273 /**
1274 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1275 *
1276 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1277 * to do so, it returns the fallback value.
1278 *
1279 * @param config The CarrierConfig to read the value from.
1280 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1281 * @return cycleDay to use in the mobile NetworkPolicy.
1282 */
1283 @VisibleForTesting
1284 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1285 int fallbackCycleDay) {
1286 if (config == null) {
1287 return fallbackCycleDay;
1288 }
1289 int cycleDay =
1290 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1291 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1292 return fallbackCycleDay;
1293 }
1294 // validate cycleDay value
1295 final Calendar cal = Calendar.getInstance();
1296 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1297 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1298 Slog.e(TAG, "Invalid date in "
1299 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1300 return fallbackCycleDay;
1301 }
1302 return cycleDay;
1303 }
1304
1305 /**
1306 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1307 *
1308 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1309 * to do so, it returns the fallback value.
1310 *
1311 * @param config The CarrierConfig to read the value from.
1312 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1313 * @return warningBytes to use in the mobile NetworkPolicy.
1314 */
1315 @VisibleForTesting
1316 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1317 long fallbackWarningBytes) {
1318 if (config == null) {
1319 return fallbackWarningBytes;
1320 }
1321 long warningBytes =
1322 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1323
1324 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1325 return WARNING_DISABLED;
1326 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1327 return getPlatformDefaultWarningBytes();
1328 } else if (warningBytes < 0) {
1329 Slog.e(TAG, "Invalid value in "
1330 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1331 + "non-negative value but got: " + warningBytes);
1332 return fallbackWarningBytes;
1333 }
1334
1335 return warningBytes;
1336 }
1337
1338 /**
1339 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1340 *
1341 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1342 * to do so, it returns the fallback value.
1343 *
1344 * @param config The CarrierConfig to read the value from.
1345 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1346 * @return limitBytes to use in the mobile NetworkPolicy.
1347 */
1348 @VisibleForTesting
1349 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1350 long fallbackLimitBytes) {
1351 if (config == null) {
1352 return fallbackLimitBytes;
1353 }
1354 long limitBytes =
1355 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1356
1357 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1358 return LIMIT_DISABLED;
1359 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1360 return getPlatformDefaultLimitBytes();
1361 } else if (limitBytes < 0) {
1362 Slog.e(TAG, "Invalid value in "
1363 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1364 + "non-negative value but got: " + limitBytes);
1365 return fallbackLimitBytes;
1366 }
1367 return limitBytes;
1368 }
1369
1370 /**
1371 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1372 */
1373 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1374 @Override
1375 public void onReceive(Context context, Intent intent) {
1376 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1377 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1378
1379 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1380 return;
1381 }
1382 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
1383 final TelephonyManager tele = TelephonyManager.from(mContext);
1384 final String subscriberId = tele.getSubscriberId(subId);
1385
1386 maybeRefreshTrustedTime();
1387 synchronized (mUidRulesFirstLock) {
1388 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001389 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001390 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001391 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001392 if (!updated) return;
1393 // update network and notification rules, as the data cycle changed and it's
1394 // possible that we should be triggering warnings/limits now
1395 handleNetworkPoliciesUpdateAL(true);
1396 }
1397 }
1398 }
1399 };
1400
1401 /**
1402 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1403 * one has been updated.
1404 *
1405 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1406 * update.
1407 */
1408 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1409 if (shouldNormalizePolicies) {
1410 normalizePoliciesNL();
1411 }
1412 updateNetworkEnabledNL();
1413 updateNetworkRulesNL();
1414 updateNotificationsNL();
1415 writePolicyAL();
1416 }
1417
1418 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001419 * Proactively control network data connections when they exceed
1420 * {@link NetworkPolicy#limitBytes}.
1421 */
Felipe Lemef0823852016-06-08 13:43:08 -07001422 void updateNetworkEnabledNL() {
1423 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001424
1425 // TODO: reset any policy-disabled networks when any policy is removed
1426 // completely, which is currently rare case.
1427
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001428 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1429 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001430 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001431 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001432 setNetworkTemplateEnabled(policy.template, true);
1433 continue;
1434 }
1435
Jeff Sharkey53313d72017-07-13 16:47:32 -06001436 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1437 .cycleIterator(policy).next();
1438 final long start = cycle.first.toInstant().toEpochMilli();
1439 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001440 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001441
1442 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001443 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1444 && policy.lastLimitSnooze < start;
1445 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001446
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001447 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001448 }
1449 }
1450
1451 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001452 * Proactively disable networks that match the given
1453 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001454 */
1455 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001456 // TODO: reach into ConnectivityManager to proactively disable bringing
1457 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001458
1459 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1460 // If mobile data usage hits the limit or if the user resumes the data, we need to
1461 // notify telephony.
1462 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1463 final TelephonyManager tm = TelephonyManager.from(mContext);
1464
1465 final int[] subIds = sm.getActiveSubscriptionIdList();
1466 for (int subId : subIds) {
1467 final String subscriberId = tm.getSubscriberId(subId);
1468 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1469 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1470 // Template is matched when subscriber id matches.
1471 if (template.matches(probeIdent)) {
1472 tm.setPolicyDataEnabled(enabled, subId);
1473 }
1474 }
1475 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001476 }
1477
1478 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001479 * Collect all ifaces from a {@link NetworkState} into the given set.
1480 */
1481 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1482 final String baseIface = state.linkProperties.getInterfaceName();
1483 if (baseIface != null) {
1484 ifaces.add(baseIface);
1485 }
1486 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1487 final String stackedIface = stackedLink.getInterfaceName();
1488 if (stackedIface != null) {
1489 ifaces.add(stackedIface);
1490 }
1491 }
1492 }
1493
1494 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001495 * Examine all connected {@link NetworkState}, looking for
1496 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1497 * remaining quota based on usage cycle and historical stats.
1498 */
Felipe Lemef0823852016-06-08 13:43:08 -07001499 void updateNetworkRulesNL() {
1500 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001501
1502 final NetworkState[] states;
1503 try {
1504 states = mConnManager.getAllNetworkState();
1505 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001506 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001507 return;
1508 }
1509
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001510 // First, generate identities of all connected networks so we can
1511 // quickly compare them against all defined policies below.
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001512 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001513 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001514 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001515 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001516 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001517 }
1518 }
1519
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001520 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001521 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001522
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001523 // For every well-defined policy, compute remaining data based on
1524 // current cycle and historical stats, and push to kernel.
1525 final ArraySet<String> matchingIfaces = new ArraySet<>();
1526 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1527 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1528
1529 // Collect all ifaces that match this policy
1530 matchingIfaces.clear();
1531 for (int j = identified.size() - 1; j >= 0; j--) {
1532 if (policy.template.matches(identified.valueAt(j))) {
1533 collectIfaces(matchingIfaces, identified.keyAt(j));
1534 }
1535 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001536
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001537 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001538 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001539 }
1540
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001541 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001542 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001543 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001544 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001545 if (hasLimit && policy.hasCycle()) {
1546 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1547 .cycleIterator(policy).next();
1548 final long start = cycle.first.toInstant().toEpochMilli();
1549 final long end = cycle.second.toInstant().toEpochMilli();
1550 final long totalBytes = getTotalBytes(policy.template, start, end);
1551
1552 if (policy.lastLimitSnooze >= start) {
1553 // snoozing past quota, but we still need to restrict apps,
1554 // so push really high quota.
1555 quotaBytes = Long.MAX_VALUE;
1556 } else {
1557 // remaining "quota" bytes are based on total usage in
1558 // current cycle. kernel doesn't like 0-byte rules, so we
1559 // set 1-byte quota and disable the radio later.
1560 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1561 }
1562 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001563 // metered network, but no policy limit; we still need to
1564 // restrict apps, so push really high quota.
1565 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001566 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001567
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001568 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001569 // TODO: switch to shared quota once NMS supports
1570 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001571 }
1572
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001573 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1574 final String iface = matchingIfaces.valueAt(j);
1575 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001576 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001577 }
1578 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001579
1580 // keep track of lowest warning or limit of active policies
1581 if (hasWarning && policy.warningBytes < lowestRule) {
1582 lowestRule = policy.warningBytes;
1583 }
1584 if (hasLimit && policy.limitBytes < lowestRule) {
1585 lowestRule = policy.limitBytes;
1586 }
1587 }
1588
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001589 // One final pass to catch any metered ifaces that don't have explicitly
1590 // defined policies; typically Wi-Fi networks.
1591 for (NetworkState state : states) {
1592 if (state.networkInfo != null && state.networkInfo.isConnected()
1593 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1594 matchingIfaces.clear();
1595 collectIfaces(matchingIfaces, state);
1596 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1597 final String iface = matchingIfaces.valueAt(j);
1598 if (!newMeteredIfaces.contains(iface)) {
1599 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1600 newMeteredIfaces.add(iface);
1601 }
1602 }
1603 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001604 }
1605
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001606 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001607 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1608 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001609 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001610 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001611 }
1612 }
1613 mMeteredIfaces = newMeteredIfaces;
1614
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001615 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001616 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001617
1618 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001619 }
1620
1621 /**
1622 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1623 * have at least a default mobile policy defined.
1624 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001625 private void ensureActiveMobilePolicyAL() {
1626 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001627 if (mSuppressDefaultPolicy) return;
1628
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001629 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001630 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001631
Jeff Sharkey32566012014-12-02 18:30:14 -08001632 final int[] subIds = sub.getActiveSubscriptionIdList();
1633 for (int subId : subIds) {
1634 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001635 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001636 }
1637 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001638
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001639 /**
1640 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1641 * have at least a default mobile policy defined.
1642 *
1643 * @param subId to build a default policy for
1644 * @param subscriberId that we check for an existing policy
1645 * @return true if a mobile network policy was added, or false one already existed.
1646 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001647 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001648 // Poke around to see if we already have a policy
1649 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001650 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001651 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1652 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1653 if (template.matches(probeIdent)) {
1654 if (LOGD) {
1655 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1656 + NetworkIdentity.scrubSubscriberId(subscriberId));
1657 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001658 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001659 }
1660 }
1661
Jeff Sharkey32566012014-12-02 18:30:14 -08001662 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1663 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001664 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001665 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001666 return true;
1667 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001668
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001669 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001670 final int dataWarningConfig = mContext.getResources().getInteger(
1671 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001672 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001673 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001674 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001675 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001676 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001677 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001678
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001679 private long getPlatformDefaultLimitBytes() {
1680 return LIMIT_DISABLED;
1681 }
1682
1683 @VisibleForTesting
1684 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001685 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001686 final RecurrenceRule cycleRule = NetworkPolicy
1687 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001688 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001689 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1690 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1691 synchronized (mUidRulesFirstLock) {
1692 synchronized (mNetworkPoliciesSecondLock) {
1693 updateDefaultMobilePolicyAL(subId, policy);
1694 }
1695 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001696 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001697 }
1698
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001699 /**
1700 * Update the given {@link NetworkPolicy} based on any carrier-provided
1701 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1702 * Leaves policy untouched if the user has modified it.
1703 *
1704 * @return if the policy was modified
1705 */
1706 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1707 if (!policy.inferred) {
1708 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1709 return false;
1710 }
1711
1712 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1713 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1714 policy.lastLimitSnooze, policy.metered, policy.inferred);
1715
1716 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1717 if (!ArrayUtils.isEmpty(plans)) {
1718 final SubscriptionPlan plan = plans[0];
1719 policy.cycleRule = plan.getCycleRule();
1720 final long planLimitBytes = plan.getDataLimitBytes();
1721 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1722 policy.warningBytes = getPlatformDefaultWarningBytes();
1723 policy.limitBytes = getPlatformDefaultLimitBytes();
1724 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1725 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1726 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1727 } else {
1728 policy.warningBytes = (planLimitBytes * 9) / 10;
1729 switch (plan.getDataLimitBehavior()) {
1730 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1731 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1732 policy.limitBytes = planLimitBytes;
1733 break;
1734 default:
1735 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1736 break;
1737 }
1738 }
1739 } else {
1740 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1741 final int currentCycleDay;
1742 if (policy.cycleRule.isMonthly()) {
1743 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1744 } else {
1745 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1746 }
1747 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1748 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1749 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1750 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1751 }
1752
1753 if (policy.equals(original)) {
1754 return false;
1755 } else {
1756 Slog.d(TAG, "Updated " + original + " to " + policy);
1757 return true;
1758 }
1759 }
1760
Felipe Lemef0823852016-06-08 13:43:08 -07001761 private void readPolicyAL() {
1762 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001763
1764 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001765 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001766 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001767 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001768 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001769
1770 FileInputStream fis = null;
1771 try {
1772 fis = mPolicyFile.openRead();
1773 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001774 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001775
Felipe Leme46b451f2016-08-19 08:46:17 -07001776 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1777 // to skip UIDs that were explicitly blacklisted.
1778 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1779
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001780 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001781 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001782 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001783 while ((type = in.next()) != END_DOCUMENT) {
1784 final String tag = in.getName();
1785 if (type == START_TAG) {
1786 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001787 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001788 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07001789 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
1790 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001791 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1792 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1793 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001794 final String networkId;
1795 if (version >= VERSION_ADDED_NETWORK_ID) {
1796 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1797 } else {
1798 networkId = null;
1799 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001800 final RecurrenceRule cycleRule;
1801 if (version >= VERSION_ADDED_CYCLE) {
1802 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1803 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1804 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1805 cycleRule = new RecurrenceRule(
1806 RecurrenceRule.convertZonedDateTime(start),
1807 RecurrenceRule.convertZonedDateTime(end),
1808 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001809 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001810 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1811 final String cycleTimezone;
1812 if (version >= VERSION_ADDED_TIMEZONE) {
1813 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1814 } else {
1815 cycleTimezone = "UTC";
1816 }
1817 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001818 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001819 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1820 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001821 final long lastLimitSnooze;
1822 if (version >= VERSION_SPLIT_SNOOZE) {
1823 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1824 } else if (version >= VERSION_ADDED_SNOOZE) {
1825 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001826 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001827 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001828 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001829 final boolean metered;
1830 if (version >= VERSION_ADDED_METERED) {
1831 metered = readBooleanAttribute(in, ATTR_METERED);
1832 } else {
1833 switch (networkTemplate) {
1834 case MATCH_MOBILE_3G_LOWER:
1835 case MATCH_MOBILE_4G:
1836 case MATCH_MOBILE_ALL:
1837 metered = true;
1838 break;
1839 default:
1840 metered = false;
1841 }
1842 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001843 final long lastWarningSnooze;
1844 if (version >= VERSION_SPLIT_SNOOZE) {
1845 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1846 } else {
1847 lastWarningSnooze = SNOOZE_NEVER;
1848 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001849 final boolean inferred;
1850 if (version >= VERSION_ADDED_INFERRED) {
1851 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1852 } else {
1853 inferred = false;
1854 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001855
Jeff Sharkey32566012014-12-02 18:30:14 -08001856 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1857 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001858 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001859 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
1860 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001861 lastLimitSnooze, metered, inferred));
1862 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001863
1864 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
1865 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1866 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1867 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1868 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
1869 RecurrenceRule.convertZonedDateTime(start),
1870 RecurrenceRule.convertZonedDateTime(end),
1871 RecurrenceRule.convertPeriod(period));
1872 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
1873 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
1874
1875 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
1876 SubscriptionPlan.BYTES_UNKNOWN);
1877 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
1878 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
1879 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
1880 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
1881 builder.setDataLimit(limitBytes, limitBehavior);
1882 }
1883
1884 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
1885 SubscriptionPlan.BYTES_UNKNOWN);
1886 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
1887 SubscriptionPlan.TIME_UNKNOWN);
1888 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
1889 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
1890 builder.setDataUsage(usageBytes, usageTime);
1891 }
1892
1893 final int subId = readIntAttribute(in, ATTR_SUB_ID);
1894 final SubscriptionPlan plan = builder.build();
1895 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
1896 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
1897
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001898 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
1899 mSubscriptionPlansOwner.put(subId, ownerPackage);
1900
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001901 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001902 final int uid = readIntAttribute(in, ATTR_UID);
1903 final int policy = readIntAttribute(in, ATTR_POLICY);
1904
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001905 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001906 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001907 } else {
1908 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1909 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001910 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001911 final int appId = readIntAttribute(in, ATTR_APP_ID);
1912 final int policy = readIntAttribute(in, ATTR_POLICY);
1913
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001914 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001915 // app policy is deprecated so this is only used in pre system user split.
1916 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001917 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001918 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001919 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001920 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001921 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001922 } else if (TAG_WHITELIST.equals(tag)) {
1923 insideWhitelist = true;
1924 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1925 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001926 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001927 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1928 final int uid = readIntAttribute(in, ATTR_UID);
1929 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001930 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001931 } else if (type == END_TAG) {
1932 if (TAG_WHITELIST.equals(tag)) {
1933 insideWhitelist = false;
1934 }
1935
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001936 }
1937 }
1938
Felipe Leme46b451f2016-08-19 08:46:17 -07001939 final int size = whitelistedRestrictBackground.size();
1940 for (int i = 0; i < size; i++) {
1941 final int uid = whitelistedRestrictBackground.keyAt(i);
1942 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1943 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1944 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1945 + " because its policy is " + uidPoliciesToString(policy));
1946 continue;
1947 }
1948 if (UserHandle.isApp(uid)) {
1949 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1950 if (LOGV)
1951 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1952 setUidPolicyUncheckedUL(uid, newPolicy, false);
1953 } else {
1954 Slog.w(TAG, "unable to update policy on UID " + uid);
1955 }
1956 }
1957
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001958 } catch (FileNotFoundException e) {
1959 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001960 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001961 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001962 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001963 } finally {
1964 IoUtils.closeQuietly(fis);
1965 }
1966 }
1967
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001968 /**
1969 * Upgrade legacy background data flags, notifying listeners of one last
1970 * change to always-true.
1971 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001972 private void upgradeDefaultBackgroundDataUL() {
1973 // This method is only called when we're unable to find the network policy flag, which
1974 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001975
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001976 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07001977 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001978 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
1979
1980 // NOTE: We used to read the legacy setting here :
1981 //
1982 // final int legacyFlagValue = Settings.Secure.getInt(
1983 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
1984 //
1985 // This is no longer necessary because we will never upgrade directly from Gingerbread
1986 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
1987 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001988 }
1989
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001990 /**
1991 * Perform upgrade step of moving any user-defined meterness overrides over
1992 * into {@link WifiConfiguration}.
1993 */
1994 private void upgradeWifiMeteredOverrideAL() {
1995 boolean modified = false;
1996 final WifiManager wm = mContext.getSystemService(WifiManager.class);
1997 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
1998 for (int i = 0; i < mNetworkPolicy.size(); ) {
1999 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2000 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2001 && !policy.inferred) {
2002 mNetworkPolicy.removeAt(i);
2003 modified = true;
2004
2005 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2006 for (WifiConfiguration config : configs) {
2007 if (Objects.equals(resolveNetworkId(config), networkId)) {
2008 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2009 config.meteredOverride = policy.metered
2010 ? WifiConfiguration.METERED_OVERRIDE_METERED
2011 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2012 wm.updateNetwork(config);
2013 }
2014 }
2015 } else {
2016 i++;
2017 }
2018 }
2019 if (modified) {
2020 writePolicyAL();
2021 }
2022 }
2023
Felipe Lemef0823852016-06-08 13:43:08 -07002024 void writePolicyAL() {
2025 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002026
2027 FileOutputStream fos = null;
2028 try {
2029 fos = mPolicyFile.startWrite();
2030
2031 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002032 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002033 out.startDocument(null, true);
2034
2035 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002036 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002037 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002038
2039 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002040 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2041 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002042 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002043 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002044
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002045 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002046 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2047 final String subscriberId = template.getSubscriberId();
2048 if (subscriberId != null) {
2049 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002050 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002051 final String networkId = template.getNetworkId();
2052 if (networkId != null) {
2053 out.attribute(null, ATTR_NETWORK_ID, networkId);
2054 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002055 writeStringAttribute(out, ATTR_CYCLE_START,
2056 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2057 writeStringAttribute(out, ATTR_CYCLE_END,
2058 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2059 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2060 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002061 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2062 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002063 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2064 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002065 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002066 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002067 out.endTag(null, TAG_NETWORK_POLICY);
2068 }
2069
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002070 // write all known subscription plans
2071 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2072 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002073 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002074 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2075 if (ArrayUtils.isEmpty(plans)) continue;
2076
2077 for (SubscriptionPlan plan : plans) {
2078 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2079 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002080 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002081 final RecurrenceRule cycleRule = plan.getCycleRule();
2082 writeStringAttribute(out, ATTR_CYCLE_START,
2083 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2084 writeStringAttribute(out, ATTR_CYCLE_END,
2085 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2086 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2087 RecurrenceRule.convertPeriod(cycleRule.period));
2088 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2089 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2090 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2091 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2092 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2093 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2094 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2095 }
2096 }
2097
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002098 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002099 for (int i = 0; i < mUidPolicy.size(); i++) {
2100 final int uid = mUidPolicy.keyAt(i);
2101 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002102
Jeff Sharkey497e4432011-06-14 17:27:29 -07002103 // skip writing empty policies
2104 if (policy == POLICY_NONE) continue;
2105
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002106 out.startTag(null, TAG_UID_POLICY);
2107 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002108 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002109 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002110 }
2111
2112 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002113
2114 // write all whitelists
2115 out.startTag(null, TAG_WHITELIST);
2116
Felipe Lemea9505cc2016-02-26 10:28:41 -08002117 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002118 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002119 for (int i = 0; i < size; i++) {
2120 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2121 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2122 writeIntAttribute(out, ATTR_UID, uid);
2123 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2124 }
2125
Felipe Lemeb85a6372016-01-14 16:16:16 -08002126 out.endTag(null, TAG_WHITELIST);
2127
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002128 out.endDocument();
2129
2130 mPolicyFile.finishWrite(fos);
2131 } catch (IOException e) {
2132 if (fos != null) {
2133 mPolicyFile.failWrite(fos);
2134 }
2135 }
2136 }
2137
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002138 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002139 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002140 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002141
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002142 if (!UserHandle.isApp(uid)) {
2143 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002144 }
Felipe Lemef0823852016-06-08 13:43:08 -07002145 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002146 final long token = Binder.clearCallingIdentity();
2147 try {
2148 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2149 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002150 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002151 }
2152 } finally {
2153 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002154 }
2155 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002156 }
2157
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002158 @Override
2159 public void addUidPolicy(int uid, int policy) {
2160 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002161
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002162 if (!UserHandle.isApp(uid)) {
2163 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2164 }
2165
Felipe Lemef0823852016-06-08 13:43:08 -07002166 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002167 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2168 policy |= oldPolicy;
2169 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002170 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002171 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002172 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002173 }
2174
2175 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002176 public void removeUidPolicy(int uid, int policy) {
2177 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2178
2179 if (!UserHandle.isApp(uid)) {
2180 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2181 }
2182
Felipe Lemef0823852016-06-08 13:43:08 -07002183 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002184 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2185 policy = oldPolicy & ~policy;
2186 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002187 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002188 }
2189 }
2190 }
2191
Felipe Lemef0823852016-06-08 13:43:08 -07002192 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2193 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002194
Felipe Leme57e3d312016-08-23 14:42:52 -07002195 final boolean notifyApp;
2196 if (!isUidValidForWhitelistRules(uid)) {
2197 notifyApp = false;
2198 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002199 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2200 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2201 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2202 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002203 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2204 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002205 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2206 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2207 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2208 if (LOGD)
2209 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2210 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2211 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002212 notifyApp = wasBlocked != isBlocked;
2213 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002214 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2215 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002216 }
2217
Felipe Lemef0823852016-06-08 13:43:08 -07002218 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002219 if (policy == POLICY_NONE) {
2220 mUidPolicy.delete(uid);
2221 } else {
2222 mUidPolicy.put(uid, policy);
2223 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002224
2225 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002226 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002227 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002228 synchronized (mNetworkPoliciesSecondLock) {
2229 writePolicyAL();
2230 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002231 }
2232 }
2233
2234 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002235 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002236 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2237
Felipe Lemef0823852016-06-08 13:43:08 -07002238 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002239 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002240 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002241 }
2242
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002243 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002244 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002245 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2246
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002247 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002248 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002249 for (int i = 0; i < mUidPolicy.size(); i++) {
2250 final int uid = mUidPolicy.keyAt(i);
2251 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002252 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2253 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002254 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002255 }
2256 }
2257 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002258 return uids;
2259 }
2260
2261 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002262 * Removes any persistable state associated with given {@link UserHandle}, persisting
2263 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002264 */
Felipe Lemef0823852016-06-08 13:43:08 -07002265 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002266
Felipe Lemef0823852016-06-08 13:43:08 -07002267 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07002268 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002269
Felipe Lemea110eec2016-04-29 09:58:06 -07002270 // Remove entries from revoked default restricted background UID whitelist
2271 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2272 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2273 if (UserHandle.getUserId(uid) == userId) {
2274 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002275 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002276 }
2277 }
2278
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002279 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002280 int[] uids = new int[0];
2281 for (int i = 0; i < mUidPolicy.size(); i++) {
2282 final int uid = mUidPolicy.keyAt(i);
2283 if (UserHandle.getUserId(uid) == userId) {
2284 uids = appendInt(uids, uid);
2285 }
2286 }
2287
2288 if (uids.length > 0) {
2289 for (int uid : uids) {
2290 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002291 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002292 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002293 }
Felipe Lemef0823852016-06-08 13:43:08 -07002294 synchronized (mNetworkPoliciesSecondLock) {
2295 updateRulesForGlobalChangeAL(true);
2296 if (writePolicy && changed) {
2297 writePolicyAL();
2298 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002299 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002300 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002301 }
2302
2303 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002304 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002305 // TODO: create permission for observing network policy
2306 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002307 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002308 }
2309
2310 @Override
2311 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002312 // TODO: create permission for observing network policy
2313 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002314 mListeners.unregister(listener);
2315 }
2316
Jeff Sharkey1b861272011-05-22 00:34:52 -07002317 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002318 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002319 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2320
Felipe Leme6a05eee2016-02-19 14:43:51 -08002321 final long token = Binder.clearCallingIdentity();
2322 try {
2323 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002324 synchronized (mUidRulesFirstLock) {
2325 synchronized (mNetworkPoliciesSecondLock) {
2326 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002327 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002328 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002329 }
2330 } finally {
2331 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002332 }
2333 }
2334
Hugo Benichi446c9c92017-04-10 09:41:10 +09002335 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002336 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002337 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2338 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002339 }
2340
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002341 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002342 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002343 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002344 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002345 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2346 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2347 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002348 } catch (SecurityException e) {
2349 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002350
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002351 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2352 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2353 return new NetworkPolicy[0];
2354 }
Svet Ganov16a16892015-04-16 10:32:04 -07002355 }
2356
Felipe Lemef0823852016-06-08 13:43:08 -07002357 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002358 final int size = mNetworkPolicy.size();
2359 final NetworkPolicy[] policies = new NetworkPolicy[size];
2360 for (int i = 0; i < size; i++) {
2361 policies[i] = mNetworkPolicy.valueAt(i);
2362 }
2363 return policies;
2364 }
2365 }
2366
Felipe Lemef0823852016-06-08 13:43:08 -07002367 private void normalizePoliciesNL() {
2368 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002369 }
2370
Felipe Lemef0823852016-06-08 13:43:08 -07002371 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002372 final TelephonyManager tele = TelephonyManager.from(mContext);
2373 final String[] merged = tele.getMergedSubscriberIds();
2374
2375 mNetworkPolicy.clear();
2376 for (NetworkPolicy policy : policies) {
2377 // When two normalized templates conflict, prefer the most
2378 // restrictive policy
2379 policy.template = NetworkTemplate.normalize(policy.template, merged);
2380 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2381 if (existing == null || existing.compareTo(policy) > 0) {
2382 if (existing != null) {
2383 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2384 }
2385 mNetworkPolicy.put(policy.template, policy);
2386 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002387 }
2388 }
2389
2390 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002391 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002392 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002393
2394 final long token = Binder.clearCallingIdentity();
2395 try {
2396 performSnooze(template, TYPE_LIMIT);
2397 } finally {
2398 Binder.restoreCallingIdentity(token);
2399 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002400 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002401
Dianne Hackborn497175b2014-07-01 12:56:08 -07002402 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002403 maybeRefreshTrustedTime();
2404 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002405 synchronized (mUidRulesFirstLock) {
2406 synchronized (mNetworkPoliciesSecondLock) {
2407 // find and snooze local policy that matches
2408 final NetworkPolicy policy = mNetworkPolicy.get(template);
2409 if (policy == null) {
2410 throw new IllegalArgumentException("unable to find policy for " + template);
2411 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002412
Felipe Lemef0823852016-06-08 13:43:08 -07002413 switch (type) {
2414 case TYPE_WARNING:
2415 policy.lastWarningSnooze = currentTime;
2416 break;
2417 case TYPE_LIMIT:
2418 policy.lastLimitSnooze = currentTime;
2419 break;
2420 default:
2421 throw new IllegalArgumentException("unexpected type");
2422 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002423
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002424 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002425 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002426 }
2427 }
2428
2429 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002430 public void onTetheringChanged(String iface, boolean tethering) {
2431 // No need to enforce permission because setRestrictBackground() will do it.
2432 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002433 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002434 if (mRestrictBackground && tethering) {
2435 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2436 setRestrictBackground(false);
2437 }
2438 }
2439 }
2440
2441 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002442 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002443 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002444 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002445 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2446 final long token = Binder.clearCallingIdentity();
2447 try {
2448 maybeRefreshTrustedTime();
2449 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002450 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002451 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002452 } finally {
2453 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002454 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002455 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002456 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002457 }
2458 }
2459
Felipe Lemef0823852016-06-08 13:43:08 -07002460 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002461 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002462 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002463 if (restrictBackground == mRestrictBackground) {
2464 // Ideally, UI should never allow this scenario...
2465 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002466 return;
2467 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002468 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2469 final boolean oldRestrictBackground = mRestrictBackground;
2470 mRestrictBackground = restrictBackground;
2471 // Must whitelist foreground apps before turning data saver mode on.
2472 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2473 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2474 updateRulesForRestrictBackgroundUL();
2475 try {
2476 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2477 Slog.e(TAG,
2478 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2479 mRestrictBackground = oldRestrictBackground;
2480 // TODO: if it knew the foreground apps (see TODO above), it could call
2481 // updateRulesForRestrictBackgroundUL() again to restore state.
2482 return;
2483 }
2484 } catch (RemoteException e) {
2485 // ignored; service lives in system_server
2486 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002487
Sudheer Shanka543339f2017-07-28 15:18:07 -07002488 sendRestrictBackgroundChangedMsg();
2489
2490 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2491 mRestrictBackgroundChangedInBsm = true;
2492 }
2493 synchronized (mNetworkPoliciesSecondLock) {
2494 updateNotificationsNL();
2495 writePolicyAL();
2496 }
2497 } finally {
2498 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002499 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002500 }
2501
2502 private void sendRestrictBackgroundChangedMsg() {
2503 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2504 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2505 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002506 }
2507
Felipe Lemeb85a6372016-01-14 16:16:16 -08002508 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002509 public int getRestrictBackgroundByCaller() {
2510 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2511 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002512
Felipe Lemef0823852016-06-08 13:43:08 -07002513 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002514 // Must clear identity because getUidPolicy() is restricted to system.
2515 final long token = Binder.clearCallingIdentity();
2516 final int policy;
2517 try {
2518 policy = getUidPolicy(uid);
2519 } finally {
2520 Binder.restoreCallingIdentity(token);
2521 }
2522 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2523 // App is blacklisted.
2524 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2525 }
Felipe Leme1b103232016-01-22 09:44:57 -08002526 if (!mRestrictBackground) {
2527 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2528 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002529 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002530 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2531 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2532 }
2533 }
2534
2535 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002536 public boolean getRestrictBackground() {
2537 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2538
Felipe Lemef0823852016-06-08 13:43:08 -07002539 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002540 return mRestrictBackground;
2541 }
2542 }
2543
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002544 @Override
2545 public void setDeviceIdleMode(boolean enabled) {
2546 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002547 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2548 try {
2549 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002550 if (mDeviceIdleMode == enabled) {
2551 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002552 }
Felipe Lemeea014392016-09-06 13:59:54 -07002553 mDeviceIdleMode = enabled;
2554 if (mSystemReady) {
2555 // Device idle change means we need to rebuild rules for all
2556 // known apps, so do a global refresh.
2557 updateRulesForRestrictPowerUL();
2558 }
2559 }
2560 if (enabled) {
2561 EventLogTags.writeDeviceIdleOnPhase("net");
2562 } else {
2563 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002564 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002565 } finally {
2566 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002567 }
2568 }
2569
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002570 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002571 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2572 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002573 final long token = Binder.clearCallingIdentity();
2574 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002575 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2576 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2577 for (WifiConfiguration config : configs) {
2578 if (Objects.equals(resolveNetworkId(config), networkId)) {
2579 config.meteredOverride = meteredOverride;
2580 wm.updateNetwork(config);
2581 }
2582 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002583 } finally {
2584 Binder.restoreCallingIdentity(token);
2585 }
2586 }
2587
Jeff Sharkey46645002011-07-27 21:11:21 -07002588 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002589 @Deprecated
2590 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2591 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2592 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2593 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002594 }
2595
Jeff Sharkey53313d72017-07-13 16:47:32 -06002596 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2597 // Verify they're not lying about package name
2598 mAppOps.checkPackage(callingUid, callingPackage);
2599
Jeff Sharkey53313d72017-07-13 16:47:32 -06002600 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002601 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002602 final long token = Binder.clearCallingIdentity();
2603 try {
2604 si = mContext.getSystemService(SubscriptionManager.class)
2605 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002606 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002607 } finally {
2608 Binder.restoreCallingIdentity(token);
2609 }
2610
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002611 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002612 if (si != null) {
2613 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2614 return;
2615 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002616 }
2617
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002618 // Second check: has the CarrierService delegated access?
2619 if (config != null) {
2620 final String overridePackage = config
2621 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2622 if (!TextUtils.isEmpty(overridePackage)
2623 && Objects.equals(overridePackage, callingPackage)) {
2624 return;
2625 }
2626 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002627
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002628 // Third check: is caller the fallback/default CarrierService?
2629 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2630 if (!TextUtils.isEmpty(defaultPackage)
2631 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002632 return;
2633 }
2634
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002635 // Final check: does the caller hold a permission?
2636 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002637 }
2638
2639 @Override
2640 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2641 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2642
Jeff Sharkey53313d72017-07-13 16:47:32 -06002643 final String fake = SystemProperties.get("fw.fake_plan");
2644 if (!TextUtils.isEmpty(fake)) {
2645 final List<SubscriptionPlan> plans = new ArrayList<>();
2646 if ("month_hard".equals(fake)) {
2647 plans.add(SubscriptionPlan.Builder
2648 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2649 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002650 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2651 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2652 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2653 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2654 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002655 plans.add(SubscriptionPlan.Builder
2656 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2657 .setTitle("G-Mobile Happy")
2658 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2659 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2660 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2661 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2662 .build());
2663 plans.add(SubscriptionPlan.Builder
2664 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2665 .setTitle("G-Mobile, Charged after limit")
2666 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2667 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2668 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2669 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2670 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002671 } else if ("month_soft".equals(fake)) {
2672 plans.add(SubscriptionPlan.Builder
2673 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2674 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2675 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2676 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002677 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2678 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2679 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2680 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2681 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002682 plans.add(SubscriptionPlan.Builder
2683 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2684 .setTitle("G-Mobile, Throttled after limit")
2685 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2686 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2687 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2688 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2689 .build());
2690 plans.add(SubscriptionPlan.Builder
2691 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2692 .setTitle("G-Mobile, No data connection after limit")
2693 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2694 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2695 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2696 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2697 .build());
2698
Jeff Sharkey53313d72017-07-13 16:47:32 -06002699 } else if ("month_none".equals(fake)) {
2700 plans.add(SubscriptionPlan.Builder
2701 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2702 .setTitle("G-Mobile")
2703 .build());
2704 } else if ("prepaid".equals(fake)) {
2705 plans.add(SubscriptionPlan.Builder
2706 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2707 ZonedDateTime.now().plusDays(10))
2708 .setTitle("G-Mobile")
2709 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2710 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2711 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2712 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2713 .build());
2714 } else if ("prepaid_crazy".equals(fake)) {
2715 plans.add(SubscriptionPlan.Builder
2716 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2717 ZonedDateTime.now().plusDays(10))
2718 .setTitle("G-Mobile Anytime")
2719 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2720 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2721 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2722 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2723 .build());
2724 plans.add(SubscriptionPlan.Builder
2725 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2726 ZonedDateTime.now().plusDays(20))
2727 .setTitle("G-Mobile Nickel Nights")
2728 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002729 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2730 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002731 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2732 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2733 .build());
2734 plans.add(SubscriptionPlan.Builder
2735 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2736 ZonedDateTime.now().plusDays(20))
2737 .setTitle("G-Mobile Bonus 3G")
2738 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002739 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002740 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2741 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2742 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2743 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002744 } else if ("unlimited".equals(fake)) {
2745 plans.add(SubscriptionPlan.Builder
2746 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2747 ZonedDateTime.now().plusDays(10))
2748 .setTitle("G-Mobile Awesome")
2749 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2750 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2751 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2752 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2753 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002754 }
2755 return plans.toArray(new SubscriptionPlan[plans.size()]);
2756 }
2757
Jeff Sharkey4635f102017-09-01 11:27:13 -06002758 synchronized (mNetworkPoliciesSecondLock) {
2759 // Only give out plan details to the package that defined them,
2760 // so that we don't risk leaking plans between apps. We always
2761 // let in core system components (like the Settings app).
2762 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2763 if (Objects.equals(ownerPackage, callingPackage)
2764 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2765 return mSubscriptionPlans.get(subId);
2766 } else {
2767 Log.w(TAG, "Not returning plans because caller " + callingPackage
2768 + " doesn't match owner " + ownerPackage);
2769 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002770 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002771 }
2772 }
2773
2774 @Override
2775 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2776 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2777
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002778 for (SubscriptionPlan plan : plans) {
2779 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002780 }
2781
2782 final long token = Binder.clearCallingIdentity();
2783 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002784 maybeRefreshTrustedTime();
2785 synchronized (mUidRulesFirstLock) {
2786 synchronized (mNetworkPoliciesSecondLock) {
2787 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002788 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002789
2790 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
2791 .getSubscriberId(subId);
2792 ensureActiveMobilePolicyAL(subId, subscriberId);
2793 maybeUpdateMobilePolicyCycleAL(subId);
2794 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002795 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002796 }
2797 } finally {
2798 Binder.restoreCallingIdentity(token);
2799 }
2800 }
2801
2802 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002803 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002804 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002805
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002806 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2807
Dianne Hackborn497175b2014-07-01 12:56:08 -07002808 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002809 for (String arg : args) {
2810 argSet.add(arg);
2811 }
2812
Felipe Lemef0823852016-06-08 13:43:08 -07002813 synchronized (mUidRulesFirstLock) {
2814 synchronized (mNetworkPoliciesSecondLock) {
2815 if (argSet.contains("--unsnooze")) {
2816 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2817 mNetworkPolicy.valueAt(i).clearSnooze();
2818 }
2819
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002820 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002821
2822 fout.println("Cleared snooze timestamps");
2823 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002824 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002825
Felipe Lemef0823852016-06-08 13:43:08 -07002826 fout.print("System ready: "); fout.println(mSystemReady);
2827 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2828 fout.print("Restrict power: "); fout.println(mRestrictPower);
2829 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002830 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2831
2832 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07002833 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002834 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002835 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2836 fout.println(mNetworkPolicy.valueAt(i).toString());
2837 }
2838 fout.decreaseIndent();
2839
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002840 fout.println();
2841 fout.println("Subscription plans:");
2842 fout.increaseIndent();
2843 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2844 final int subId = mSubscriptionPlans.keyAt(i);
2845 fout.println("Subscriber ID " + subId + ":");
2846 fout.increaseIndent();
2847 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2848 if (!ArrayUtils.isEmpty(plans)) {
2849 for (SubscriptionPlan plan : plans) {
2850 fout.println(plan);
2851 }
2852 }
2853 fout.decreaseIndent();
2854 }
2855 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002856
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002857 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07002858 fout.println("Policy for UIDs:");
2859 fout.increaseIndent();
2860 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002861 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002862 final int uid = mUidPolicy.keyAt(i);
2863 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002864 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002865 fout.print(uid);
2866 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002867 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002868 fout.println();
2869 }
2870 fout.decreaseIndent();
2871
2872 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2873 if (size > 0) {
2874 fout.println("Power save whitelist (except idle) app ids:");
2875 fout.increaseIndent();
2876 for (int i = 0; i < size; i++) {
2877 fout.print("UID=");
2878 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2879 fout.print(": ");
2880 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2881 fout.println();
2882 }
2883 fout.decreaseIndent();
2884 }
2885
2886 size = mPowerSaveWhitelistAppIds.size();
2887 if (size > 0) {
2888 fout.println("Power save whitelist app ids:");
2889 fout.increaseIndent();
2890 for (int i = 0; i < size; i++) {
2891 fout.print("UID=");
2892 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2893 fout.print(": ");
2894 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2895 fout.println();
2896 }
2897 fout.decreaseIndent();
2898 }
2899
Felipe Lemef0823852016-06-08 13:43:08 -07002900 size = mDefaultRestrictBackgroundWhitelistUids.size();
2901 if (size > 0) {
2902 fout.println("Default restrict background whitelist uids:");
2903 fout.increaseIndent();
2904 for (int i = 0; i < size; i++) {
2905 fout.print("UID=");
2906 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2907 fout.println();
2908 }
2909 fout.decreaseIndent();
2910 }
2911
2912 size = mRestrictBackgroundWhitelistRevokedUids.size();
2913 if (size > 0) {
2914 fout.println("Default restrict background whitelist uids revoked by users:");
2915 fout.increaseIndent();
2916 for (int i = 0; i < size; i++) {
2917 fout.print("UID=");
2918 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2919 fout.println();
2920 }
2921 fout.decreaseIndent();
2922 }
2923
2924 final SparseBooleanArray knownUids = new SparseBooleanArray();
2925 collectKeys(mUidState, knownUids);
2926 collectKeys(mUidRules, knownUids);
2927
2928 fout.println("Status for all known UIDs:");
2929 fout.increaseIndent();
2930 size = knownUids.size();
2931 for (int i = 0; i < size; i++) {
2932 final int uid = knownUids.keyAt(i);
2933 fout.print("UID=");
2934 fout.print(uid);
2935
2936 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2937 fout.print(" state=");
2938 fout.print(state);
2939 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2940 fout.print(" (fg)");
2941 } else {
2942 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2943 ? " (fg svc)" : " (bg)");
2944 }
2945
2946 final int uidRules = mUidRules.get(uid, RULE_NONE);
2947 fout.print(" rules=");
2948 fout.print(uidRulesToString(uidRules));
2949 fout.println();
2950 }
2951 fout.decreaseIndent();
2952
2953 fout.println("Status for just UIDs with rules:");
2954 fout.increaseIndent();
2955 size = mUidRules.size();
2956 for (int i = 0; i < size; i++) {
2957 final int uid = mUidRules.keyAt(i);
2958 fout.print("UID=");
2959 fout.print(uid);
2960 final int uidRules = mUidRules.get(uid, RULE_NONE);
2961 fout.print(" rules=");
2962 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002963 fout.println();
2964 }
2965 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08002966
2967 fout.println("Observed uid state changes:");
2968 fout.increaseIndent();
2969 mObservedHistory.dumpUL(fout);
2970 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002971 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002972 }
2973 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002974
2975 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002976 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002977 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002978 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002979 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002980 }
2981
2982 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002983 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002984 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2985
Felipe Lemef0823852016-06-08 13:43:08 -07002986 synchronized (mUidRulesFirstLock) {
2987 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002988 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002989 }
2990
Felipe Lemef0823852016-06-08 13:43:08 -07002991 private boolean isUidForegroundUL(int uid) {
2992 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002993 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2994 }
2995
Felipe Lemef0823852016-06-08 13:43:08 -07002996 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002997 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002998 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002999 }
3000
Felipe Lemef0823852016-06-08 13:43:08 -07003001 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003002 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3003 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3004 }
3005
Felipe Lemef0823852016-06-08 13:43:08 -07003006 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003007 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07003008 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003009 }
3010
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003011 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003012 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003013 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3014 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003015 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003016 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003017 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3018 try {
3019 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3020 if (oldUidState != uidState) {
3021 // state changed, push updated rules
3022 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003023 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3024 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3025 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003026 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003027 if (mDeviceIdleMode) {
3028 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003029 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003030 if (mRestrictPower) {
3031 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003032 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003033 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003034 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003035 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003036 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003037 } finally {
3038 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003039 }
3040 }
3041
Felipe Lemef0823852016-06-08 13:43:08 -07003042 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003043 final int index = mUidState.indexOfKey(uid);
3044 if (index >= 0) {
3045 final int oldUidState = mUidState.valueAt(index);
3046 mUidState.removeAt(index);
3047 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003048 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003049 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003050 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003051 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003052 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003053 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003054 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003055 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003056 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003057 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003058 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003059 }
3060 }
3061
Felipe Lemef28983d2016-03-25 12:18:23 -07003062 // adjust stats accounting based on foreground status
3063 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003064 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3065 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3066 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3067 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003068 try {
3069 mNetworkStats.setUidForeground(uid, uidForeground);
3070 } catch (RemoteException e) {
3071 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003072 } finally {
3073 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003074 }
3075 }
3076
Sudheer Shankac9d94072017-02-22 22:13:55 +00003077 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3078 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003079 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003080 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003081 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003082 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003083 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003084 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003085 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003086 }
3087
Felipe Lemef0823852016-06-08 13:43:08 -07003088 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003089 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3090 try {
3091 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3092 mUidFirewallPowerSaveRules);
3093 } finally {
3094 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3095 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003096 }
3097
Felipe Lemef0823852016-06-08 13:43:08 -07003098 void updateRuleForRestrictPowerUL(int uid) {
3099 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003100 }
3101
Felipe Lemef0823852016-06-08 13:43:08 -07003102 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003103 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3104 try {
3105 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3106 mUidFirewallDozableRules);
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 updateRuleForDeviceIdleUL(int uid) {
3113 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003114 }
3115
Felipe Lemef28983d2016-03-25 12:18:23 -07003116 // NOTE: since both fw_dozable and fw_powersave uses the same map
3117 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003118 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003119 SparseIntArray rules) {
3120 if (enabled) {
3121 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003122 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003123 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003124 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003125 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003126 for (int ui = users.size() - 1; ui >= 0; ui--) {
3127 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003128 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3129 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3130 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3131 updateRulesForWhitelistedAppIds(uidRules,
3132 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003133 }
3134 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003135 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003136 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003137 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3138 }
3139 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003140 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003141 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003142 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003143 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003144 }
3145
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003146 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3147 final SparseBooleanArray whitelistedAppIds, int userId) {
3148 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3149 if (whitelistedAppIds.valueAt(i)) {
3150 final int appId = whitelistedAppIds.keyAt(i);
3151 final int uid = UserHandle.getUid(userId, appId);
3152 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3153 }
3154 }
3155 }
3156
3157 /**
3158 * @param deviceIdleMode if true then we don't consider
3159 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3160 * whitelisted.
3161 */
3162 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003163 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003164 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3165 || mPowerSaveWhitelistAppIds.get(appId);
3166 if (!deviceIdleMode) {
3167 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3168 }
3169 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003170 }
3171
Felipe Lemef28983d2016-03-25 12:18:23 -07003172 // NOTE: since both fw_dozable and fw_powersave uses the same map
3173 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003174 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003175 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003176 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3177 chain == FIREWALL_CHAIN_DOZABLE);
3178 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003179 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003180 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003181 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003182 }
3183 }
3184 }
3185
Felipe Lemef0823852016-06-08 13:43:08 -07003186 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003187 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3188 try {
3189 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3190 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003191
Felipe Leme873a83a2016-09-07 11:34:10 -07003192 // Fully update the app idle firewall chain.
3193 final List<UserInfo> users = mUserManager.getUsers();
3194 for (int ui = users.size() - 1; ui >= 0; ui--) {
3195 UserInfo user = users.get(ui);
3196 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3197 for (int uid : idleUids) {
3198 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3199 // quick check: if this uid doesn't have INTERNET permission, it
3200 // doesn't have network access anyway, so it is a waste to mess
3201 // with it here.
3202 if (hasInternetPermissions(uid)) {
3203 uidRules.put(uid, FIREWALL_RULE_DENY);
3204 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003205 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003206 }
3207 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003208
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003209 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003210 } finally {
3211 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3212 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003213 }
3214
Felipe Lemef0823852016-06-08 13:43:08 -07003215 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003216 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003217
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003218 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3219 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3220 }
3221 try {
3222 int appId = UserHandle.getAppId(uid);
3223 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3224 && !isUidForegroundOnRestrictPowerUL(uid)) {
3225 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3226 } else {
3227 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3228 }
3229 } finally {
3230 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003231 }
3232 }
3233
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003234 /**
3235 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3236 * changed.
3237 */
Felipe Lemef0823852016-06-08 13:43:08 -07003238 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003239 boolean paroled = mUsageStats.isAppIdleParoleOn();
3240 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003241 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003242
3243 int ruleCount = mUidFirewallStandbyRules.size();
3244 for (int i = 0; i < ruleCount; i++) {
3245 int uid = mUidFirewallStandbyRules.keyAt(i);
3246 int oldRules = mUidRules.get(uid);
3247 if (enableChain) {
3248 // Chain wasn't enabled before and the other power-related
3249 // chains are whitelists, so we can clear the
3250 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3251 // the effective rules result in blocking network access.
3252 oldRules &= MASK_METERED_NETWORKS;
3253 } else {
3254 // Skip if it had no restrictions to begin with
3255 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3256 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003257 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3258 if (newUidRules == RULE_NONE) {
3259 mUidRules.delete(uid);
3260 } else {
3261 mUidRules.put(uid, newUidRules);
3262 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003263 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003264 }
3265
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003266 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003267 * Update rules that might be changed by {@link #mRestrictBackground},
3268 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003269 */
Felipe Lemef0823852016-06-08 13:43:08 -07003270 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003271 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3272 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3273 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3274 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003275 try {
Felipe Leme09700462016-09-08 09:33:48 -07003276 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003277 updateRulesForRestrictPowerUL();
3278 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003279
Felipe Leme873a83a2016-09-07 11:34:10 -07003280 // If the set of restricted networks may have changed, re-evaluate those.
3281 if (restrictedNetworksChanged) {
3282 normalizePoliciesNL();
3283 updateNetworkRulesNL();
3284 }
3285 } finally {
3286 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003287 }
3288 }
3289
Felipe Leme09700462016-09-08 09:33:48 -07003290 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003291 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003292 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3293 try {
3294 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003295 updateRulesForPowerSaveUL();
3296 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3297 } finally {
3298 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3299 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003300 }
3301
Felipe Lemef0823852016-06-08 13:43:08 -07003302 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003303 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3304 try {
3305 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3306 } finally {
3307 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3308 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003309 }
3310
3311 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3312 private static final int TYPE_RESTRICT_POWER = 2;
3313 @Retention(RetentionPolicy.SOURCE)
3314 @IntDef(flag = false, value = {
3315 TYPE_RESTRICT_BACKGROUND,
3316 TYPE_RESTRICT_POWER,
3317 })
3318 public @interface RestrictType {
3319 }
3320
3321 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003322 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003323 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3324 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3325 }
3326 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003327 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003328
3329 final PackageManager pm = mContext.getPackageManager();
3330 final List<UserInfo> users;
3331 final List<ApplicationInfo> apps;
3332
3333 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3334 try {
3335 users = mUserManager.getUsers();
3336 } finally {
3337 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3338 }
3339 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3340 try {
3341 apps = pm.getInstalledApplications(
3342 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3343 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3344 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3345 } finally {
3346 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3347 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003348
Felipe Leme873a83a2016-09-07 11:34:10 -07003349 final int usersSize = users.size();
3350 final int appsSize = apps.size();
3351 for (int i = 0; i < usersSize; i++) {
3352 final UserInfo user = users.get(i);
3353 for (int j = 0; j < appsSize; j++) {
3354 final ApplicationInfo app = apps.get(j);
3355 final int uid = UserHandle.getUid(user.id, app.uid);
3356 switch (type) {
3357 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003358 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003359 break;
3360 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003361 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003362 break;
3363 default:
3364 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3365 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003366 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003367 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003368 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003369 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003370 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003371 }
3372
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003373 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003374 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003375 final int numUsers = users.size();
3376 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003377 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003378 int uid = UserHandle.getUid(user.id, appId);
3379 // Update external firewall rules.
3380 updateRuleForAppIdleUL(uid);
3381 updateRuleForDeviceIdleUL(uid);
3382 updateRuleForRestrictPowerUL(uid);
3383 // Update internal rules.
3384 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003385 }
3386 }
3387
Felipe Leme70c57c22016-03-29 10:45:13 -07003388 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3389 // methods below could be merged into a isUidValidForRules() method.
3390 private boolean isUidValidForBlacklistRules(int uid) {
3391 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003392 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003393 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003394 return true;
3395 }
3396
3397 return false;
3398 }
3399
Felipe Leme70c57c22016-03-29 10:45:13 -07003400 private boolean isUidValidForWhitelistRules(int uid) {
3401 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3402 }
3403
Amith Yamasani15e472352015-04-24 19:06:07 -07003404 private boolean isUidIdle(int uid) {
3405 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3406 final int userId = UserHandle.getUserId(uid);
3407
songjinshi0655edd2016-05-18 19:55:32 +08003408 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003409 for (String packageName : packages) {
3410 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3411 return false;
3412 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003413 }
3414 }
3415 return true;
3416 }
3417
3418 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003419 * Checks if an uid has INTERNET permissions.
3420 * <p>
3421 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003422 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003423 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003424 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003425 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003426 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003427 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003428 }
3429 } catch (RemoteException e) {
3430 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003431 return true;
3432 }
3433
3434 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003435 * Clears all state - internal and external - associated with an UID.
3436 */
3437 private void onUidDeletedUL(int uid) {
3438 // First cleanup in-memory state synchronously...
3439 mUidRules.delete(uid);
3440 mUidPolicy.delete(uid);
3441 mUidFirewallStandbyRules.delete(uid);
3442 mUidFirewallDozableRules.delete(uid);
3443 mUidFirewallPowerSaveRules.delete(uid);
3444 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3445 mPowerSaveWhitelistAppIds.delete(uid);
3446 mPowerSaveTempWhitelistAppIds.delete(uid);
3447
3448 // ...then update iptables asynchronously.
3449 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3450 }
3451
3452 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003453 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003454 *
Felipe Leme781ba142016-05-09 16:24:48 -07003455 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003456 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003457 * <li>Doze mode
3458 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003459 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003460 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003461 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003462 *
3463 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003464 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003465 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003466 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003467 updateRuleForDeviceIdleUL(uid);
3468 updateRuleForAppIdleUL(uid);
3469 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003470
3471 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003472 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003473
3474 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003475 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003476 }
3477
Felipe Leme70c57c22016-03-29 10:45:13 -07003478 /**
3479 * Applies network rules to bandwidth controllers based on process state and user-defined
3480 * restrictions (blacklist / whitelist).
3481 *
3482 * <p>
3483 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3484 * networks:
3485 * <ul>
3486 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3487 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3488 * also blacklisted.
3489 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3490 * no UIDs other those whitelisted will have access.
3491 * <ul>
3492 *
3493 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3494 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3495 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3496 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003497 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003498 * {@link INetworkManagementService}, but this method should also be called in events (like
3499 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3500 * following rules should also be applied:
3501 *
3502 * <ul>
3503 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3504 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3505 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3506 * {@code bw_penalty_box}.
3507 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3508 * </ul>
3509 *
3510 * <p>For optimization, the rules are only applied on user apps that have internet access
3511 * permission, since there is no need to change the {@code iptables} rule if the app does not
3512 * have permission to use the internet.
3513 *
3514 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003515 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003516 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003517 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003518 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3519 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3520 "updateRulesForDataUsageRestrictionsUL: " + uid);
3521 }
3522 try {
3523 updateRulesForDataUsageRestrictionsULInner(uid);
3524 } finally {
3525 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3526 }
3527 }
3528
3529 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003530 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003531 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003532 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003533 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003534
Dianne Hackborn497175b2014-07-01 12:56:08 -07003535 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003536 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003537 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003538
Felipe Leme781ba142016-05-09 16:24:48 -07003539 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003540 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003541 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3542 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003543
Felipe Leme70c57c22016-03-29 10:45:13 -07003544 // First step: define the new rule based on user restrictions and foreground state.
3545 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003546 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3547 newRule = RULE_TEMPORARY_ALLOW_METERED;
3548 } else if (isWhitelisted) {
3549 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003550 }
3551 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003552 if (isBlacklisted) {
3553 newRule = RULE_REJECT_METERED;
3554 } else if (mRestrictBackground && isWhitelisted) {
3555 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003556 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003557 }
Felipe Leme781ba142016-05-09 16:24:48 -07003558 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003559
Felipe Lemef28983d2016-03-25 12:18:23 -07003560 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003561 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003562 + ": isForeground=" +isForeground
3563 + ", isBlacklisted=" + isBlacklisted
3564 + ", isWhitelisted=" + isWhitelisted
3565 + ", oldRule=" + uidRulesToString(oldRule)
3566 + ", newRule=" + uidRulesToString(newRule)
3567 + ", newUidRules=" + uidRulesToString(newUidRules)
3568 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003569 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003570
Felipe Leme46c4fc32016-05-04 09:21:43 -07003571 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003572 mUidRules.delete(uid);
3573 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003574 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003575 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003576
Felipe Leme70c57c22016-03-29 10:45:13 -07003577 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003578 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003579 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003580 // Temporarily whitelist foreground app, removing from blacklist if necessary
3581 // (since bw_penalty_box prevails over bw_happy_box).
3582
3583 setMeteredNetworkWhitelist(uid, true);
3584 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3585 // but ideally it should be just:
3586 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003587 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003588 setMeteredNetworkBlacklist(uid, false);
3589 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003590 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003591 // Remove temporary whitelist from app that is not on foreground anymore.
3592
3593 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3594 // but ideally they should be just:
3595 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3596 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003597 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003598 setMeteredNetworkWhitelist(uid, false);
3599 }
Felipe Leme781ba142016-05-09 16:24:48 -07003600 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003601 setMeteredNetworkBlacklist(uid, true);
3602 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003603 } else if (hasRule(newRule, RULE_REJECT_METERED)
3604 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003605 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003606 setMeteredNetworkBlacklist(uid, isBlacklisted);
Hugo Benichi2966c182017-03-28 17:17:13 +09003607 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003608 // Since blacklist prevails over whitelist, we need to handle the special case
3609 // where app is whitelisted and blacklisted at the same time (although such
3610 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003611 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003612 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003613 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3614 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003615 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003616 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003617 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003618 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003619 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3620 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003621 + ", whitelisted=" + isWhitelisted
3622 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003623 + ", newRule=" + uidRulesToString(newUidRules)
3624 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003625 }
Felipe Leme781ba142016-05-09 16:24:48 -07003626
Sudheer Shankac9d94072017-02-22 22:13:55 +00003627 // Dispatch changed rule to existing listeners.
3628 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003629 }
3630 }
3631
3632 /**
3633 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3634 * listeners in case of change.
3635 * <p>
3636 * There are 3 power-related rules that affects whether an app has background access on
3637 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3638 * restriction, it's added to the equivalent firewall chain:
3639 * <ul>
3640 * <li>App is idle: {@code fw_standby} firewall chain.
3641 * <li>Device is idle: {@code fw_dozable} firewall chain.
3642 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3643 * </ul>
3644 * <p>
3645 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3646 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3647 * <p>
3648 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3649 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003650 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003651 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3652
Sudheer Shankac9d94072017-02-22 22:13:55 +00003653 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003654
Sudheer Shankac9d94072017-02-22 22:13:55 +00003655 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003656 mUidRules.delete(uid);
3657 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003658 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003659 }
3660 }
3661
3662 /**
3663 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3664 *
3665 * @param uid the uid of the app to update rules for
3666 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3667 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3668 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003669 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003670 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003671 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003672 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3673 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3674 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3675 + (paroled ? "P" : "-"));
3676 }
3677 try {
3678 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3679 } finally {
3680 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3681 }
3682 }
3683
3684 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003685 if (!isUidValidForBlacklistRules(uid)) {
3686 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003687 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003688 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003689
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003690 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003691 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003692 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003693
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003694 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003695 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3696 int newRule = RULE_NONE;
3697
3698 // First step: define the new rule based on user restrictions and foreground state.
3699
3700 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3701 // by considering the foreground and non-foreground states.
3702 if (isForeground) {
3703 if (restrictMode) {
3704 newRule = RULE_ALLOW_ALL;
3705 }
3706 } else if (restrictMode) {
3707 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3708 }
3709
3710 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3711
3712 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003713 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003714 + ", isIdle: " + isIdle
3715 + ", mRestrictPower: " + mRestrictPower
3716 + ", mDeviceIdleMode: " + mDeviceIdleMode
3717 + ", isForeground=" + isForeground
3718 + ", isWhitelisted=" + isWhitelisted
3719 + ", oldRule=" + uidRulesToString(oldRule)
3720 + ", newRule=" + uidRulesToString(newRule)
3721 + ", newUidRules=" + uidRulesToString(newUidRules)
3722 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3723 }
3724
Felipe Leme781ba142016-05-09 16:24:48 -07003725 // Second step: notify listeners if state changed.
3726 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003727 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003728 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003729 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003730 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3731 } else {
3732 // All scenarios should have been covered above
3733 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3734 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003735 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003736 + ", newRule=" + uidRulesToString(newUidRules)
3737 + ", oldRule=" + uidRulesToString(oldUidRules));
3738 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003739 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003740 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003741
Sudheer Shankac9d94072017-02-22 22:13:55 +00003742 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003743 }
3744
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003745 private class AppIdleStateChangeListener
3746 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3747
3748 @Override
3749 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3750 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003751 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3752 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003753 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003754 synchronized (mUidRulesFirstLock) {
3755 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003756 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003757 }
3758 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003759 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003760 }
3761
3762 @Override
3763 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003764 synchronized (mUidRulesFirstLock) {
3765 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003766 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003767 }
3768 }
3769
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003770 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3771 if (listener != null) {
3772 try {
3773 listener.onUidRulesChanged(uid, uidRules);
3774 } catch (RemoteException ignored) {
3775 }
3776 }
3777 }
3778
3779 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3780 String[] meteredIfaces) {
3781 if (listener != null) {
3782 try {
3783 listener.onMeteredIfacesChanged(meteredIfaces);
3784 } catch (RemoteException ignored) {
3785 }
3786 }
3787 }
3788
3789 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3790 boolean restrictBackground) {
3791 if (listener != null) {
3792 try {
3793 listener.onRestrictBackgroundChanged(restrictBackground);
3794 } catch (RemoteException ignored) {
3795 }
3796 }
3797 }
3798
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003799 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3800 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003801 if (listener != null) {
3802 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003803 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003804 } catch (RemoteException ignored) {
3805 }
3806 }
3807 }
3808
Makoto Onuki8e777332017-03-28 11:25:47 -07003809 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003810 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003811 public boolean handleMessage(Message msg) {
3812 switch (msg.what) {
3813 case MSG_RULES_CHANGED: {
3814 final int uid = msg.arg1;
3815 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003816 final int length = mListeners.beginBroadcast();
3817 for (int i = 0; i < length; i++) {
3818 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3819 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003820 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003821 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003822 return true;
3823 }
3824 case MSG_METERED_IFACES_CHANGED: {
3825 final String[] meteredIfaces = (String[]) msg.obj;
3826 final int length = mListeners.beginBroadcast();
3827 for (int i = 0; i < length; i++) {
3828 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003829 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003830 }
3831 mListeners.finishBroadcast();
3832 return true;
3833 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003834 case MSG_LIMIT_REACHED: {
3835 final String iface = (String) msg.obj;
3836
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003837 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003838 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003839 if (mMeteredIfaces.contains(iface)) {
3840 try {
3841 // force stats update to make sure we have
3842 // numbers that caused alert to trigger.
3843 mNetworkStats.forceUpdate();
3844 } catch (RemoteException e) {
3845 // ignored; service lives in system_server
3846 }
3847
Felipe Lemef0823852016-06-08 13:43:08 -07003848 updateNetworkEnabledNL();
3849 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003850 }
3851 }
3852 return true;
3853 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003854 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3855 final boolean restrictBackground = msg.arg1 != 0;
3856 final int length = mListeners.beginBroadcast();
3857 for (int i = 0; i < length; i++) {
3858 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003859 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003860 }
3861 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003862 final Intent intent =
3863 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3864 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3865 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3866 return true;
3867 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003868 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003869 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003870 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003871 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003872 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07003873 final int length = mListeners.beginBroadcast();
3874 for (int i = 0; i < length; i++) {
3875 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003876 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003877 }
3878 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003879 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3880 if (notifyApp.booleanValue()) {
3881 broadcastRestrictBackgroundChanged(uid, notifyApp);
3882 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003883 return true;
3884 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003885 case MSG_ADVISE_PERSIST_THRESHOLD: {
3886 final long lowestRule = (Long) msg.obj;
3887 try {
3888 // make sure stats are recorded frequently enough; we aim
3889 // for 2MB threshold for 2GB/month rules.
3890 final long persistThreshold = lowestRule / 1000;
3891 mNetworkStats.advisePersistThreshold(persistThreshold);
3892 } catch (RemoteException e) {
3893 // ignored; service lives in system_server
3894 }
3895 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003896 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003897 case MSG_UPDATE_INTERFACE_QUOTA: {
3898 removeInterfaceQuota((String) msg.obj);
3899 // int params need to be stitched back into a long
3900 setInterfaceQuota((String) msg.obj,
3901 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3902 return true;
3903 }
3904 case MSG_REMOVE_INTERFACE_QUOTA: {
3905 removeInterfaceQuota((String) msg.obj);
3906 return true;
3907 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003908 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3909 resetUidFirewallRules(msg.arg1);
3910 return true;
3911 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003912 default: {
3913 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003914 }
3915 }
3916 }
Makoto Onuki8e777332017-03-28 11:25:47 -07003917 };
3918
3919 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
3920 @Override
3921 public boolean handleMessage(Message msg) {
3922 switch (msg.what) {
3923 case UID_MSG_STATE_CHANGED: {
3924 final int uid = msg.arg1;
3925 final int procState = msg.arg2;
3926 final long procStateSeq = (Long) msg.obj;
3927
3928 handleUidChanged(uid, procState, procStateSeq);
3929 return true;
3930 }
3931 case UID_MSG_GONE: {
3932 final int uid = msg.arg1;
3933 handleUidGone(uid);
3934 return true;
3935 }
3936 default: {
3937 return false;
3938 }
3939 }
3940 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003941
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003942 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003943
Makoto Onuki8e777332017-03-28 11:25:47 -07003944 void handleUidChanged(int uid, int procState, long procStateSeq) {
3945 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
3946 try {
3947 synchronized (mUidRulesFirstLock) {
3948 // We received a uid state change callback, add it to the history so that it
3949 // will be useful for debugging.
3950 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
3951 // Now update the network policy rules as per the updated uid state.
3952 updateUidStateUL(uid, procState);
3953 // Updating the network rules is done, so notify AMS about this.
3954 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
3955 }
3956 } finally {
3957 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3958 }
3959 }
3960
3961 void handleUidGone(int uid) {
3962 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
3963 try {
3964 synchronized (mUidRulesFirstLock) {
3965 removeUidStateUL(uid);
3966 }
3967 } finally {
3968 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3969 }
3970 }
3971
Felipe Leme57e3d312016-08-23 14:42:52 -07003972 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3973 final PackageManager pm = mContext.getPackageManager();
3974 final String[] packages = pm.getPackagesForUid(uid);
3975 if (packages != null) {
3976 final int userId = UserHandle.getUserId(uid);
3977 for (String packageName : packages) {
3978 final Intent intent =
3979 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3980 intent.setPackage(packageName);
3981 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3982 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3983 }
3984 }
3985 }
3986
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06003987 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
3988 // long quotaBytes split up into two ints to fit in message
3989 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
3990 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
3991 }
3992
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003993 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003994 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003995 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003996 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003997 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003998 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003999 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004000 }
4001 }
4002
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004003 private void removeInterfaceQuotaAsync(String iface) {
4004 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4005 }
4006
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004007 private void removeInterfaceQuota(String iface) {
4008 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004009 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004010 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004011 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004012 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004013 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004014 }
4015 }
4016
Felipe Leme70c57c22016-03-29 10:45:13 -07004017 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4018 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004019 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004020 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004021 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004022 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4023 } catch (RemoteException e) {
4024 // ignored; service lives in system_server
4025 }
4026 }
4027
4028 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4029 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4030 try {
4031 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4032 } catch (IllegalStateException e) {
4033 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004034 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004035 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004036 }
4037 }
4038
Felipe Lemebc853dd2016-09-08 13:26:55 -07004039 private static final int CHAIN_TOGGLE_NONE = 0;
4040 private static final int CHAIN_TOGGLE_ENABLE = 1;
4041 private static final int CHAIN_TOGGLE_DISABLE = 2;
4042 @Retention(RetentionPolicy.SOURCE)
4043 @IntDef(flag = false, value = {
4044 CHAIN_TOGGLE_NONE,
4045 CHAIN_TOGGLE_ENABLE,
4046 CHAIN_TOGGLE_DISABLE
4047 })
4048 public @interface ChainToggleType {
4049 }
4050
4051 /**
4052 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004053 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004054 *
4055 * @param chain firewall chain.
4056 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4057 * @param toggle whether the chain should be enabled, disabled, or not changed.
4058 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004059 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004060 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004061 if (uidRules != null) {
4062 setUidFirewallRulesUL(chain, uidRules);
4063 }
4064 if (toggle != CHAIN_TOGGLE_NONE) {
4065 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4066 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004067 }
4068
Amith Yamasani15e472352015-04-24 19:06:07 -07004069 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004070 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4071 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4072 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004073 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004074 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004075 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004076 int size = uidRules.size();
4077 int[] uids = new int[size];
4078 int[] rules = new int[size];
4079 for(int index = size - 1; index >= 0; --index) {
4080 uids[index] = uidRules.keyAt(index);
4081 rules[index] = uidRules.valueAt(index);
4082 }
4083 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004084 } catch (IllegalStateException e) {
4085 Log.wtf(TAG, "problem setting firewall uid rules", e);
4086 } catch (RemoteException e) {
4087 // ignored; service lives in system_server
4088 }
4089 }
4090
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004091 /**
4092 * Add or remove a uid to the firewall blacklist for all network ifaces.
4093 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004094 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004095 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4096 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4097 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004098 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004099 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004100 if (chain == FIREWALL_CHAIN_DOZABLE) {
4101 mUidFirewallDozableRules.put(uid, rule);
4102 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4103 mUidFirewallStandbyRules.put(uid, rule);
4104 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4105 mUidFirewallPowerSaveRules.put(uid, rule);
4106 }
4107
4108 try {
4109 mNetworkManager.setFirewallUidRule(chain, uid, rule);
4110 } catch (IllegalStateException e) {
4111 Log.wtf(TAG, "problem setting firewall uid rules", e);
4112 } catch (RemoteException e) {
4113 // ignored; service lives in system_server
4114 }
4115 } finally {
4116 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004117 }
4118 }
4119
4120 /**
4121 * Add or remove a uid to the firewall blacklist for all network ifaces.
4122 */
Felipe Lemef0823852016-06-08 13:43:08 -07004123 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004124 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4125 mFirewallChainStates.get(chain) == enable) {
4126 // All is the same, nothing to do.
4127 return;
4128 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004129 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004130 try {
4131 mNetworkManager.setFirewallChainEnabled(chain, enable);
4132 } catch (IllegalStateException e) {
4133 Log.wtf(TAG, "problem enable firewall chain", e);
4134 } catch (RemoteException e) {
4135 // ignored; service lives in system_server
4136 }
4137 }
4138
Felipe Leme03e95e22016-09-09 09:25:31 -07004139 /**
4140 * Resets all firewall rules associated with an UID.
4141 */
4142 private void resetUidFirewallRules(int uid) {
4143 try {
4144 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4145 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4146 mNetworkManager
4147 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4148 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4149 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4150 } catch (IllegalStateException e) {
4151 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4152 } catch (RemoteException e) {
4153 // ignored; service lives in system_server
4154 }
4155 }
4156
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004157 private long getTotalBytes(NetworkTemplate template, long start, long end) {
4158 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004159 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004160 } catch (RuntimeException e) {
4161 Slog.w(TAG, "problem reading network stats: " + e);
4162 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004163 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004164 // ignored; service lives in system_server
4165 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004166 }
4167 }
4168
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004169 private boolean isBandwidthControlEnabled() {
4170 final long token = Binder.clearCallingIdentity();
4171 try {
4172 return mNetworkManager.isBandwidthControlEnabled();
4173 } catch (RemoteException e) {
4174 // ignored; service lives in system_server
4175 return false;
4176 } finally {
4177 Binder.restoreCallingIdentity(token);
4178 }
4179 }
4180
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004181 /**
4182 * Try refreshing {@link #mTime} when stale.
4183 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07004184 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004185 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004186 mTime.forceRefresh();
4187 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004188 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004189
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004190 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004191 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
4192 }
4193
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004194 private static Intent buildAllowBackgroundDataIntent() {
4195 return new Intent(ACTION_ALLOW_BACKGROUND);
4196 }
4197
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004198 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4199 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
4200 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4201 return intent;
4202 }
4203
Wei Liu546cb772016-07-21 16:19:01 -07004204 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004205 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004206 intent.setComponent(ComponentName.unflattenFromString(
4207 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004208 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4209 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4210 return intent;
4211 }
4212
Wei Liu546cb772016-07-21 16:19:01 -07004213 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004214 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004215 intent.setComponent(ComponentName.unflattenFromString(
4216 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004217 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4218 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4219 return intent;
4220 }
4221
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004222 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004223 public void addIdleHandler(IdleHandler handler) {
4224 mHandler.getLooper().getQueue().addIdleHandler(handler);
4225 }
4226
jackqdyulei29c82ab2017-03-10 14:09:16 -08004227 @VisibleForTesting
4228 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4229 mRestrictBackgroundPowerState = result;
4230
4231 boolean restrictBackground = result.batterySaverEnabled;
4232 boolean shouldInvokeRestrictBackground;
4233 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4234 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4235
4236 if (result.globalBatterySaverEnabled) {
4237 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4238 // turn it on.
4239 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4240 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4241 localRestrictBgChangedInBsm = false;
4242 } else {
4243 // Try to restore the restrictBackground if it doesn't change in bsm
4244 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4245 restrictBackground = mRestrictBackgroundBeforeBsm;
4246 }
4247
4248 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004249 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004250 }
4251
4252 // Change it at last so setRestrictBackground() won't affect this variable
4253 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4254 }
4255
Jeff Sharkey1b861272011-05-22 00:34:52 -07004256 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4257 final int size = source.size();
4258 for (int i = 0; i < size; i++) {
4259 target.put(source.keyAt(i), true);
4260 }
4261 }
4262
Stuart Scottf1fb3972015-04-02 18:00:02 -07004263 @Override
4264 public void factoryReset(String subscriber) {
4265 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4266
Stuart Scotte3e314d2015-04-20 14:07:45 -07004267 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4268 return;
4269 }
4270
Stuart Scottf1fb3972015-04-02 18:00:02 -07004271 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004272 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004273 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4274 for (NetworkPolicy policy : policies) {
4275 if (policy.template.equals(template)) {
4276 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4277 policy.inferred = false;
4278 policy.clearSnooze();
4279 }
4280 }
4281 setNetworkPolicies(policies);
4282
4283 // Turn restrict background data off
4284 setRestrictBackground(false);
4285
Stuart Scotte3e314d2015-04-20 14:07:45 -07004286 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4287 // Remove app's "restrict background data" flag
4288 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4289 setUidPolicy(uid, POLICY_NONE);
4290 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004291 }
4292 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004293
Sudheer Shankab8f23162017-08-04 13:30:10 -07004294 @Override
4295 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4296 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4297 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4298 }
4299
4300 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4301 final int uidRules;
4302 final boolean isBackgroundRestricted;
4303 synchronized (mUidRulesFirstLock) {
4304 uidRules = mUidRules.get(uid, RULE_NONE);
4305 isBackgroundRestricted = mRestrictBackground;
4306 }
4307 if (hasRule(uidRules, RULE_REJECT_ALL)) {
4308 if (LOGV) logUidStatus(uid, "blocked by power restrictions");
4309 return true;
4310 }
4311 if (!isNetworkMetered) {
4312 if (LOGV) logUidStatus(uid, "allowed on unmetered network");
4313 return false;
4314 }
4315 if (hasRule(uidRules, RULE_REJECT_METERED)) {
4316 if (LOGV) logUidStatus(uid, "blacklisted on metered network");
4317 return true;
4318 }
4319 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4320 if (LOGV) logUidStatus(uid, "whitelisted on metered network");
4321 return false;
4322 }
4323 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4324 if (LOGV) logUidStatus(uid, "temporary whitelisted on metered network");
4325 return false;
4326 }
4327 if (isBackgroundRestricted) {
4328 if (LOGV) logUidStatus(uid, "blocked when background is restricted");
4329 return true;
4330 }
4331 if (LOGV) logUidStatus(uid, "allowed by default");
4332 return false;
4333 }
4334
Felipe Lemed17fda42016-04-29 11:12:45 -07004335 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4336
4337 @Override
4338 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004339 synchronized (mUidRulesFirstLock) {
4340 boolean changed = removeUserStateUL(userId, false);
4341 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004342 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004343 synchronized (mNetworkPoliciesSecondLock) {
4344 writePolicyAL();
4345 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004346 }
4347 }
4348 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004349
4350 /**
4351 * @return true if the given uid is restricted from doing networking on metered networks.
4352 */
4353 @Override
4354 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4355 final int uidRules;
4356 final boolean isBackgroundRestricted;
4357 synchronized (mUidRulesFirstLock) {
4358 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4359 isBackgroundRestricted = mRestrictBackground;
4360 }
4361 return isBackgroundRestricted
4362 && !hasRule(uidRules, RULE_ALLOW_METERED)
4363 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4364 }
4365
4366 /**
4367 * @return true if networking is blocked on the given interface for the given uid according
4368 * to current networking policies.
4369 */
4370 @Override
4371 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004372 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004373 synchronized (mNetworkPoliciesSecondLock) {
4374 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004375 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004376 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004377 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004378
4379 @Override
4380 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4381 synchronized (mUidRulesFirstLock) {
4382 if (added) {
4383 mPowerSaveTempWhitelistAppIds.put(appId, true);
4384 } else {
4385 mPowerSaveTempWhitelistAppIds.delete(appId);
4386 }
4387 updateRulesForTempWhitelistChangeUL(appId);
4388 }
4389 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004390 }
4391
4392 private static boolean hasRule(int uidRules, int rule) {
4393 return (uidRules & rule) != 0;
4394 }
4395
4396 private static void logUidStatus(int uid, String descr) {
4397 Slog.d(TAG, String.format("uid %d is %s", uid, descr));
Felipe Lemed17fda42016-04-29 11:12:45 -07004398 }
Sudheer Shankae7361852017-03-07 11:51:46 -08004399
4400 /**
4401 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
4402 * (uid, procStateSeq) pairs.
4403 */
4404 @VisibleForTesting
4405 public static final class ProcStateSeqHistory {
4406 private static final int INVALID_UID = -1;
4407
4408 /**
4409 * Denotes maximum number of items this history can hold.
4410 */
4411 private final int mMaxCapacity;
4412 /**
4413 * Used for storing the uid information.
4414 */
4415 private final int[] mUids;
4416 /**
4417 * Used for storing the sequence numbers associated with {@link #mUids}.
4418 */
4419 private final long[] mProcStateSeqs;
4420 /**
4421 * Points to the next available slot for writing (uid, procStateSeq) pair.
4422 */
4423 private int mHistoryNext;
4424
4425 public ProcStateSeqHistory(int maxCapacity) {
4426 mMaxCapacity = maxCapacity;
4427 mUids = new int[mMaxCapacity];
4428 Arrays.fill(mUids, INVALID_UID);
4429 mProcStateSeqs = new long[mMaxCapacity];
4430 }
4431
4432 @GuardedBy("mUidRulesFirstLock")
4433 public void addProcStateSeqUL(int uid, long procStateSeq) {
4434 mUids[mHistoryNext] = uid;
4435 mProcStateSeqs[mHistoryNext] = procStateSeq;
4436 mHistoryNext = increaseNext(mHistoryNext, 1);
4437 }
4438
4439 @GuardedBy("mUidRulesFirstLock")
4440 public void dumpUL(IndentingPrintWriter fout) {
4441 if (mUids[0] == INVALID_UID) {
4442 fout.println("NONE");
4443 return;
4444 }
4445 int index = mHistoryNext;
4446 do {
4447 index = increaseNext(index, -1);
4448 if (mUids[index] == INVALID_UID) {
4449 break;
4450 }
4451 fout.println(getString(mUids[index], mProcStateSeqs[index]));
4452 } while (index != mHistoryNext);
4453 }
4454
4455 public static String getString(int uid, long procStateSeq) {
Sudheer Shankadb9aaf032017-06-19 19:05:31 -07004456 return "UID=" + uid + " Seq=" + procStateSeq;
Sudheer Shankae7361852017-03-07 11:51:46 -08004457 }
4458
4459 private int increaseNext(int next, int increment) {
4460 next += increment;
4461 if (next >= mMaxCapacity) {
4462 next = 0;
4463 } else if (next < 0) {
4464 next = mMaxCapacity - 1;
4465 }
4466 return next;
4467 }
4468 }
Chris Wren193ae6b2017-03-31 15:17:11 -04004469
4470 private class NotificationId {
4471 private final String mTag;
4472 private final int mId;
4473
4474 NotificationId(NetworkPolicy policy, int type) {
4475 mTag = buildNotificationTag(policy, type);
4476 mId = type;
4477 }
4478
4479 @Override
4480 public boolean equals(Object o) {
4481 if (this == o) return true;
4482 if (!(o instanceof NotificationId)) return false;
4483 NotificationId that = (NotificationId) o;
4484 return Objects.equals(mTag, that.mTag);
4485 }
4486
4487 @Override
4488 public int hashCode() {
4489 return Objects.hash(mTag);
4490 }
4491
4492 /**
4493 * Build unique tag that identifies an active {@link NetworkPolicy}
4494 * notification of a specific type, like {@link #TYPE_LIMIT}.
4495 */
4496 private String buildNotificationTag(NetworkPolicy policy, int type) {
4497 return TAG + ":" + policy.template.hashCode() + ":" + type;
4498 }
4499
4500 public String getTag() {
4501 return mTag;
4502 }
4503
4504 public int getId() {
4505 return mId;
4506 }
4507 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004508}