blob: da710492ec0311934692853a559d9b946364d80b [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;
Sudheer Shanka352dc572017-09-22 17:09:38 -070085import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_DEFAULT;
86import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_NON_METERED;
87import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_TMP_WHITELIST;
88import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_WHITELIST;
89import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BG_RESTRICT;
90import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BLACKLIST;
91import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_POWER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070092import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060093
Jeff Sharkey21c9c452011-06-07 12:26:43 -070094import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080095import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070096import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070097
Dianne Hackborn88e98df2015-03-23 13:29:14 -070098import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070099import android.annotation.IntDef;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700100import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700101import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -0800102import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700103import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700104import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700105import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700106import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700107import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700108import android.app.Notification;
109import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700110import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700111import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700112import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700113import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700114import android.content.Intent;
115import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700116import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700117import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700118import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700119import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700120import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700121import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700122import android.net.ConnectivityManager;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600123import android.net.ConnectivityManager.NetworkCallback;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700124import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700125import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700126import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700127import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700128import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700129import android.net.LinkProperties;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600130import android.net.Network;
131import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700132import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700133import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600134import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700135import android.net.NetworkQuotaInfo;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600136import android.net.NetworkRequest;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700137import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700138import android.net.NetworkTemplate;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600139import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700140import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700141import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700142import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700143import android.os.Environment;
144import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700145import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700146import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700147import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700148import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700149import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700150import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700151import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700152import android.os.PowerManager.ServiceType;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700153import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600154import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800155import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700156import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700157import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600158import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700159import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700160import android.os.ShellCallback;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600161import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700162import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700163import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700164import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700165import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100166import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700167import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600168import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800169import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600170import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700171import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400172import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700173import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700174import android.util.ArrayMap;
175import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700176import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700177import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700178import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700179import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600180import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700181import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600182import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700183import android.util.SparseBooleanArray;
184import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700185import android.util.TrustedTime;
186import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700187
Jeff Sharkey497e4432011-06-14 17:27:29 -0700188import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700189import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800190import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400191import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500192import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700193import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800194import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600195import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700196import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700197import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600198import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700199import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700200import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700201import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800202import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600203
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600204import libcore.io.IoUtils;
205
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700206import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700207import org.xmlpull.v1.XmlSerializer;
208
209import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700210import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700211import java.io.FileInputStream;
212import java.io.FileNotFoundException;
213import java.io.FileOutputStream;
214import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700215import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700216import java.lang.annotation.Retention;
217import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100218import java.nio.charset.StandardCharsets;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600219import java.time.ZoneId;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600220import java.time.ZonedDateTime;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700221import java.util.ArrayList;
222import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700223import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600224import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400225import java.util.Objects;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800226import java.util.concurrent.CountDownLatch;
227import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700228
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700229/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700230 * Service that maintains low-level network policy rules, using
231 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700232 * <p>
233 * Derives active rules by combining a given policy with other system status,
234 * and delivers to listeners, such as {@link ConnectivityManager}, for
235 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700236 *
237 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000238 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700239 * <ul>
240 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
241 * rules).
242 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
243 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000244 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
245 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700246 * </ul>
247 *
248 * <p>
249 * As such, methods that require synchronization have the following prefixes:
250 * <ul>
251 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
252 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000253 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
254 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700255 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700256 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700257public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700258 static final String TAG = NetworkPolicyLogger.TAG;
259 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
260 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700261
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700262 private static final int VERSION_INIT = 1;
263 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700264 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800265 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800266 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800267 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700268 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700269 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700270 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700271 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600272 private static final int VERSION_ADDED_CYCLE = 11;
273 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700274
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
Sudheer Shanka352dc572017-09-22 17:09:38 -0700474 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800475
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700476 // TODO: keep whitelist of system-critical services that should never have
477 // rules enforced, such as system, phone, and radio UIDs.
478
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700479 // TODO: migrate notifications to SystemUI
480
Jeff Sharkey75279902011-05-24 18:39:45 -0700481 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700482 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
483 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700484 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
485 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700486 }
487
488 private static File getSystemDir() {
489 return new File(Environment.getDataDirectory(), "system");
490 }
491
492 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700493 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700494 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700495 mContext = checkNotNull(context, "missing context");
496 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700497 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700498 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700499 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700500 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700501 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700502 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700503 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700504 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700505
Amith Yamasani450a16b2013-09-18 16:28:50 -0700506 HandlerThread thread = new HandlerThread(TAG);
507 thread.start();
508 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700509
Makoto Onuki8e777332017-03-28 11:25:47 -0700510 // We create another thread for the UID events, which are more time-critical.
511 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
512 /*allowIo=*/ false);
513 mUidEventThread.start();
514 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
515
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700516 mSuppressDefaultPolicy = suppressDefaultPolicy;
517
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700518 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700519
520 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800521
Felipe Lemed17fda42016-04-29 11:12:45 -0700522 // Expose private service for system components to use.
523 LocalServices.addService(NetworkPolicyManagerInternal.class,
524 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700525 }
526
527 public void bindConnectivityManager(IConnectivityManager connManager) {
528 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700529 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700530
Jeff Sharkey497e4432011-06-14 17:27:29 -0700531 public void bindNotificationManager(INotificationManager notifManager) {
532 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
533 }
534
Felipe Lemef0823852016-06-08 13:43:08 -0700535 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700536 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700537 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
538 mPowerSaveWhitelistExceptIdleAppIds.clear();
539 if (whitelist != null) {
540 for (int uid : whitelist) {
541 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
542 }
543 }
544 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700545 mPowerSaveWhitelistAppIds.clear();
546 if (whitelist != null) {
547 for (int uid : whitelist) {
548 mPowerSaveWhitelistAppIds.put(uid, true);
549 }
550 }
551 } catch (RemoteException e) {
552 }
553 }
554
Felipe Lemea9505cc2016-02-26 10:28:41 -0800555 /**
556 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
557 * revoke the whitelist.
558 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700559 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800560 */
Felipe Lemef0823852016-06-08 13:43:08 -0700561 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800562 final List<UserInfo> users = mUserManager.getUsers();
563 final int numberUsers = users.size();
564
Felipe Lemea110eec2016-04-29 09:58:06 -0700565 boolean changed = false;
566 for (int i = 0; i < numberUsers; i++) {
567 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700568 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700569 }
570 return changed;
571 }
572
Felipe Lemef0823852016-06-08 13:43:08 -0700573 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700574 final SystemConfig sysConfig = SystemConfig.getInstance();
575 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800576 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
577 boolean changed = false;
578 for (int i = 0; i < allowDataUsage.size(); i++) {
579 final String pkg = allowDataUsage.valueAt(i);
580 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700581 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
582 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800583 final ApplicationInfo app;
584 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700585 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800586 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700587 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
588 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800589 continue;
590 }
591 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700592 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
593 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800594 continue;
595 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700596 final int uid = UserHandle.getUid(userId, app.uid);
597 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
598 if (LOGD)
599 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
600 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800601 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700602 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700603 if (LOGD)
604 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
605 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700606 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700607 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800608 }
609 }
610 return changed;
611 }
612
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800613 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700614 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800615 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700616 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800617 // Boost thread's priority during system server init
618 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700619 if (!isBandwidthControlEnabled()) {
620 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
621 return;
622 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700623
Felipe Leme873a83a2016-09-07 11:34:10 -0700624 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700625
Felipe Leme873a83a2016-09-07 11:34:10 -0700626 synchronized (mUidRulesFirstLock) {
627 synchronized (mNetworkPoliciesSecondLock) {
628 updatePowerSaveWhitelistUL();
629 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
630 mPowerManagerInternal.registerLowPowerModeObserver(
631 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800632 @Override
633 public int getServiceType() {
634 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700635 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800636
637 @Override
638 public void onLowPowerModeChanged(PowerSaveState result) {
639 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800640 if (LOGD) {
641 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
642 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800643 synchronized (mUidRulesFirstLock) {
644 if (mRestrictPower != enabled) {
645 mRestrictPower = enabled;
646 updateRulesForRestrictPowerUL();
647 }
648 }
649 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800650 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800651 mRestrictPower = mPowerManagerInternal.getLowPowerState(
652 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700653
654 mSystemReady = true;
655
656 // read policy from disk
657 readPolicyAL();
658
jackqdyulei29c82ab2017-03-10 14:09:16 -0800659 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700660 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800661 mRestrictBackgroundPowerState = mPowerManagerInternal
662 .getLowPowerState(ServiceType.DATA_SAVER);
663 final boolean localRestrictBackground =
664 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700665 if (localRestrictBackground && !mLoadedRestrictBackground) {
666 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800667 }
668 mPowerManagerInternal.registerLowPowerModeObserver(
669 new PowerManagerInternal.LowPowerModeListener() {
670 @Override
671 public int getServiceType() {
672 return ServiceType.DATA_SAVER;
673 }
674
675 @Override
676 public void onLowPowerModeChanged(PowerSaveState result) {
677 synchronized (mUidRulesFirstLock) {
678 updateRestrictBackgroundByLowPowerModeUL(result);
679 }
680 }
681 });
682
Felipe Leme873a83a2016-09-07 11:34:10 -0700683 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
684 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700685 }
Felipe Lemef0823852016-06-08 13:43:08 -0700686
Sudheer Shanka543339f2017-07-28 15:18:07 -0700687 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700688 updateRulesForGlobalChangeAL(false);
689 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700690 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800691 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700692
Sudheer Shankae7361852017-03-07 11:51:46 -0800693 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700694 try {
695 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000696 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800697 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700698 mNetworkManager.registerObserver(mAlertObserver);
699 } catch (RemoteException e) {
700 // ignored; both services live in system_server
701 }
702
703 // listen for changes to power save whitelist
704 final IntentFilter whitelistFilter = new IntentFilter(
705 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
706 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
707
Felipe Leme873a83a2016-09-07 11:34:10 -0700708 // watch for network interfaces to be claimed
709 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
710 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
711
712 // listen for package changes to update policy
713 final IntentFilter packageFilter = new IntentFilter();
714 packageFilter.addAction(ACTION_PACKAGE_ADDED);
715 packageFilter.addDataScheme("package");
716 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
717
718 // listen for UID changes to update policy
719 mContext.registerReceiver(
720 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
721
722 // listen for user changes to update policy
723 final IntentFilter userFilter = new IntentFilter();
724 userFilter.addAction(ACTION_USER_ADDED);
725 userFilter.addAction(ACTION_USER_REMOVED);
726 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
727
728 // listen for stats update events
729 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
730 mContext.registerReceiver(
731 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
732
733 // listen for restrict background changes from notifications
734 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
735 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
736
737 // listen for snooze warning from notifications
738 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
739 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
740 MANAGE_NETWORK_POLICY, mHandler);
741
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600742 // listen for configured wifi networks to be loaded
743 final IntentFilter wifiFilter =
744 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
745 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700746
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700747 // listen for carrier config changes to update data cycle information
748 final IntentFilter carrierConfigFilter = new IntentFilter(
749 ACTION_CARRIER_CONFIG_CHANGED);
750 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
751
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600752 // listen for meteredness changes
753 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
754 new NetworkRequest.Builder().build(), mNetworkCallback);
755
Felipe Leme873a83a2016-09-07 11:34:10 -0700756 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800757 // tell systemReady() that the service has been initialized
758 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700759 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800760 // Restore the default priority after init is done
761 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700762 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700763 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700764 }
765
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800766 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
767 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
768 mHandler.post(() -> initService(initCompleteSignal));
769 return initCompleteSignal;
770 }
771
772 public void systemReady(CountDownLatch initCompleteSignal) {
773 // wait for initService to complete
774 try {
775 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
776 throw new IllegalStateException("Service " + TAG +" init timeout");
777 }
778 } catch (InterruptedException e) {
779 Thread.currentThread().interrupt();
780 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
781 }
782 }
783
Sudheer Shankac9d94072017-02-22 22:13:55 +0000784 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700785 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700786 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
787 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700788 }
789
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700790 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700791 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700792 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700793
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700794 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700795 }
796
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700797 @Override public void onUidIdle(int uid, boolean disabled) {
798 }
799
800 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700801 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700802 };
803
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700804 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700805 @Override
806 public void onReceive(Context context, Intent intent) {
807 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700808 synchronized (mUidRulesFirstLock) {
809 updatePowerSaveWhitelistUL();
810 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700811 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700812 }
813 }
814 };
815
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700816 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700817 @Override
818 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700819 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700820
821 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700822 final int uid = intent.getIntExtra(EXTRA_UID, -1);
823 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700824
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700825 if (ACTION_PACKAGE_ADDED.equals(action)) {
826 // update rules for UID, since it might be subject to
827 // global background data policy
828 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700829 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700830 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700831 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700832 }
833 }
834 };
835
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700836 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700837 @Override
838 public void onReceive(Context context, Intent intent) {
839 // on background handler thread, and UID_REMOVED is protected
840
841 final int uid = intent.getIntExtra(EXTRA_UID, -1);
842 if (uid == -1) return;
843
844 // remove any policy and update rules to clean up
845 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700846 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700847 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700848 synchronized (mNetworkPoliciesSecondLock) {
849 writePolicyAL();
850 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700851 }
852 }
853 };
854
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700855 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700856 @Override
857 public void onReceive(Context context, Intent intent) {
858 // on background handler thread, and USER_ADDED and USER_REMOVED
859 // broadcasts are protected
860
861 final String action = intent.getAction();
862 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
863 if (userId == -1) return;
864
Amith Yamasani15e472352015-04-24 19:06:07 -0700865 switch (action) {
866 case ACTION_USER_REMOVED:
867 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700868 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800869 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700870 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700871 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700872 if (action == ACTION_USER_ADDED) {
873 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700874 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700875 }
876 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700877 synchronized (mNetworkPoliciesSecondLock) {
878 updateRulesForGlobalChangeAL(true);
879 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700880 }
881 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700882 }
883 }
884 };
885
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700886 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700887 * Receiver that watches for {@link INetworkStatsService} updates, which we
888 * use to check against {@link NetworkPolicy#warningBytes}.
889 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700890 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700891 @Override
892 public void onReceive(Context context, Intent intent) {
893 // on background handler thread, and verified
894 // READ_NETWORK_USAGE_HISTORY permission above.
895
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800896 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700897 synchronized (mNetworkPoliciesSecondLock) {
898 updateNetworkEnabledNL();
899 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700900 }
901 }
902 };
903
904 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700905 * Receiver that watches for {@link Notification} control of
906 * {@link #mRestrictBackground}.
907 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700908 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700909 @Override
910 public void onReceive(Context context, Intent intent) {
911 // on background handler thread, and verified MANAGE_NETWORK_POLICY
912 // permission above.
913
914 setRestrictBackground(false);
915 }
916 };
917
918 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800919 * Receiver that watches for {@link Notification} control of
920 * {@link NetworkPolicy#lastWarningSnooze}.
921 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700922 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800923 @Override
924 public void onReceive(Context context, Intent intent) {
925 // on background handler thread, and verified MANAGE_NETWORK_POLICY
926 // permission above.
927
928 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
929 performSnooze(template, TYPE_WARNING);
930 }
931 };
932
933 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600934 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -0600935 * we can perform upgrade logic. After initial upgrade logic, it updates
936 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700937 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600938 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700939 @Override
940 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900941 synchronized (mUidRulesFirstLock) {
942 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600943 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600944 }
945 }
946 // Only need to perform upgrade logic once
947 mContext.unregisterReceiver(this);
948 }
949 };
950
951 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
952 @Override
953 public void onCapabilitiesChanged(Network network,
954 NetworkCapabilities networkCapabilities) {
955 if (network == null || networkCapabilities == null) return;
956
957 synchronized (mNetworkPoliciesSecondLock) {
958 final boolean oldMetered = mNetworkMetered.get(network.netId, false);
959 final boolean newMetered = !networkCapabilities
960 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
961
962 if ((oldMetered != newMetered) || mNetworkMetered.indexOfKey(network.netId) < 0) {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700963 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600964 mNetworkMetered.put(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -0600965 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700966 }
967 }
968 }
969 };
970
971 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700972 * Observer that watches for {@link INetworkManagementService} alerts.
973 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700974 final private INetworkManagementEventObserver mAlertObserver
975 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700976 @Override
977 public void limitReached(String limitName, String iface) {
978 // only someone like NMS should be calling us
979 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
980
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800981 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
982 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700983 }
984 }
985 };
986
987 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700988 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
989 * to show visible notifications as needed.
990 */
Felipe Lemef0823852016-06-08 13:43:08 -0700991 void updateNotificationsNL() {
992 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700993
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700994 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -0400995 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700996 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700997
998 // TODO: when switching to kernel notifications, compute next future
999 // cycle boundary to recompute notifications.
1000
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001001 // examine stats for each active policy
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001002 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1003 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001004 // ignore policies that aren't relevant to user
1005 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001006 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001007
Jeff Sharkey53313d72017-07-13 16:47:32 -06001008 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1009 .cycleIterator(policy).next();
1010 final long start = cycle.first.toInstant().toEpochMilli();
1011 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001012 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001013
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001014 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001015 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001016 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1017 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001018 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001019 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001020 }
1021
Jeff Sharkey497e4432011-06-14 17:27:29 -07001022 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001023 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001024
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001025 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001026 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001027 }
1028 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001029 }
1030
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001031 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001032 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001033 final NotificationId notificationId = beforeNotifs.valueAt(i);
1034 if (!mActiveNotifs.contains(notificationId)) {
1035 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001036 }
1037 }
1038 }
1039
1040 /**
1041 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001042 * current device state, such as when
1043 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1044 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001045 */
1046 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001047 if (template.isMatchRuleMobile()) {
1048 final TelephonyManager tele = TelephonyManager.from(mContext);
1049 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001050
Jeff Sharkey32566012014-12-02 18:30:14 -08001051 // Mobile template is relevant when any active subscriber matches
1052 final int[] subIds = sub.getActiveSubscriptionIdList();
1053 for (int subId : subIds) {
1054 final String subscriberId = tele.getSubscriberId(subId);
1055 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001056 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001057 if (template.matches(probeIdent)) {
1058 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001059 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001060 }
1061 return false;
1062 } else {
1063 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001064 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001065 }
1066
1067 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001068 * Notify that given {@link NetworkTemplate} is over
1069 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1070 */
Felipe Lemef0823852016-06-08 13:43:08 -07001071 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001072 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001073 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001074 mOverLimitNotified.add(template);
1075 }
1076 }
1077
Felipe Lemef0823852016-06-08 13:43:08 -07001078 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001079 mOverLimitNotified.remove(template);
1080 }
1081
1082 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001083 * Show notification for combined {@link NetworkPolicy} and specific type,
1084 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1085 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001086 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001087 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001088 final Notification.Builder builder =
1089 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001090 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001091 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001092 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001093 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001094
1095 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001096 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001097 switch (type) {
1098 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001099 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001100 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001101
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001102 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001103 builder.setTicker(title);
1104 builder.setContentTitle(title);
1105 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001106 builder.setDefaults(Notification.DEFAULT_ALL);
Julia Reynoldsbad42972017-04-25 13:52:49 -04001107 builder.setChannelId(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001108
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001109 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1110 builder.setDeleteIntent(PendingIntent.getBroadcast(
1111 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1112
Wei Liu546cb772016-07-21 16:19:01 -07001113 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001114 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001115 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1116
Jeff Sharkey497e4432011-06-14 17:27:29 -07001117 break;
1118 }
1119 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001120 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001121
1122 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001123 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001124 switch (policy.template.getMatchRule()) {
1125 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001126 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001127 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001128 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001129 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001130 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001131 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001132 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001133 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001134 case MATCH_WIFI:
1135 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001136 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001137 break;
1138 default:
1139 title = null;
1140 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001141 }
1142
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001143 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001144 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001145 builder.setTicker(title);
1146 builder.setContentTitle(title);
1147 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001148
Wei Liu546cb772016-07-21 16:19:01 -07001149 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001150 builder.setContentIntent(PendingIntent.getActivity(
1151 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1152 break;
1153 }
1154 case TYPE_LIMIT_SNOOZED: {
1155 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001156 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001157 Formatter.formatFileSize(mContext, overBytes));
1158
1159 final CharSequence title;
1160 switch (policy.template.getMatchRule()) {
1161 case MATCH_MOBILE_3G_LOWER:
1162 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1163 break;
1164 case MATCH_MOBILE_4G:
1165 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1166 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001167 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001168 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1169 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001170 case MATCH_WIFI:
1171 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1172 break;
1173 default:
1174 title = null;
1175 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001176 }
1177
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001178 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001179 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001180 builder.setTicker(title);
1181 builder.setContentTitle(title);
1182 builder.setContentText(body);
1183
Wei Liu546cb772016-07-21 16:19:01 -07001184 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001185 builder.setContentIntent(PendingIntent.getActivity(
1186 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001187 break;
1188 }
1189 }
1190
1191 // TODO: move to NotificationManager once we can mock it
1192 try {
1193 final String packageName = mContext.getPackageName();
Chris Wren193ae6b2017-03-31 15:17:11 -04001194 if (!TextUtils.isEmpty(body)) {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001195 builder.setStyle(new Notification.BigTextStyle()
1196 .bigText(body));
1197 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001198 mNotifManager.enqueueNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001199 packageName, packageName, notificationId.getTag(), notificationId.getId(),
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001200 builder.build(), UserHandle.USER_ALL);
Chris Wren193ae6b2017-03-31 15:17:11 -04001201 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001202 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001203 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001204 }
1205 }
1206
Chris Wren193ae6b2017-03-31 15:17:11 -04001207 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001208 // TODO: move to NotificationManager once we can mock it
1209 try {
1210 final String packageName = mContext.getPackageName();
1211 mNotifManager.cancelNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001212 packageName, notificationId.getTag(), notificationId.getId(),
1213 UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001214 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001215 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001216 }
1217 }
1218
1219 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001220 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001221 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001222 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001223 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001224 @Override
1225 public void onReceive(Context context, Intent intent) {
1226 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1227 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001228
1229 maybeRefreshTrustedTime();
Hugo Benichi446c9c92017-04-10 09:41:10 +09001230 synchronized (mUidRulesFirstLock) {
1231 synchronized (mNetworkPoliciesSecondLock) {
1232 ensureActiveMobilePolicyAL();
1233 normalizePoliciesNL();
1234 updateNetworkEnabledNL();
1235 updateNetworkRulesNL();
1236 updateNotificationsNL();
1237 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001238 }
1239 }
1240 };
1241
1242 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001243 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1244 * if necessary.
1245 *
1246 * @param subId that has its associated NetworkPolicy updated if necessary
1247 * @return if any policies were updated
1248 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001249 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1250 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001251
1252 boolean policyUpdated = false;
1253 final String subscriberId = TelephonyManager.from(mContext).getSubscriberId(subId);
1254
1255 // find and update the mobile NetworkPolicy for this subscriber id
1256 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1257 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1258 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1259 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1260 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001261 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1262 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001263 }
1264 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001265 return policyUpdated;
1266 }
1267
1268 /**
1269 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1270 *
1271 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1272 * to do so, it returns the fallback value.
1273 *
1274 * @param config The CarrierConfig to read the value from.
1275 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1276 * @return cycleDay to use in the mobile NetworkPolicy.
1277 */
1278 @VisibleForTesting
1279 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1280 int fallbackCycleDay) {
1281 if (config == null) {
1282 return fallbackCycleDay;
1283 }
1284 int cycleDay =
1285 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1286 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1287 return fallbackCycleDay;
1288 }
1289 // validate cycleDay value
1290 final Calendar cal = Calendar.getInstance();
1291 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1292 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1293 Slog.e(TAG, "Invalid date in "
1294 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1295 return fallbackCycleDay;
1296 }
1297 return cycleDay;
1298 }
1299
1300 /**
1301 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1302 *
1303 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1304 * to do so, it returns the fallback value.
1305 *
1306 * @param config The CarrierConfig to read the value from.
1307 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1308 * @return warningBytes to use in the mobile NetworkPolicy.
1309 */
1310 @VisibleForTesting
1311 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1312 long fallbackWarningBytes) {
1313 if (config == null) {
1314 return fallbackWarningBytes;
1315 }
1316 long warningBytes =
1317 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1318
1319 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1320 return WARNING_DISABLED;
1321 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1322 return getPlatformDefaultWarningBytes();
1323 } else if (warningBytes < 0) {
1324 Slog.e(TAG, "Invalid value in "
1325 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1326 + "non-negative value but got: " + warningBytes);
1327 return fallbackWarningBytes;
1328 }
1329
1330 return warningBytes;
1331 }
1332
1333 /**
1334 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1335 *
1336 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1337 * to do so, it returns the fallback value.
1338 *
1339 * @param config The CarrierConfig to read the value from.
1340 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1341 * @return limitBytes to use in the mobile NetworkPolicy.
1342 */
1343 @VisibleForTesting
1344 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1345 long fallbackLimitBytes) {
1346 if (config == null) {
1347 return fallbackLimitBytes;
1348 }
1349 long limitBytes =
1350 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1351
1352 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1353 return LIMIT_DISABLED;
1354 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1355 return getPlatformDefaultLimitBytes();
1356 } else if (limitBytes < 0) {
1357 Slog.e(TAG, "Invalid value in "
1358 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1359 + "non-negative value but got: " + limitBytes);
1360 return fallbackLimitBytes;
1361 }
1362 return limitBytes;
1363 }
1364
1365 /**
1366 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1367 */
1368 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1369 @Override
1370 public void onReceive(Context context, Intent intent) {
1371 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1372 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1373
1374 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1375 return;
1376 }
1377 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
1378 final TelephonyManager tele = TelephonyManager.from(mContext);
1379 final String subscriberId = tele.getSubscriberId(subId);
1380
1381 maybeRefreshTrustedTime();
1382 synchronized (mUidRulesFirstLock) {
1383 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001384 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001385 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001386 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001387 if (!updated) return;
1388 // update network and notification rules, as the data cycle changed and it's
1389 // possible that we should be triggering warnings/limits now
1390 handleNetworkPoliciesUpdateAL(true);
1391 }
1392 }
1393 }
1394 };
1395
1396 /**
1397 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1398 * one has been updated.
1399 *
1400 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1401 * update.
1402 */
1403 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1404 if (shouldNormalizePolicies) {
1405 normalizePoliciesNL();
1406 }
1407 updateNetworkEnabledNL();
1408 updateNetworkRulesNL();
1409 updateNotificationsNL();
1410 writePolicyAL();
1411 }
1412
1413 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001414 * Proactively control network data connections when they exceed
1415 * {@link NetworkPolicy#limitBytes}.
1416 */
Felipe Lemef0823852016-06-08 13:43:08 -07001417 void updateNetworkEnabledNL() {
1418 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001419
1420 // TODO: reset any policy-disabled networks when any policy is removed
1421 // completely, which is currently rare case.
1422
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001423 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1424 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001425 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001426 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001427 setNetworkTemplateEnabled(policy.template, true);
1428 continue;
1429 }
1430
Jeff Sharkey53313d72017-07-13 16:47:32 -06001431 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1432 .cycleIterator(policy).next();
1433 final long start = cycle.first.toInstant().toEpochMilli();
1434 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001435 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001436
1437 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001438 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1439 && policy.lastLimitSnooze < start;
1440 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001441
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001442 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001443 }
1444 }
1445
1446 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001447 * Proactively disable networks that match the given
1448 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001449 */
1450 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001451 // TODO: reach into ConnectivityManager to proactively disable bringing
1452 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001453
1454 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1455 // If mobile data usage hits the limit or if the user resumes the data, we need to
1456 // notify telephony.
1457 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1458 final TelephonyManager tm = TelephonyManager.from(mContext);
1459
1460 final int[] subIds = sm.getActiveSubscriptionIdList();
1461 for (int subId : subIds) {
1462 final String subscriberId = tm.getSubscriberId(subId);
1463 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1464 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1465 // Template is matched when subscriber id matches.
1466 if (template.matches(probeIdent)) {
1467 tm.setPolicyDataEnabled(enabled, subId);
1468 }
1469 }
1470 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001471 }
1472
1473 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001474 * Collect all ifaces from a {@link NetworkState} into the given set.
1475 */
1476 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1477 final String baseIface = state.linkProperties.getInterfaceName();
1478 if (baseIface != null) {
1479 ifaces.add(baseIface);
1480 }
1481 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1482 final String stackedIface = stackedLink.getInterfaceName();
1483 if (stackedIface != null) {
1484 ifaces.add(stackedIface);
1485 }
1486 }
1487 }
1488
1489 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001490 * Examine all connected {@link NetworkState}, looking for
1491 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1492 * remaining quota based on usage cycle and historical stats.
1493 */
Felipe Lemef0823852016-06-08 13:43:08 -07001494 void updateNetworkRulesNL() {
1495 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001496
1497 final NetworkState[] states;
1498 try {
1499 states = mConnManager.getAllNetworkState();
1500 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001501 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001502 return;
1503 }
1504
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001505 // First, generate identities of all connected networks so we can
1506 // quickly compare them against all defined policies below.
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001507 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001508 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001509 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001510 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001511 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001512 }
1513 }
1514
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001515 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001516 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001517
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001518 // For every well-defined policy, compute remaining data based on
1519 // current cycle and historical stats, and push to kernel.
1520 final ArraySet<String> matchingIfaces = new ArraySet<>();
1521 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1522 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1523
1524 // Collect all ifaces that match this policy
1525 matchingIfaces.clear();
1526 for (int j = identified.size() - 1; j >= 0; j--) {
1527 if (policy.template.matches(identified.valueAt(j))) {
1528 collectIfaces(matchingIfaces, identified.keyAt(j));
1529 }
1530 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001531
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001532 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001533 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001534 }
1535
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001536 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001537 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001538 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001539 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001540 if (hasLimit && policy.hasCycle()) {
1541 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1542 .cycleIterator(policy).next();
1543 final long start = cycle.first.toInstant().toEpochMilli();
1544 final long end = cycle.second.toInstant().toEpochMilli();
1545 final long totalBytes = getTotalBytes(policy.template, start, end);
1546
1547 if (policy.lastLimitSnooze >= start) {
1548 // snoozing past quota, but we still need to restrict apps,
1549 // so push really high quota.
1550 quotaBytes = Long.MAX_VALUE;
1551 } else {
1552 // remaining "quota" bytes are based on total usage in
1553 // current cycle. kernel doesn't like 0-byte rules, so we
1554 // set 1-byte quota and disable the radio later.
1555 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1556 }
1557 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001558 // metered network, but no policy limit; we still need to
1559 // restrict apps, so push really high quota.
1560 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001561 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001562
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001563 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001564 // TODO: switch to shared quota once NMS supports
1565 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001566 }
1567
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001568 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1569 final String iface = matchingIfaces.valueAt(j);
1570 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001571 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001572 }
1573 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001574
1575 // keep track of lowest warning or limit of active policies
1576 if (hasWarning && policy.warningBytes < lowestRule) {
1577 lowestRule = policy.warningBytes;
1578 }
1579 if (hasLimit && policy.limitBytes < lowestRule) {
1580 lowestRule = policy.limitBytes;
1581 }
1582 }
1583
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001584 // One final pass to catch any metered ifaces that don't have explicitly
1585 // defined policies; typically Wi-Fi networks.
1586 for (NetworkState state : states) {
1587 if (state.networkInfo != null && state.networkInfo.isConnected()
1588 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1589 matchingIfaces.clear();
1590 collectIfaces(matchingIfaces, state);
1591 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1592 final String iface = matchingIfaces.valueAt(j);
1593 if (!newMeteredIfaces.contains(iface)) {
1594 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1595 newMeteredIfaces.add(iface);
1596 }
1597 }
1598 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001599 }
1600
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001601 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001602 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1603 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001604 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001605 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001606 }
1607 }
1608 mMeteredIfaces = newMeteredIfaces;
1609
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001610 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001611 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001612
1613 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001614 }
1615
1616 /**
1617 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1618 * have at least a default mobile policy defined.
1619 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001620 private void ensureActiveMobilePolicyAL() {
1621 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001622 if (mSuppressDefaultPolicy) return;
1623
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001624 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001625 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001626
Jeff Sharkey32566012014-12-02 18:30:14 -08001627 final int[] subIds = sub.getActiveSubscriptionIdList();
1628 for (int subId : subIds) {
1629 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001630 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001631 }
1632 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001633
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001634 /**
1635 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1636 * have at least a default mobile policy defined.
1637 *
1638 * @param subId to build a default policy for
1639 * @param subscriberId that we check for an existing policy
1640 * @return true if a mobile network policy was added, or false one already existed.
1641 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001642 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001643 // Poke around to see if we already have a policy
1644 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001645 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001646 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1647 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1648 if (template.matches(probeIdent)) {
1649 if (LOGD) {
1650 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1651 + NetworkIdentity.scrubSubscriberId(subscriberId));
1652 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001653 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001654 }
1655 }
1656
Jeff Sharkey32566012014-12-02 18:30:14 -08001657 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1658 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001659 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001660 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001661 return true;
1662 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001663
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001664 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001665 final int dataWarningConfig = mContext.getResources().getInteger(
1666 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001667 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001668 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001669 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001670 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001671 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001672 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001673
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001674 private long getPlatformDefaultLimitBytes() {
1675 return LIMIT_DISABLED;
1676 }
1677
1678 @VisibleForTesting
1679 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001680 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001681 final RecurrenceRule cycleRule = NetworkPolicy
1682 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001683 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001684 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1685 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1686 synchronized (mUidRulesFirstLock) {
1687 synchronized (mNetworkPoliciesSecondLock) {
1688 updateDefaultMobilePolicyAL(subId, policy);
1689 }
1690 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001691 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001692 }
1693
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001694 /**
1695 * Update the given {@link NetworkPolicy} based on any carrier-provided
1696 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1697 * Leaves policy untouched if the user has modified it.
1698 *
1699 * @return if the policy was modified
1700 */
1701 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1702 if (!policy.inferred) {
1703 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1704 return false;
1705 }
1706
1707 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1708 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1709 policy.lastLimitSnooze, policy.metered, policy.inferred);
1710
1711 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1712 if (!ArrayUtils.isEmpty(plans)) {
1713 final SubscriptionPlan plan = plans[0];
1714 policy.cycleRule = plan.getCycleRule();
1715 final long planLimitBytes = plan.getDataLimitBytes();
1716 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1717 policy.warningBytes = getPlatformDefaultWarningBytes();
1718 policy.limitBytes = getPlatformDefaultLimitBytes();
1719 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1720 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1721 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1722 } else {
1723 policy.warningBytes = (planLimitBytes * 9) / 10;
1724 switch (plan.getDataLimitBehavior()) {
1725 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1726 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1727 policy.limitBytes = planLimitBytes;
1728 break;
1729 default:
1730 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1731 break;
1732 }
1733 }
1734 } else {
1735 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1736 final int currentCycleDay;
1737 if (policy.cycleRule.isMonthly()) {
1738 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1739 } else {
1740 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1741 }
1742 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1743 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1744 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1745 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1746 }
1747
1748 if (policy.equals(original)) {
1749 return false;
1750 } else {
1751 Slog.d(TAG, "Updated " + original + " to " + policy);
1752 return true;
1753 }
1754 }
1755
Felipe Lemef0823852016-06-08 13:43:08 -07001756 private void readPolicyAL() {
1757 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001758
1759 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001760 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001761 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001762 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001763 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001764
1765 FileInputStream fis = null;
1766 try {
1767 fis = mPolicyFile.openRead();
1768 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001769 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001770
Felipe Leme46b451f2016-08-19 08:46:17 -07001771 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1772 // to skip UIDs that were explicitly blacklisted.
1773 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1774
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001775 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001776 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001777 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001778 while ((type = in.next()) != END_DOCUMENT) {
1779 final String tag = in.getName();
1780 if (type == START_TAG) {
1781 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001782 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001783 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07001784 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
1785 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001786 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1787 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1788 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001789 final String networkId;
1790 if (version >= VERSION_ADDED_NETWORK_ID) {
1791 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1792 } else {
1793 networkId = null;
1794 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001795 final RecurrenceRule cycleRule;
1796 if (version >= VERSION_ADDED_CYCLE) {
1797 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1798 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1799 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1800 cycleRule = new RecurrenceRule(
1801 RecurrenceRule.convertZonedDateTime(start),
1802 RecurrenceRule.convertZonedDateTime(end),
1803 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001804 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001805 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1806 final String cycleTimezone;
1807 if (version >= VERSION_ADDED_TIMEZONE) {
1808 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1809 } else {
1810 cycleTimezone = "UTC";
1811 }
1812 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001813 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001814 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1815 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001816 final long lastLimitSnooze;
1817 if (version >= VERSION_SPLIT_SNOOZE) {
1818 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1819 } else if (version >= VERSION_ADDED_SNOOZE) {
1820 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001821 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001822 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001823 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001824 final boolean metered;
1825 if (version >= VERSION_ADDED_METERED) {
1826 metered = readBooleanAttribute(in, ATTR_METERED);
1827 } else {
1828 switch (networkTemplate) {
1829 case MATCH_MOBILE_3G_LOWER:
1830 case MATCH_MOBILE_4G:
1831 case MATCH_MOBILE_ALL:
1832 metered = true;
1833 break;
1834 default:
1835 metered = false;
1836 }
1837 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001838 final long lastWarningSnooze;
1839 if (version >= VERSION_SPLIT_SNOOZE) {
1840 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1841 } else {
1842 lastWarningSnooze = SNOOZE_NEVER;
1843 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001844 final boolean inferred;
1845 if (version >= VERSION_ADDED_INFERRED) {
1846 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1847 } else {
1848 inferred = false;
1849 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001850
Jeff Sharkey32566012014-12-02 18:30:14 -08001851 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1852 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001853 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001854 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
1855 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001856 lastLimitSnooze, metered, inferred));
1857 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001858
1859 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
1860 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1861 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1862 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1863 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
1864 RecurrenceRule.convertZonedDateTime(start),
1865 RecurrenceRule.convertZonedDateTime(end),
1866 RecurrenceRule.convertPeriod(period));
1867 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
1868 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
1869
1870 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
1871 SubscriptionPlan.BYTES_UNKNOWN);
1872 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
1873 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
1874 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
1875 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
1876 builder.setDataLimit(limitBytes, limitBehavior);
1877 }
1878
1879 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
1880 SubscriptionPlan.BYTES_UNKNOWN);
1881 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
1882 SubscriptionPlan.TIME_UNKNOWN);
1883 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
1884 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
1885 builder.setDataUsage(usageBytes, usageTime);
1886 }
1887
1888 final int subId = readIntAttribute(in, ATTR_SUB_ID);
1889 final SubscriptionPlan plan = builder.build();
1890 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
1891 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
1892
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001893 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
1894 mSubscriptionPlansOwner.put(subId, ownerPackage);
1895
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001896 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001897 final int uid = readIntAttribute(in, ATTR_UID);
1898 final int policy = readIntAttribute(in, ATTR_POLICY);
1899
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001900 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001901 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001902 } else {
1903 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1904 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001905 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001906 final int appId = readIntAttribute(in, ATTR_APP_ID);
1907 final int policy = readIntAttribute(in, ATTR_POLICY);
1908
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001909 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001910 // app policy is deprecated so this is only used in pre system user split.
1911 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001912 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001913 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001914 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001915 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001916 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001917 } else if (TAG_WHITELIST.equals(tag)) {
1918 insideWhitelist = true;
1919 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1920 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001921 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001922 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1923 final int uid = readIntAttribute(in, ATTR_UID);
1924 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001925 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001926 } else if (type == END_TAG) {
1927 if (TAG_WHITELIST.equals(tag)) {
1928 insideWhitelist = false;
1929 }
1930
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001931 }
1932 }
1933
Felipe Leme46b451f2016-08-19 08:46:17 -07001934 final int size = whitelistedRestrictBackground.size();
1935 for (int i = 0; i < size; i++) {
1936 final int uid = whitelistedRestrictBackground.keyAt(i);
1937 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1938 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1939 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1940 + " because its policy is " + uidPoliciesToString(policy));
1941 continue;
1942 }
1943 if (UserHandle.isApp(uid)) {
1944 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1945 if (LOGV)
1946 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1947 setUidPolicyUncheckedUL(uid, newPolicy, false);
1948 } else {
1949 Slog.w(TAG, "unable to update policy on UID " + uid);
1950 }
1951 }
1952
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001953 } catch (FileNotFoundException e) {
1954 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001955 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001956 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001957 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001958 } finally {
1959 IoUtils.closeQuietly(fis);
1960 }
1961 }
1962
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001963 /**
1964 * Upgrade legacy background data flags, notifying listeners of one last
1965 * change to always-true.
1966 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001967 private void upgradeDefaultBackgroundDataUL() {
1968 // This method is only called when we're unable to find the network policy flag, which
1969 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001970
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001971 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07001972 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001973 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
1974
1975 // NOTE: We used to read the legacy setting here :
1976 //
1977 // final int legacyFlagValue = Settings.Secure.getInt(
1978 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
1979 //
1980 // This is no longer necessary because we will never upgrade directly from Gingerbread
1981 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
1982 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001983 }
1984
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001985 /**
1986 * Perform upgrade step of moving any user-defined meterness overrides over
1987 * into {@link WifiConfiguration}.
1988 */
1989 private void upgradeWifiMeteredOverrideAL() {
1990 boolean modified = false;
1991 final WifiManager wm = mContext.getSystemService(WifiManager.class);
1992 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
1993 for (int i = 0; i < mNetworkPolicy.size(); ) {
1994 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1995 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
1996 && !policy.inferred) {
1997 mNetworkPolicy.removeAt(i);
1998 modified = true;
1999
2000 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2001 for (WifiConfiguration config : configs) {
2002 if (Objects.equals(resolveNetworkId(config), networkId)) {
2003 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2004 config.meteredOverride = policy.metered
2005 ? WifiConfiguration.METERED_OVERRIDE_METERED
2006 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2007 wm.updateNetwork(config);
2008 }
2009 }
2010 } else {
2011 i++;
2012 }
2013 }
2014 if (modified) {
2015 writePolicyAL();
2016 }
2017 }
2018
Felipe Lemef0823852016-06-08 13:43:08 -07002019 void writePolicyAL() {
2020 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002021
2022 FileOutputStream fos = null;
2023 try {
2024 fos = mPolicyFile.startWrite();
2025
2026 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002027 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002028 out.startDocument(null, true);
2029
2030 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002031 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002032 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002033
2034 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002035 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2036 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002037 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002038 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002039
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002040 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002041 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2042 final String subscriberId = template.getSubscriberId();
2043 if (subscriberId != null) {
2044 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002045 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002046 final String networkId = template.getNetworkId();
2047 if (networkId != null) {
2048 out.attribute(null, ATTR_NETWORK_ID, networkId);
2049 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002050 writeStringAttribute(out, ATTR_CYCLE_START,
2051 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2052 writeStringAttribute(out, ATTR_CYCLE_END,
2053 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2054 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2055 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002056 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2057 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002058 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2059 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002060 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002061 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002062 out.endTag(null, TAG_NETWORK_POLICY);
2063 }
2064
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002065 // write all known subscription plans
2066 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2067 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002068 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002069 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2070 if (ArrayUtils.isEmpty(plans)) continue;
2071
2072 for (SubscriptionPlan plan : plans) {
2073 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2074 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002075 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002076 final RecurrenceRule cycleRule = plan.getCycleRule();
2077 writeStringAttribute(out, ATTR_CYCLE_START,
2078 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2079 writeStringAttribute(out, ATTR_CYCLE_END,
2080 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2081 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2082 RecurrenceRule.convertPeriod(cycleRule.period));
2083 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2084 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2085 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2086 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2087 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2088 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2089 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2090 }
2091 }
2092
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002093 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002094 for (int i = 0; i < mUidPolicy.size(); i++) {
2095 final int uid = mUidPolicy.keyAt(i);
2096 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002097
Jeff Sharkey497e4432011-06-14 17:27:29 -07002098 // skip writing empty policies
2099 if (policy == POLICY_NONE) continue;
2100
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002101 out.startTag(null, TAG_UID_POLICY);
2102 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002103 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002104 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002105 }
2106
2107 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002108
2109 // write all whitelists
2110 out.startTag(null, TAG_WHITELIST);
2111
Felipe Lemea9505cc2016-02-26 10:28:41 -08002112 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002113 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002114 for (int i = 0; i < size; i++) {
2115 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2116 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2117 writeIntAttribute(out, ATTR_UID, uid);
2118 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2119 }
2120
Felipe Lemeb85a6372016-01-14 16:16:16 -08002121 out.endTag(null, TAG_WHITELIST);
2122
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002123 out.endDocument();
2124
2125 mPolicyFile.finishWrite(fos);
2126 } catch (IOException e) {
2127 if (fos != null) {
2128 mPolicyFile.failWrite(fos);
2129 }
2130 }
2131 }
2132
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002133 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002134 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002135 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002136
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002137 if (!UserHandle.isApp(uid)) {
2138 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002139 }
Felipe Lemef0823852016-06-08 13:43:08 -07002140 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002141 final long token = Binder.clearCallingIdentity();
2142 try {
2143 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2144 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002145 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002146 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002147 }
2148 } finally {
2149 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002150 }
2151 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002152 }
2153
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002154 @Override
2155 public void addUidPolicy(int uid, int policy) {
2156 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002157
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002158 if (!UserHandle.isApp(uid)) {
2159 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2160 }
2161
Felipe Lemef0823852016-06-08 13:43:08 -07002162 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002163 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2164 policy |= oldPolicy;
2165 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002166 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002167 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002168 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002169 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002170 }
2171
2172 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002173 public void removeUidPolicy(int uid, int policy) {
2174 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2175
2176 if (!UserHandle.isApp(uid)) {
2177 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2178 }
2179
Felipe Lemef0823852016-06-08 13:43:08 -07002180 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002181 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2182 policy = oldPolicy & ~policy;
2183 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002184 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002185 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002186 }
2187 }
2188 }
2189
Felipe Lemef0823852016-06-08 13:43:08 -07002190 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2191 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002192
Felipe Leme57e3d312016-08-23 14:42:52 -07002193 final boolean notifyApp;
2194 if (!isUidValidForWhitelistRules(uid)) {
2195 notifyApp = false;
2196 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002197 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2198 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2199 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2200 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002201 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2202 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002203 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2204 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2205 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2206 if (LOGD)
2207 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2208 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2209 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002210 notifyApp = wasBlocked != isBlocked;
2211 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002212 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2213 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002214 }
2215
Felipe Lemef0823852016-06-08 13:43:08 -07002216 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002217 if (policy == POLICY_NONE) {
2218 mUidPolicy.delete(uid);
2219 } else {
2220 mUidPolicy.put(uid, policy);
2221 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002222
2223 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002224 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002225 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002226 synchronized (mNetworkPoliciesSecondLock) {
2227 writePolicyAL();
2228 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002229 }
2230 }
2231
2232 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002233 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002234 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2235
Felipe Lemef0823852016-06-08 13:43:08 -07002236 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002237 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002238 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002239 }
2240
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002241 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002242 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002243 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2244
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002245 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002246 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002247 for (int i = 0; i < mUidPolicy.size(); i++) {
2248 final int uid = mUidPolicy.keyAt(i);
2249 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002250 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2251 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002252 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002253 }
2254 }
2255 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002256 return uids;
2257 }
2258
2259 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002260 * Removes any persistable state associated with given {@link UserHandle}, persisting
2261 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002262 */
Felipe Lemef0823852016-06-08 13:43:08 -07002263 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002264
Sudheer Shanka352dc572017-09-22 17:09:38 -07002265 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002266 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002267
Felipe Lemea110eec2016-04-29 09:58:06 -07002268 // Remove entries from revoked default restricted background UID whitelist
2269 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2270 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2271 if (UserHandle.getUserId(uid) == userId) {
2272 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002273 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002274 }
2275 }
2276
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002277 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002278 int[] uids = new int[0];
2279 for (int i = 0; i < mUidPolicy.size(); i++) {
2280 final int uid = mUidPolicy.keyAt(i);
2281 if (UserHandle.getUserId(uid) == userId) {
2282 uids = appendInt(uids, uid);
2283 }
2284 }
2285
2286 if (uids.length > 0) {
2287 for (int uid : uids) {
2288 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002289 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002290 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002291 }
Felipe Lemef0823852016-06-08 13:43:08 -07002292 synchronized (mNetworkPoliciesSecondLock) {
2293 updateRulesForGlobalChangeAL(true);
2294 if (writePolicy && changed) {
2295 writePolicyAL();
2296 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002297 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002298 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002299 }
2300
2301 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002302 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002303 // TODO: create permission for observing network policy
2304 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002305 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002306 }
2307
2308 @Override
2309 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002310 // TODO: create permission for observing network policy
2311 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002312 mListeners.unregister(listener);
2313 }
2314
Jeff Sharkey1b861272011-05-22 00:34:52 -07002315 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002316 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002317 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2318
Felipe Leme6a05eee2016-02-19 14:43:51 -08002319 final long token = Binder.clearCallingIdentity();
2320 try {
2321 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002322 synchronized (mUidRulesFirstLock) {
2323 synchronized (mNetworkPoliciesSecondLock) {
2324 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002325 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002326 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002327 }
2328 } finally {
2329 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002330 }
2331 }
2332
Hugo Benichi446c9c92017-04-10 09:41:10 +09002333 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002334 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002335 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2336 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002337 }
2338
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002339 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002340 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002341 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002342 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002343 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2344 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2345 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002346 } catch (SecurityException e) {
2347 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002348
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002349 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2350 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2351 return new NetworkPolicy[0];
2352 }
Svet Ganov16a16892015-04-16 10:32:04 -07002353 }
2354
Felipe Lemef0823852016-06-08 13:43:08 -07002355 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002356 final int size = mNetworkPolicy.size();
2357 final NetworkPolicy[] policies = new NetworkPolicy[size];
2358 for (int i = 0; i < size; i++) {
2359 policies[i] = mNetworkPolicy.valueAt(i);
2360 }
2361 return policies;
2362 }
2363 }
2364
Felipe Lemef0823852016-06-08 13:43:08 -07002365 private void normalizePoliciesNL() {
2366 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002367 }
2368
Felipe Lemef0823852016-06-08 13:43:08 -07002369 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002370 final TelephonyManager tele = TelephonyManager.from(mContext);
2371 final String[] merged = tele.getMergedSubscriberIds();
2372
2373 mNetworkPolicy.clear();
2374 for (NetworkPolicy policy : policies) {
2375 // When two normalized templates conflict, prefer the most
2376 // restrictive policy
2377 policy.template = NetworkTemplate.normalize(policy.template, merged);
2378 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2379 if (existing == null || existing.compareTo(policy) > 0) {
2380 if (existing != null) {
2381 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2382 }
2383 mNetworkPolicy.put(policy.template, policy);
2384 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002385 }
2386 }
2387
2388 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002389 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002390 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002391
2392 final long token = Binder.clearCallingIdentity();
2393 try {
2394 performSnooze(template, TYPE_LIMIT);
2395 } finally {
2396 Binder.restoreCallingIdentity(token);
2397 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002398 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002399
Dianne Hackborn497175b2014-07-01 12:56:08 -07002400 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002401 maybeRefreshTrustedTime();
2402 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002403 synchronized (mUidRulesFirstLock) {
2404 synchronized (mNetworkPoliciesSecondLock) {
2405 // find and snooze local policy that matches
2406 final NetworkPolicy policy = mNetworkPolicy.get(template);
2407 if (policy == null) {
2408 throw new IllegalArgumentException("unable to find policy for " + template);
2409 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002410
Felipe Lemef0823852016-06-08 13:43:08 -07002411 switch (type) {
2412 case TYPE_WARNING:
2413 policy.lastWarningSnooze = currentTime;
2414 break;
2415 case TYPE_LIMIT:
2416 policy.lastLimitSnooze = currentTime;
2417 break;
2418 default:
2419 throw new IllegalArgumentException("unexpected type");
2420 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002421
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002422 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002423 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002424 }
2425 }
2426
2427 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002428 public void onTetheringChanged(String iface, boolean tethering) {
2429 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002430 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002431 if (mRestrictBackground && tethering) {
2432 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2433 setRestrictBackground(false);
2434 }
2435 }
2436 }
2437
2438 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002439 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002440 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002441 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002442 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2443 final long token = Binder.clearCallingIdentity();
2444 try {
2445 maybeRefreshTrustedTime();
2446 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002447 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002448 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002449 } finally {
2450 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002451 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002452 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002453 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002454 }
2455 }
2456
Felipe Lemef0823852016-06-08 13:43:08 -07002457 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002458 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002459 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002460 if (restrictBackground == mRestrictBackground) {
2461 // Ideally, UI should never allow this scenario...
2462 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002463 return;
2464 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002465 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2466 final boolean oldRestrictBackground = mRestrictBackground;
2467 mRestrictBackground = restrictBackground;
2468 // Must whitelist foreground apps before turning data saver mode on.
2469 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2470 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2471 updateRulesForRestrictBackgroundUL();
2472 try {
2473 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2474 Slog.e(TAG,
2475 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2476 mRestrictBackground = oldRestrictBackground;
2477 // TODO: if it knew the foreground apps (see TODO above), it could call
2478 // updateRulesForRestrictBackgroundUL() again to restore state.
2479 return;
2480 }
2481 } catch (RemoteException e) {
2482 // ignored; service lives in system_server
2483 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002484
Sudheer Shanka543339f2017-07-28 15:18:07 -07002485 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002486 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002487
2488 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2489 mRestrictBackgroundChangedInBsm = true;
2490 }
2491 synchronized (mNetworkPoliciesSecondLock) {
2492 updateNotificationsNL();
2493 writePolicyAL();
2494 }
2495 } finally {
2496 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002497 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002498 }
2499
2500 private void sendRestrictBackgroundChangedMsg() {
2501 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2502 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2503 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002504 }
2505
Felipe Lemeb85a6372016-01-14 16:16:16 -08002506 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002507 public int getRestrictBackgroundByCaller() {
2508 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2509 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002510
Felipe Lemef0823852016-06-08 13:43:08 -07002511 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002512 // Must clear identity because getUidPolicy() is restricted to system.
2513 final long token = Binder.clearCallingIdentity();
2514 final int policy;
2515 try {
2516 policy = getUidPolicy(uid);
2517 } finally {
2518 Binder.restoreCallingIdentity(token);
2519 }
2520 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2521 // App is blacklisted.
2522 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2523 }
Felipe Leme1b103232016-01-22 09:44:57 -08002524 if (!mRestrictBackground) {
2525 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2526 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002527 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002528 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2529 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2530 }
2531 }
2532
2533 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002534 public boolean getRestrictBackground() {
2535 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2536
Felipe Lemef0823852016-06-08 13:43:08 -07002537 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002538 return mRestrictBackground;
2539 }
2540 }
2541
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002542 @Override
2543 public void setDeviceIdleMode(boolean enabled) {
2544 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002545 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2546 try {
2547 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002548 if (mDeviceIdleMode == enabled) {
2549 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002550 }
Felipe Lemeea014392016-09-06 13:59:54 -07002551 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002552 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002553 if (mSystemReady) {
2554 // Device idle change means we need to rebuild rules for all
2555 // known apps, so do a global refresh.
2556 updateRulesForRestrictPowerUL();
2557 }
2558 }
2559 if (enabled) {
2560 EventLogTags.writeDeviceIdleOnPhase("net");
2561 } else {
2562 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002563 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002564 } finally {
2565 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002566 }
2567 }
2568
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002569 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002570 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2571 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002572 final long token = Binder.clearCallingIdentity();
2573 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002574 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2575 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2576 for (WifiConfiguration config : configs) {
2577 if (Objects.equals(resolveNetworkId(config), networkId)) {
2578 config.meteredOverride = meteredOverride;
2579 wm.updateNetwork(config);
2580 }
2581 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002582 } finally {
2583 Binder.restoreCallingIdentity(token);
2584 }
2585 }
2586
Jeff Sharkey46645002011-07-27 21:11:21 -07002587 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002588 @Deprecated
2589 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2590 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2591 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2592 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002593 }
2594
Jeff Sharkey53313d72017-07-13 16:47:32 -06002595 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2596 // Verify they're not lying about package name
2597 mAppOps.checkPackage(callingUid, callingPackage);
2598
Jeff Sharkey53313d72017-07-13 16:47:32 -06002599 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002600 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002601 final long token = Binder.clearCallingIdentity();
2602 try {
2603 si = mContext.getSystemService(SubscriptionManager.class)
2604 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002605 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002606 } finally {
2607 Binder.restoreCallingIdentity(token);
2608 }
2609
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002610 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002611 if (si != null) {
2612 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2613 return;
2614 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002615 }
2616
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002617 // Second check: has the CarrierService delegated access?
2618 if (config != null) {
2619 final String overridePackage = config
2620 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2621 if (!TextUtils.isEmpty(overridePackage)
2622 && Objects.equals(overridePackage, callingPackage)) {
2623 return;
2624 }
2625 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002626
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002627 // Third check: is caller the fallback/default CarrierService?
2628 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2629 if (!TextUtils.isEmpty(defaultPackage)
2630 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002631 return;
2632 }
2633
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002634 // Final check: does the caller hold a permission?
2635 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002636 }
2637
2638 @Override
2639 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2640 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2641
Jeff Sharkey53313d72017-07-13 16:47:32 -06002642 final String fake = SystemProperties.get("fw.fake_plan");
2643 if (!TextUtils.isEmpty(fake)) {
2644 final List<SubscriptionPlan> plans = new ArrayList<>();
2645 if ("month_hard".equals(fake)) {
2646 plans.add(SubscriptionPlan.Builder
2647 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2648 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002649 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2650 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2651 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2652 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2653 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002654 plans.add(SubscriptionPlan.Builder
2655 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2656 .setTitle("G-Mobile Happy")
2657 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2658 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2659 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2660 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2661 .build());
2662 plans.add(SubscriptionPlan.Builder
2663 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2664 .setTitle("G-Mobile, Charged after limit")
2665 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2666 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2667 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2668 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2669 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002670 } else if ("month_soft".equals(fake)) {
2671 plans.add(SubscriptionPlan.Builder
2672 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2673 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2674 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2675 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002676 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2677 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2678 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2679 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2680 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002681 plans.add(SubscriptionPlan.Builder
2682 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2683 .setTitle("G-Mobile, Throttled after limit")
2684 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2685 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2686 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2687 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2688 .build());
2689 plans.add(SubscriptionPlan.Builder
2690 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2691 .setTitle("G-Mobile, No data connection after limit")
2692 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2693 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2694 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2695 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2696 .build());
2697
Jeff Sharkey53313d72017-07-13 16:47:32 -06002698 } else if ("month_none".equals(fake)) {
2699 plans.add(SubscriptionPlan.Builder
2700 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2701 .setTitle("G-Mobile")
2702 .build());
2703 } else if ("prepaid".equals(fake)) {
2704 plans.add(SubscriptionPlan.Builder
2705 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2706 ZonedDateTime.now().plusDays(10))
2707 .setTitle("G-Mobile")
2708 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2709 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2710 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2711 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2712 .build());
2713 } else if ("prepaid_crazy".equals(fake)) {
2714 plans.add(SubscriptionPlan.Builder
2715 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2716 ZonedDateTime.now().plusDays(10))
2717 .setTitle("G-Mobile Anytime")
2718 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2719 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2720 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2721 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2722 .build());
2723 plans.add(SubscriptionPlan.Builder
2724 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2725 ZonedDateTime.now().plusDays(20))
2726 .setTitle("G-Mobile Nickel Nights")
2727 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002728 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2729 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002730 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2731 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2732 .build());
2733 plans.add(SubscriptionPlan.Builder
2734 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2735 ZonedDateTime.now().plusDays(20))
2736 .setTitle("G-Mobile Bonus 3G")
2737 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002738 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002739 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2740 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2741 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2742 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002743 } else if ("unlimited".equals(fake)) {
2744 plans.add(SubscriptionPlan.Builder
2745 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2746 ZonedDateTime.now().plusDays(10))
2747 .setTitle("G-Mobile Awesome")
2748 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2749 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2750 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2751 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2752 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002753 }
2754 return plans.toArray(new SubscriptionPlan[plans.size()]);
2755 }
2756
Jeff Sharkey4635f102017-09-01 11:27:13 -06002757 synchronized (mNetworkPoliciesSecondLock) {
2758 // Only give out plan details to the package that defined them,
2759 // so that we don't risk leaking plans between apps. We always
2760 // let in core system components (like the Settings app).
2761 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2762 if (Objects.equals(ownerPackage, callingPackage)
2763 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2764 return mSubscriptionPlans.get(subId);
2765 } else {
2766 Log.w(TAG, "Not returning plans because caller " + callingPackage
2767 + " doesn't match owner " + ownerPackage);
2768 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002769 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002770 }
2771 }
2772
2773 @Override
2774 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2775 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2776
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002777 for (SubscriptionPlan plan : plans) {
2778 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002779 }
2780
2781 final long token = Binder.clearCallingIdentity();
2782 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002783 maybeRefreshTrustedTime();
2784 synchronized (mUidRulesFirstLock) {
2785 synchronized (mNetworkPoliciesSecondLock) {
2786 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002787 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002788
2789 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
2790 .getSubscriberId(subId);
2791 ensureActiveMobilePolicyAL(subId, subscriberId);
2792 maybeUpdateMobilePolicyCycleAL(subId);
2793 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002794 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002795 }
2796 } finally {
2797 Binder.restoreCallingIdentity(token);
2798 }
2799 }
2800
2801 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07002802 public String getSubscriptionPlansOwner(int subId) {
2803 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
2804 throw new SecurityException();
2805 }
2806
2807 synchronized (mNetworkPoliciesSecondLock) {
2808 return mSubscriptionPlansOwner.get(subId);
2809 }
2810 }
2811
2812 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002813 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002814 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002815
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002816 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2817
Dianne Hackborn497175b2014-07-01 12:56:08 -07002818 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002819 for (String arg : args) {
2820 argSet.add(arg);
2821 }
2822
Felipe Lemef0823852016-06-08 13:43:08 -07002823 synchronized (mUidRulesFirstLock) {
2824 synchronized (mNetworkPoliciesSecondLock) {
2825 if (argSet.contains("--unsnooze")) {
2826 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2827 mNetworkPolicy.valueAt(i).clearSnooze();
2828 }
2829
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002830 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002831
2832 fout.println("Cleared snooze timestamps");
2833 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002834 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002835
Felipe Lemef0823852016-06-08 13:43:08 -07002836 fout.print("System ready: "); fout.println(mSystemReady);
2837 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2838 fout.print("Restrict power: "); fout.println(mRestrictPower);
2839 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002840 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2841
2842 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07002843 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002844 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002845 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2846 fout.println(mNetworkPolicy.valueAt(i).toString());
2847 }
2848 fout.decreaseIndent();
2849
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002850 fout.println();
2851 fout.println("Subscription plans:");
2852 fout.increaseIndent();
2853 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2854 final int subId = mSubscriptionPlans.keyAt(i);
2855 fout.println("Subscriber ID " + subId + ":");
2856 fout.increaseIndent();
2857 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2858 if (!ArrayUtils.isEmpty(plans)) {
2859 for (SubscriptionPlan plan : plans) {
2860 fout.println(plan);
2861 }
2862 }
2863 fout.decreaseIndent();
2864 }
2865 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002866
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002867 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07002868 fout.println("Policy for UIDs:");
2869 fout.increaseIndent();
2870 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002871 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002872 final int uid = mUidPolicy.keyAt(i);
2873 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002874 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002875 fout.print(uid);
2876 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002877 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002878 fout.println();
2879 }
2880 fout.decreaseIndent();
2881
2882 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2883 if (size > 0) {
2884 fout.println("Power save whitelist (except idle) app ids:");
2885 fout.increaseIndent();
2886 for (int i = 0; i < size; i++) {
2887 fout.print("UID=");
2888 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2889 fout.print(": ");
2890 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2891 fout.println();
2892 }
2893 fout.decreaseIndent();
2894 }
2895
2896 size = mPowerSaveWhitelistAppIds.size();
2897 if (size > 0) {
2898 fout.println("Power save whitelist app ids:");
2899 fout.increaseIndent();
2900 for (int i = 0; i < size; i++) {
2901 fout.print("UID=");
2902 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2903 fout.print(": ");
2904 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2905 fout.println();
2906 }
2907 fout.decreaseIndent();
2908 }
2909
Felipe Lemef0823852016-06-08 13:43:08 -07002910 size = mDefaultRestrictBackgroundWhitelistUids.size();
2911 if (size > 0) {
2912 fout.println("Default restrict background whitelist uids:");
2913 fout.increaseIndent();
2914 for (int i = 0; i < size; i++) {
2915 fout.print("UID=");
2916 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2917 fout.println();
2918 }
2919 fout.decreaseIndent();
2920 }
2921
2922 size = mRestrictBackgroundWhitelistRevokedUids.size();
2923 if (size > 0) {
2924 fout.println("Default restrict background whitelist uids revoked by users:");
2925 fout.increaseIndent();
2926 for (int i = 0; i < size; i++) {
2927 fout.print("UID=");
2928 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2929 fout.println();
2930 }
2931 fout.decreaseIndent();
2932 }
2933
2934 final SparseBooleanArray knownUids = new SparseBooleanArray();
2935 collectKeys(mUidState, knownUids);
2936 collectKeys(mUidRules, knownUids);
2937
2938 fout.println("Status for all known UIDs:");
2939 fout.increaseIndent();
2940 size = knownUids.size();
2941 for (int i = 0; i < size; i++) {
2942 final int uid = knownUids.keyAt(i);
2943 fout.print("UID=");
2944 fout.print(uid);
2945
2946 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2947 fout.print(" state=");
2948 fout.print(state);
2949 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2950 fout.print(" (fg)");
2951 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08002952 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07002953 ? " (fg svc)" : " (bg)");
2954 }
2955
2956 final int uidRules = mUidRules.get(uid, RULE_NONE);
2957 fout.print(" rules=");
2958 fout.print(uidRulesToString(uidRules));
2959 fout.println();
2960 }
2961 fout.decreaseIndent();
2962
2963 fout.println("Status for just UIDs with rules:");
2964 fout.increaseIndent();
2965 size = mUidRules.size();
2966 for (int i = 0; i < size; i++) {
2967 final int uid = mUidRules.keyAt(i);
2968 fout.print("UID=");
2969 fout.print(uid);
2970 final int uidRules = mUidRules.get(uid, RULE_NONE);
2971 fout.print(" rules=");
2972 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002973 fout.println();
2974 }
2975 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08002976
Sudheer Shanka352dc572017-09-22 17:09:38 -07002977 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002978 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002979 }
2980 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002981
2982 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002983 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002984 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002985 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002986 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002987 }
2988
2989 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002990 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002991 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2992
Felipe Lemef0823852016-06-08 13:43:08 -07002993 synchronized (mUidRulesFirstLock) {
2994 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002995 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002996 }
2997
Felipe Lemef0823852016-06-08 13:43:08 -07002998 private boolean isUidForegroundUL(int uid) {
2999 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07003000 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
3001 }
3002
Felipe Lemef0823852016-06-08 13:43:08 -07003003 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003004 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003005 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003006 }
3007
Felipe Lemef0823852016-06-08 13:43:08 -07003008 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003009 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3010 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3011 }
3012
Felipe Lemef0823852016-06-08 13:43:08 -07003013 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003014 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07003015 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003016 }
3017
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003018 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003019 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003020 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3021 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003022 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003023 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003024 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3025 try {
3026 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3027 if (oldUidState != uidState) {
3028 // state changed, push updated rules
3029 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003030 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3031 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3032 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003033 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003034 if (mDeviceIdleMode) {
3035 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003036 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003037 if (mRestrictPower) {
3038 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003039 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003040 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003041 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003042 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003043 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003044 } finally {
3045 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003046 }
3047 }
3048
Felipe Lemef0823852016-06-08 13:43:08 -07003049 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003050 final int index = mUidState.indexOfKey(uid);
3051 if (index >= 0) {
3052 final int oldUidState = mUidState.valueAt(index);
3053 mUidState.removeAt(index);
3054 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003055 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003056 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003057 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003058 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003059 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003060 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003061 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003062 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003063 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003064 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003065 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003066 }
3067 }
3068
Felipe Lemef28983d2016-03-25 12:18:23 -07003069 // adjust stats accounting based on foreground status
3070 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003071 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3072 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3073 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3074 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003075 try {
3076 mNetworkStats.setUidForeground(uid, uidForeground);
3077 } catch (RemoteException e) {
3078 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003079 } finally {
3080 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003081 }
3082 }
3083
Sudheer Shankac9d94072017-02-22 22:13:55 +00003084 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3085 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003086 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003087 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003088 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003089 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003090 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003091 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003092 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003093 }
3094
Felipe Lemef0823852016-06-08 13:43:08 -07003095 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003096 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3097 try {
3098 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3099 mUidFirewallPowerSaveRules);
3100 } finally {
3101 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3102 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003103 }
3104
Felipe Lemef0823852016-06-08 13:43:08 -07003105 void updateRuleForRestrictPowerUL(int uid) {
3106 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003107 }
3108
Felipe Lemef0823852016-06-08 13:43:08 -07003109 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003110 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3111 try {
3112 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3113 mUidFirewallDozableRules);
3114 } finally {
3115 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3116 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003117 }
3118
Felipe Lemef0823852016-06-08 13:43:08 -07003119 void updateRuleForDeviceIdleUL(int uid) {
3120 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003121 }
3122
Felipe Lemef28983d2016-03-25 12:18:23 -07003123 // NOTE: since both fw_dozable and fw_powersave uses the same map
3124 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003125 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003126 SparseIntArray rules) {
3127 if (enabled) {
3128 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003129 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003130 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003131 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003132 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003133 for (int ui = users.size() - 1; ui >= 0; ui--) {
3134 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003135 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3136 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3137 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3138 updateRulesForWhitelistedAppIds(uidRules,
3139 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003140 }
3141 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003142 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003143 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003144 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3145 }
3146 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003147 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003148 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003149 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003150 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003151 }
3152
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003153 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3154 final SparseBooleanArray whitelistedAppIds, int userId) {
3155 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3156 if (whitelistedAppIds.valueAt(i)) {
3157 final int appId = whitelistedAppIds.keyAt(i);
3158 final int uid = UserHandle.getUid(userId, appId);
3159 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3160 }
3161 }
3162 }
3163
3164 /**
3165 * @param deviceIdleMode if true then we don't consider
3166 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3167 * whitelisted.
3168 */
3169 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003170 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003171 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3172 || mPowerSaveWhitelistAppIds.get(appId);
3173 if (!deviceIdleMode) {
3174 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3175 }
3176 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003177 }
3178
Felipe Lemef28983d2016-03-25 12:18:23 -07003179 // NOTE: since both fw_dozable and fw_powersave uses the same map
3180 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003181 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003182 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003183 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3184 chain == FIREWALL_CHAIN_DOZABLE);
3185 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003186 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003187 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003188 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003189 }
3190 }
3191 }
3192
Felipe Lemef0823852016-06-08 13:43:08 -07003193 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003194 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3195 try {
3196 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3197 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003198
Felipe Leme873a83a2016-09-07 11:34:10 -07003199 // Fully update the app idle firewall chain.
3200 final List<UserInfo> users = mUserManager.getUsers();
3201 for (int ui = users.size() - 1; ui >= 0; ui--) {
3202 UserInfo user = users.get(ui);
3203 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3204 for (int uid : idleUids) {
3205 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3206 // quick check: if this uid doesn't have INTERNET permission, it
3207 // doesn't have network access anyway, so it is a waste to mess
3208 // with it here.
3209 if (hasInternetPermissions(uid)) {
3210 uidRules.put(uid, FIREWALL_RULE_DENY);
3211 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003212 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003213 }
3214 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003215
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003216 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003217 } finally {
3218 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3219 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003220 }
3221
Felipe Lemef0823852016-06-08 13:43:08 -07003222 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003223 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003224
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003225 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3226 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3227 }
3228 try {
3229 int appId = UserHandle.getAppId(uid);
3230 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3231 && !isUidForegroundOnRestrictPowerUL(uid)) {
3232 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3233 } else {
3234 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3235 }
3236 } finally {
3237 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003238 }
3239 }
3240
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003241 /**
3242 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3243 * changed.
3244 */
Felipe Lemef0823852016-06-08 13:43:08 -07003245 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003246 boolean paroled = mUsageStats.isAppIdleParoleOn();
3247 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003248 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003249
3250 int ruleCount = mUidFirewallStandbyRules.size();
3251 for (int i = 0; i < ruleCount; i++) {
3252 int uid = mUidFirewallStandbyRules.keyAt(i);
3253 int oldRules = mUidRules.get(uid);
3254 if (enableChain) {
3255 // Chain wasn't enabled before and the other power-related
3256 // chains are whitelists, so we can clear the
3257 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3258 // the effective rules result in blocking network access.
3259 oldRules &= MASK_METERED_NETWORKS;
3260 } else {
3261 // Skip if it had no restrictions to begin with
3262 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3263 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003264 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3265 if (newUidRules == RULE_NONE) {
3266 mUidRules.delete(uid);
3267 } else {
3268 mUidRules.put(uid, newUidRules);
3269 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003270 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003271 }
3272
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003273 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003274 * Update rules that might be changed by {@link #mRestrictBackground},
3275 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003276 */
Felipe Lemef0823852016-06-08 13:43:08 -07003277 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003278 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3279 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3280 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3281 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003282 try {
Felipe Leme09700462016-09-08 09:33:48 -07003283 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003284 updateRulesForRestrictPowerUL();
3285 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003286
Felipe Leme873a83a2016-09-07 11:34:10 -07003287 // If the set of restricted networks may have changed, re-evaluate those.
3288 if (restrictedNetworksChanged) {
3289 normalizePoliciesNL();
3290 updateNetworkRulesNL();
3291 }
3292 } finally {
3293 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003294 }
3295 }
3296
Felipe Leme09700462016-09-08 09:33:48 -07003297 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003298 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003299 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3300 try {
3301 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003302 updateRulesForPowerSaveUL();
3303 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3304 } finally {
3305 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3306 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003307 }
3308
Felipe Lemef0823852016-06-08 13:43:08 -07003309 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003310 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3311 try {
3312 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3313 } finally {
3314 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3315 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003316 }
3317
3318 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3319 private static final int TYPE_RESTRICT_POWER = 2;
3320 @Retention(RetentionPolicy.SOURCE)
3321 @IntDef(flag = false, value = {
3322 TYPE_RESTRICT_BACKGROUND,
3323 TYPE_RESTRICT_POWER,
3324 })
3325 public @interface RestrictType {
3326 }
3327
3328 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003329 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003330 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3331 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3332 }
3333 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003334 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003335
3336 final PackageManager pm = mContext.getPackageManager();
3337 final List<UserInfo> users;
3338 final List<ApplicationInfo> apps;
3339
3340 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3341 try {
3342 users = mUserManager.getUsers();
3343 } finally {
3344 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3345 }
3346 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3347 try {
3348 apps = pm.getInstalledApplications(
3349 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3350 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3351 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3352 } finally {
3353 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3354 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003355
Felipe Leme873a83a2016-09-07 11:34:10 -07003356 final int usersSize = users.size();
3357 final int appsSize = apps.size();
3358 for (int i = 0; i < usersSize; i++) {
3359 final UserInfo user = users.get(i);
3360 for (int j = 0; j < appsSize; j++) {
3361 final ApplicationInfo app = apps.get(j);
3362 final int uid = UserHandle.getUid(user.id, app.uid);
3363 switch (type) {
3364 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003365 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003366 break;
3367 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003368 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003369 break;
3370 default:
3371 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3372 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003373 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003374 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003375 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003376 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003377 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003378 }
3379
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003380 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003381 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003382 final int numUsers = users.size();
3383 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003384 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003385 int uid = UserHandle.getUid(user.id, appId);
3386 // Update external firewall rules.
3387 updateRuleForAppIdleUL(uid);
3388 updateRuleForDeviceIdleUL(uid);
3389 updateRuleForRestrictPowerUL(uid);
3390 // Update internal rules.
3391 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003392 }
3393 }
3394
Felipe Leme70c57c22016-03-29 10:45:13 -07003395 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3396 // methods below could be merged into a isUidValidForRules() method.
3397 private boolean isUidValidForBlacklistRules(int uid) {
3398 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003399 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003400 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003401 return true;
3402 }
3403
3404 return false;
3405 }
3406
Felipe Leme70c57c22016-03-29 10:45:13 -07003407 private boolean isUidValidForWhitelistRules(int uid) {
3408 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3409 }
3410
Amith Yamasani15e472352015-04-24 19:06:07 -07003411 private boolean isUidIdle(int uid) {
3412 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3413 final int userId = UserHandle.getUserId(uid);
3414
songjinshi0655edd2016-05-18 19:55:32 +08003415 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003416 for (String packageName : packages) {
3417 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3418 return false;
3419 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003420 }
3421 }
3422 return true;
3423 }
3424
3425 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003426 * Checks if an uid has INTERNET permissions.
3427 * <p>
3428 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003429 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003430 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003431 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003432 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003433 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003434 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003435 }
3436 } catch (RemoteException e) {
3437 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003438 return true;
3439 }
3440
3441 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003442 * Clears all state - internal and external - associated with an UID.
3443 */
3444 private void onUidDeletedUL(int uid) {
3445 // First cleanup in-memory state synchronously...
3446 mUidRules.delete(uid);
3447 mUidPolicy.delete(uid);
3448 mUidFirewallStandbyRules.delete(uid);
3449 mUidFirewallDozableRules.delete(uid);
3450 mUidFirewallPowerSaveRules.delete(uid);
3451 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3452 mPowerSaveWhitelistAppIds.delete(uid);
3453 mPowerSaveTempWhitelistAppIds.delete(uid);
3454
3455 // ...then update iptables asynchronously.
3456 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3457 }
3458
3459 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003460 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003461 *
Felipe Leme781ba142016-05-09 16:24:48 -07003462 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003463 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003464 * <li>Doze mode
3465 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003466 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003467 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003468 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003469 *
3470 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003471 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003472 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003473 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003474 updateRuleForDeviceIdleUL(uid);
3475 updateRuleForAppIdleUL(uid);
3476 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003477
3478 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003479 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003480
3481 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003482 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003483 }
3484
Felipe Leme70c57c22016-03-29 10:45:13 -07003485 /**
3486 * Applies network rules to bandwidth controllers based on process state and user-defined
3487 * restrictions (blacklist / whitelist).
3488 *
3489 * <p>
3490 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3491 * networks:
3492 * <ul>
3493 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3494 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3495 * also blacklisted.
3496 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3497 * no UIDs other those whitelisted will have access.
3498 * <ul>
3499 *
3500 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3501 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3502 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3503 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003504 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003505 * {@link INetworkManagementService}, but this method should also be called in events (like
3506 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3507 * following rules should also be applied:
3508 *
3509 * <ul>
3510 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3511 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3512 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3513 * {@code bw_penalty_box}.
3514 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3515 * </ul>
3516 *
3517 * <p>For optimization, the rules are only applied on user apps that have internet access
3518 * permission, since there is no need to change the {@code iptables} rule if the app does not
3519 * have permission to use the internet.
3520 *
3521 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003522 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003523 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003524 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003525 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3526 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3527 "updateRulesForDataUsageRestrictionsUL: " + uid);
3528 }
3529 try {
3530 updateRulesForDataUsageRestrictionsULInner(uid);
3531 } finally {
3532 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3533 }
3534 }
3535
3536 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003537 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003538 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003539 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003540 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003541
Dianne Hackborn497175b2014-07-01 12:56:08 -07003542 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003543 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003544 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003545
Felipe Leme781ba142016-05-09 16:24:48 -07003546 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003547 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003548 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3549 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003550
Felipe Leme70c57c22016-03-29 10:45:13 -07003551 // First step: define the new rule based on user restrictions and foreground state.
3552 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003553 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3554 newRule = RULE_TEMPORARY_ALLOW_METERED;
3555 } else if (isWhitelisted) {
3556 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003557 }
3558 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003559 if (isBlacklisted) {
3560 newRule = RULE_REJECT_METERED;
3561 } else if (mRestrictBackground && isWhitelisted) {
3562 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003563 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003564 }
Felipe Leme781ba142016-05-09 16:24:48 -07003565 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003566
Felipe Lemef28983d2016-03-25 12:18:23 -07003567 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003568 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003569 + ": isForeground=" +isForeground
3570 + ", isBlacklisted=" + isBlacklisted
3571 + ", isWhitelisted=" + isWhitelisted
3572 + ", oldRule=" + uidRulesToString(oldRule)
3573 + ", newRule=" + uidRulesToString(newRule)
3574 + ", newUidRules=" + uidRulesToString(newUidRules)
3575 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003576 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003577
Felipe Leme46c4fc32016-05-04 09:21:43 -07003578 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003579 mUidRules.delete(uid);
3580 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003581 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003582 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003583
Felipe Leme70c57c22016-03-29 10:45:13 -07003584 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003585 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003586 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003587 // Temporarily whitelist foreground app, removing from blacklist if necessary
3588 // (since bw_penalty_box prevails over bw_happy_box).
3589
3590 setMeteredNetworkWhitelist(uid, true);
3591 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3592 // but ideally it should be just:
3593 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003594 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003595 setMeteredNetworkBlacklist(uid, false);
3596 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003597 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003598 // Remove temporary whitelist from app that is not on foreground anymore.
3599
3600 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3601 // but ideally they should be just:
3602 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3603 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003604 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003605 setMeteredNetworkWhitelist(uid, false);
3606 }
Felipe Leme781ba142016-05-09 16:24:48 -07003607 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003608 setMeteredNetworkBlacklist(uid, true);
3609 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003610 } else if (hasRule(newRule, RULE_REJECT_METERED)
3611 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003612 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003613 setMeteredNetworkBlacklist(uid, isBlacklisted);
Hugo Benichi2966c182017-03-28 17:17:13 +09003614 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003615 // Since blacklist prevails over whitelist, we need to handle the special case
3616 // where app is whitelisted and blacklisted at the same time (although such
3617 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003618 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003619 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003620 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3621 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003622 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003623 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003624 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003625 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003626 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3627 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003628 + ", whitelisted=" + isWhitelisted
3629 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003630 + ", newRule=" + uidRulesToString(newUidRules)
3631 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003632 }
Felipe Leme781ba142016-05-09 16:24:48 -07003633
Sudheer Shankac9d94072017-02-22 22:13:55 +00003634 // Dispatch changed rule to existing listeners.
3635 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003636 }
3637 }
3638
3639 /**
3640 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3641 * listeners in case of change.
3642 * <p>
3643 * There are 3 power-related rules that affects whether an app has background access on
3644 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3645 * restriction, it's added to the equivalent firewall chain:
3646 * <ul>
3647 * <li>App is idle: {@code fw_standby} firewall chain.
3648 * <li>Device is idle: {@code fw_dozable} firewall chain.
3649 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3650 * </ul>
3651 * <p>
3652 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3653 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3654 * <p>
3655 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3656 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003657 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003658 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3659
Sudheer Shankac9d94072017-02-22 22:13:55 +00003660 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003661
Sudheer Shankac9d94072017-02-22 22:13:55 +00003662 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003663 mUidRules.delete(uid);
3664 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003665 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003666 }
3667 }
3668
3669 /**
3670 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3671 *
3672 * @param uid the uid of the app to update rules for
3673 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3674 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3675 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003676 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003677 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003678 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003679 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3680 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3681 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3682 + (paroled ? "P" : "-"));
3683 }
3684 try {
3685 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3686 } finally {
3687 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3688 }
3689 }
3690
3691 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003692 if (!isUidValidForBlacklistRules(uid)) {
3693 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003694 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003695 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003696
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003697 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003698 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003699 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003700
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003701 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003702 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3703 int newRule = RULE_NONE;
3704
3705 // First step: define the new rule based on user restrictions and foreground state.
3706
3707 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3708 // by considering the foreground and non-foreground states.
3709 if (isForeground) {
3710 if (restrictMode) {
3711 newRule = RULE_ALLOW_ALL;
3712 }
3713 } else if (restrictMode) {
3714 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3715 }
3716
3717 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3718
3719 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003720 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003721 + ", isIdle: " + isIdle
3722 + ", mRestrictPower: " + mRestrictPower
3723 + ", mDeviceIdleMode: " + mDeviceIdleMode
3724 + ", isForeground=" + isForeground
3725 + ", isWhitelisted=" + isWhitelisted
3726 + ", oldRule=" + uidRulesToString(oldRule)
3727 + ", newRule=" + uidRulesToString(newRule)
3728 + ", newUidRules=" + uidRulesToString(newUidRules)
3729 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3730 }
3731
Felipe Leme781ba142016-05-09 16:24:48 -07003732 // Second step: notify listeners if state changed.
3733 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003734 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003735 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003736 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003737 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3738 } else {
3739 // All scenarios should have been covered above
3740 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3741 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003742 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003743 + ", newRule=" + uidRulesToString(newUidRules)
3744 + ", oldRule=" + uidRulesToString(oldUidRules));
3745 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003746 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003747 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003748
Sudheer Shankac9d94072017-02-22 22:13:55 +00003749 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003750 }
3751
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003752 private class AppIdleStateChangeListener
3753 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3754
3755 @Override
Amith Yamasani84cd7b72017-11-07 13:59:37 -08003756 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003757 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003758 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3759 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07003760 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07003761 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003762 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003763 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003764 }
3765 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003766 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003767 }
3768
3769 @Override
3770 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003771 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07003772 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07003773 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003774 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003775 }
3776 }
3777
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003778 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3779 if (listener != null) {
3780 try {
3781 listener.onUidRulesChanged(uid, uidRules);
3782 } catch (RemoteException ignored) {
3783 }
3784 }
3785 }
3786
3787 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3788 String[] meteredIfaces) {
3789 if (listener != null) {
3790 try {
3791 listener.onMeteredIfacesChanged(meteredIfaces);
3792 } catch (RemoteException ignored) {
3793 }
3794 }
3795 }
3796
3797 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3798 boolean restrictBackground) {
3799 if (listener != null) {
3800 try {
3801 listener.onRestrictBackgroundChanged(restrictBackground);
3802 } catch (RemoteException ignored) {
3803 }
3804 }
3805 }
3806
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003807 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3808 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003809 if (listener != null) {
3810 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003811 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003812 } catch (RemoteException ignored) {
3813 }
3814 }
3815 }
3816
Makoto Onuki8e777332017-03-28 11:25:47 -07003817 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003818 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003819 public boolean handleMessage(Message msg) {
3820 switch (msg.what) {
3821 case MSG_RULES_CHANGED: {
3822 final int uid = msg.arg1;
3823 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003824 final int length = mListeners.beginBroadcast();
3825 for (int i = 0; i < length; i++) {
3826 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3827 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003828 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003829 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003830 return true;
3831 }
3832 case MSG_METERED_IFACES_CHANGED: {
3833 final String[] meteredIfaces = (String[]) msg.obj;
3834 final int length = mListeners.beginBroadcast();
3835 for (int i = 0; i < length; i++) {
3836 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003837 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003838 }
3839 mListeners.finishBroadcast();
3840 return true;
3841 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003842 case MSG_LIMIT_REACHED: {
3843 final String iface = (String) msg.obj;
3844
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003845 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003846 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003847 if (mMeteredIfaces.contains(iface)) {
3848 try {
3849 // force stats update to make sure we have
3850 // numbers that caused alert to trigger.
3851 mNetworkStats.forceUpdate();
3852 } catch (RemoteException e) {
3853 // ignored; service lives in system_server
3854 }
3855
Felipe Lemef0823852016-06-08 13:43:08 -07003856 updateNetworkEnabledNL();
3857 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003858 }
3859 }
3860 return true;
3861 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003862 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3863 final boolean restrictBackground = msg.arg1 != 0;
3864 final int length = mListeners.beginBroadcast();
3865 for (int i = 0; i < length; i++) {
3866 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003867 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003868 }
3869 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003870 final Intent intent =
3871 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3872 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3873 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3874 return true;
3875 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003876 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003877 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003878 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003879 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003880 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07003881 final int length = mListeners.beginBroadcast();
3882 for (int i = 0; i < length; i++) {
3883 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003884 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003885 }
3886 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003887 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3888 if (notifyApp.booleanValue()) {
3889 broadcastRestrictBackgroundChanged(uid, notifyApp);
3890 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003891 return true;
3892 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003893 case MSG_ADVISE_PERSIST_THRESHOLD: {
3894 final long lowestRule = (Long) msg.obj;
3895 try {
3896 // make sure stats are recorded frequently enough; we aim
3897 // for 2MB threshold for 2GB/month rules.
3898 final long persistThreshold = lowestRule / 1000;
3899 mNetworkStats.advisePersistThreshold(persistThreshold);
3900 } catch (RemoteException e) {
3901 // ignored; service lives in system_server
3902 }
3903 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003904 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003905 case MSG_UPDATE_INTERFACE_QUOTA: {
3906 removeInterfaceQuota((String) msg.obj);
3907 // int params need to be stitched back into a long
3908 setInterfaceQuota((String) msg.obj,
3909 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3910 return true;
3911 }
3912 case MSG_REMOVE_INTERFACE_QUOTA: {
3913 removeInterfaceQuota((String) msg.obj);
3914 return true;
3915 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003916 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3917 resetUidFirewallRules(msg.arg1);
3918 return true;
3919 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003920 default: {
3921 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003922 }
3923 }
3924 }
Makoto Onuki8e777332017-03-28 11:25:47 -07003925 };
3926
3927 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
3928 @Override
3929 public boolean handleMessage(Message msg) {
3930 switch (msg.what) {
3931 case UID_MSG_STATE_CHANGED: {
3932 final int uid = msg.arg1;
3933 final int procState = msg.arg2;
3934 final long procStateSeq = (Long) msg.obj;
3935
3936 handleUidChanged(uid, procState, procStateSeq);
3937 return true;
3938 }
3939 case UID_MSG_GONE: {
3940 final int uid = msg.arg1;
3941 handleUidGone(uid);
3942 return true;
3943 }
3944 default: {
3945 return false;
3946 }
3947 }
3948 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003949
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003950 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003951
Makoto Onuki8e777332017-03-28 11:25:47 -07003952 void handleUidChanged(int uid, int procState, long procStateSeq) {
3953 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
3954 try {
3955 synchronized (mUidRulesFirstLock) {
3956 // We received a uid state change callback, add it to the history so that it
3957 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07003958 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07003959 // Now update the network policy rules as per the updated uid state.
3960 updateUidStateUL(uid, procState);
3961 // Updating the network rules is done, so notify AMS about this.
3962 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
3963 }
3964 } finally {
3965 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3966 }
3967 }
3968
3969 void handleUidGone(int uid) {
3970 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
3971 try {
3972 synchronized (mUidRulesFirstLock) {
3973 removeUidStateUL(uid);
3974 }
3975 } finally {
3976 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3977 }
3978 }
3979
Felipe Leme57e3d312016-08-23 14:42:52 -07003980 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3981 final PackageManager pm = mContext.getPackageManager();
3982 final String[] packages = pm.getPackagesForUid(uid);
3983 if (packages != null) {
3984 final int userId = UserHandle.getUserId(uid);
3985 for (String packageName : packages) {
3986 final Intent intent =
3987 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3988 intent.setPackage(packageName);
3989 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3990 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3991 }
3992 }
3993 }
3994
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06003995 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
3996 // long quotaBytes split up into two ints to fit in message
3997 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
3998 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
3999 }
4000
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004001 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004002 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004003 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004004 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004005 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004006 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004007 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004008 }
4009 }
4010
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004011 private void removeInterfaceQuotaAsync(String iface) {
4012 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4013 }
4014
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004015 private void removeInterfaceQuota(String iface) {
4016 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004017 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004018 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004019 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004020 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004021 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004022 }
4023 }
4024
Felipe Leme70c57c22016-03-29 10:45:13 -07004025 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4026 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004027 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004028 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004029 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004030 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4031 } catch (RemoteException e) {
4032 // ignored; service lives in system_server
4033 }
4034 }
4035
4036 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4037 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4038 try {
4039 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4040 } catch (IllegalStateException e) {
4041 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004042 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004043 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004044 }
4045 }
4046
Felipe Lemebc853dd2016-09-08 13:26:55 -07004047 private static final int CHAIN_TOGGLE_NONE = 0;
4048 private static final int CHAIN_TOGGLE_ENABLE = 1;
4049 private static final int CHAIN_TOGGLE_DISABLE = 2;
4050 @Retention(RetentionPolicy.SOURCE)
4051 @IntDef(flag = false, value = {
4052 CHAIN_TOGGLE_NONE,
4053 CHAIN_TOGGLE_ENABLE,
4054 CHAIN_TOGGLE_DISABLE
4055 })
4056 public @interface ChainToggleType {
4057 }
4058
4059 /**
4060 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004061 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004062 *
4063 * @param chain firewall chain.
4064 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4065 * @param toggle whether the chain should be enabled, disabled, or not changed.
4066 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004067 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004068 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004069 if (uidRules != null) {
4070 setUidFirewallRulesUL(chain, uidRules);
4071 }
4072 if (toggle != CHAIN_TOGGLE_NONE) {
4073 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4074 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004075 }
4076
Amith Yamasani15e472352015-04-24 19:06:07 -07004077 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004078 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4079 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4080 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004081 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004082 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004083 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004084 int size = uidRules.size();
4085 int[] uids = new int[size];
4086 int[] rules = new int[size];
4087 for(int index = size - 1; index >= 0; --index) {
4088 uids[index] = uidRules.keyAt(index);
4089 rules[index] = uidRules.valueAt(index);
4090 }
4091 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004092 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004093 } catch (IllegalStateException e) {
4094 Log.wtf(TAG, "problem setting firewall uid rules", e);
4095 } catch (RemoteException e) {
4096 // ignored; service lives in system_server
4097 }
4098 }
4099
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004100 /**
4101 * Add or remove a uid to the firewall blacklist for all network ifaces.
4102 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004103 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004104 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4105 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4106 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004107 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004108 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004109 if (chain == FIREWALL_CHAIN_DOZABLE) {
4110 mUidFirewallDozableRules.put(uid, rule);
4111 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4112 mUidFirewallStandbyRules.put(uid, rule);
4113 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4114 mUidFirewallPowerSaveRules.put(uid, rule);
4115 }
4116
4117 try {
4118 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004119 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004120 } catch (IllegalStateException e) {
4121 Log.wtf(TAG, "problem setting firewall uid rules", e);
4122 } catch (RemoteException e) {
4123 // ignored; service lives in system_server
4124 }
4125 } finally {
4126 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004127 }
4128 }
4129
4130 /**
4131 * Add or remove a uid to the firewall blacklist for all network ifaces.
4132 */
Felipe Lemef0823852016-06-08 13:43:08 -07004133 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004134 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4135 mFirewallChainStates.get(chain) == enable) {
4136 // All is the same, nothing to do.
4137 return;
4138 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004139 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004140 try {
4141 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004142 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004143 } catch (IllegalStateException e) {
4144 Log.wtf(TAG, "problem enable firewall chain", e);
4145 } catch (RemoteException e) {
4146 // ignored; service lives in system_server
4147 }
4148 }
4149
Felipe Leme03e95e22016-09-09 09:25:31 -07004150 /**
4151 * Resets all firewall rules associated with an UID.
4152 */
4153 private void resetUidFirewallRules(int uid) {
4154 try {
4155 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4156 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4157 mNetworkManager
4158 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4159 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4160 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4161 } catch (IllegalStateException e) {
4162 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4163 } catch (RemoteException e) {
4164 // ignored; service lives in system_server
4165 }
4166 }
4167
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004168 private long getTotalBytes(NetworkTemplate template, long start, long end) {
4169 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004170 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004171 } catch (RuntimeException e) {
4172 Slog.w(TAG, "problem reading network stats: " + e);
4173 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004174 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004175 // ignored; service lives in system_server
4176 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004177 }
4178 }
4179
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004180 private boolean isBandwidthControlEnabled() {
4181 final long token = Binder.clearCallingIdentity();
4182 try {
4183 return mNetworkManager.isBandwidthControlEnabled();
4184 } catch (RemoteException e) {
4185 // ignored; service lives in system_server
4186 return false;
4187 } finally {
4188 Binder.restoreCallingIdentity(token);
4189 }
4190 }
4191
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004192 /**
4193 * Try refreshing {@link #mTime} when stale.
4194 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07004195 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004196 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004197 mTime.forceRefresh();
4198 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004199 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004200
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004201 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004202 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
4203 }
4204
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004205 private static Intent buildAllowBackgroundDataIntent() {
4206 return new Intent(ACTION_ALLOW_BACKGROUND);
4207 }
4208
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004209 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4210 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
4211 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4212 return intent;
4213 }
4214
Wei Liu546cb772016-07-21 16:19:01 -07004215 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004216 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004217 intent.setComponent(ComponentName.unflattenFromString(
4218 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004219 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4220 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4221 return intent;
4222 }
4223
Wei Liu546cb772016-07-21 16:19:01 -07004224 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004225 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004226 intent.setComponent(ComponentName.unflattenFromString(
4227 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004228 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4229 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4230 return intent;
4231 }
4232
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004233 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004234 public void addIdleHandler(IdleHandler handler) {
4235 mHandler.getLooper().getQueue().addIdleHandler(handler);
4236 }
4237
jackqdyulei29c82ab2017-03-10 14:09:16 -08004238 @VisibleForTesting
4239 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4240 mRestrictBackgroundPowerState = result;
4241
4242 boolean restrictBackground = result.batterySaverEnabled;
4243 boolean shouldInvokeRestrictBackground;
4244 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4245 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4246
4247 if (result.globalBatterySaverEnabled) {
4248 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4249 // turn it on.
4250 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4251 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4252 localRestrictBgChangedInBsm = false;
4253 } else {
4254 // Try to restore the restrictBackground if it doesn't change in bsm
4255 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4256 restrictBackground = mRestrictBackgroundBeforeBsm;
4257 }
4258
4259 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004260 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004261 }
4262
4263 // Change it at last so setRestrictBackground() won't affect this variable
4264 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4265 }
4266
Jeff Sharkey1b861272011-05-22 00:34:52 -07004267 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4268 final int size = source.size();
4269 for (int i = 0; i < size; i++) {
4270 target.put(source.keyAt(i), true);
4271 }
4272 }
4273
Stuart Scottf1fb3972015-04-02 18:00:02 -07004274 @Override
4275 public void factoryReset(String subscriber) {
4276 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4277
Stuart Scotte3e314d2015-04-20 14:07:45 -07004278 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4279 return;
4280 }
4281
Stuart Scottf1fb3972015-04-02 18:00:02 -07004282 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004283 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004284 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4285 for (NetworkPolicy policy : policies) {
4286 if (policy.template.equals(template)) {
4287 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4288 policy.inferred = false;
4289 policy.clearSnooze();
4290 }
4291 }
4292 setNetworkPolicies(policies);
4293
4294 // Turn restrict background data off
4295 setRestrictBackground(false);
4296
Stuart Scotte3e314d2015-04-20 14:07:45 -07004297 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4298 // Remove app's "restrict background data" flag
4299 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4300 setUidPolicy(uid, POLICY_NONE);
4301 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004302 }
4303 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004304
Sudheer Shankab8f23162017-08-04 13:30:10 -07004305 @Override
4306 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4307 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4308 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4309 }
4310
4311 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4312 final int uidRules;
4313 final boolean isBackgroundRestricted;
4314 synchronized (mUidRulesFirstLock) {
4315 uidRules = mUidRules.get(uid, RULE_NONE);
4316 isBackgroundRestricted = mRestrictBackground;
4317 }
4318 if (hasRule(uidRules, RULE_REJECT_ALL)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004319 mLogger.networkBlocked(uid, NTWK_BLOCKED_POWER);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004320 return true;
4321 }
4322 if (!isNetworkMetered) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004323 mLogger.networkBlocked(uid, NTWK_ALLOWED_NON_METERED);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004324 return false;
4325 }
4326 if (hasRule(uidRules, RULE_REJECT_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004327 mLogger.networkBlocked(uid, NTWK_BLOCKED_BLACKLIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004328 return true;
4329 }
4330 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004331 mLogger.networkBlocked(uid, NTWK_ALLOWED_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004332 return false;
4333 }
4334 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004335 mLogger.networkBlocked(uid, NTWK_ALLOWED_TMP_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004336 return false;
4337 }
4338 if (isBackgroundRestricted) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004339 mLogger.networkBlocked(uid, NTWK_BLOCKED_BG_RESTRICT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004340 return true;
4341 }
Sudheer Shanka352dc572017-09-22 17:09:38 -07004342 mLogger.networkBlocked(uid, NTWK_ALLOWED_DEFAULT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004343 return false;
4344 }
4345
Felipe Lemed17fda42016-04-29 11:12:45 -07004346 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4347
4348 @Override
4349 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004350 synchronized (mUidRulesFirstLock) {
4351 boolean changed = removeUserStateUL(userId, false);
4352 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004353 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004354 synchronized (mNetworkPoliciesSecondLock) {
4355 writePolicyAL();
4356 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004357 }
4358 }
4359 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004360
4361 /**
4362 * @return true if the given uid is restricted from doing networking on metered networks.
4363 */
4364 @Override
4365 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4366 final int uidRules;
4367 final boolean isBackgroundRestricted;
4368 synchronized (mUidRulesFirstLock) {
4369 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4370 isBackgroundRestricted = mRestrictBackground;
4371 }
4372 return isBackgroundRestricted
4373 && !hasRule(uidRules, RULE_ALLOW_METERED)
4374 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4375 }
4376
4377 /**
4378 * @return true if networking is blocked on the given interface for the given uid according
4379 * to current networking policies.
4380 */
4381 @Override
4382 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004383 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004384 synchronized (mNetworkPoliciesSecondLock) {
4385 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004386 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004387 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004388 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004389
4390 @Override
4391 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4392 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004393 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004394 if (added) {
4395 mPowerSaveTempWhitelistAppIds.put(appId, true);
4396 } else {
4397 mPowerSaveTempWhitelistAppIds.delete(appId);
4398 }
4399 updateRulesForTempWhitelistChangeUL(appId);
4400 }
4401 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004402 }
4403
4404 private static boolean hasRule(int uidRules, int rule) {
4405 return (uidRules & rule) != 0;
4406 }
4407
Chris Wren193ae6b2017-03-31 15:17:11 -04004408 private class NotificationId {
4409 private final String mTag;
4410 private final int mId;
4411
4412 NotificationId(NetworkPolicy policy, int type) {
4413 mTag = buildNotificationTag(policy, type);
4414 mId = type;
4415 }
4416
4417 @Override
4418 public boolean equals(Object o) {
4419 if (this == o) return true;
4420 if (!(o instanceof NotificationId)) return false;
4421 NotificationId that = (NotificationId) o;
4422 return Objects.equals(mTag, that.mTag);
4423 }
4424
4425 @Override
4426 public int hashCode() {
4427 return Objects.hash(mTag);
4428 }
4429
4430 /**
4431 * Build unique tag that identifies an active {@link NetworkPolicy}
4432 * notification of a specific type, like {@link #TYPE_LIMIT}.
4433 */
4434 private String buildNotificationTag(NetworkPolicy policy, int type) {
4435 return TAG + ":" + policy.template.hashCode() + ":" + type;
4436 }
4437
4438 public String getTag() {
4439 return mTag;
4440 }
4441
4442 public int getId() {
4443 return mId;
4444 }
4445 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004446}