blob: 9fd54ec4f7891004afbe741ee2ddf62670c866fd [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070021import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkeyb74799882017-07-28 16:55:41 -060022import static android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080032import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060035import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey64c96ec2017-08-30 16:28:26 -060036import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070037import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070038import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070039import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070040import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070041import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080042import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
44import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070045import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070046import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060047import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
48import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
Felipe Leme46b451f2016-08-19 08:46:17 -070049import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070050import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070051import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070053import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070054import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070055import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070056import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070057import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080058import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
59import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060060import static android.net.NetworkPolicyManager.resolveNetworkId;
Felipe Lemeb146f762016-08-19 09:52:16 -070061import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070062import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070063import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
64import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070065import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
66import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070067import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080068import static android.net.TrafficStats.MB_IN_BYTES;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070069import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070070import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060071import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070072import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080073
Jeff Sharkey854b2b12012-04-13 16:03:40 -070074import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070075import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070076import static com.android.internal.util.XmlUtils.readBooleanAttribute;
77import static com.android.internal.util.XmlUtils.readIntAttribute;
78import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060079import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070080import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
81import static com.android.internal.util.XmlUtils.writeIntAttribute;
82import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060083import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070084import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070085import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060086
Jeff Sharkey21c9c452011-06-07 12:26:43 -070087import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080088import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070089import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070090
Dianne Hackborn88e98df2015-03-23 13:29:14 -070091import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070092import android.annotation.IntDef;
Felipe Lemebc853dd2016-09-08 13:26:55 -070093import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -070094import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -080095import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070096import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070097import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070098import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070099import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700100import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700101import android.app.Notification;
102import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700103import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700104import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700105import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700106import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700107import android.content.Intent;
108import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700109import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700110import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700111import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700112import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700113import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700114import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700115import android.net.ConnectivityManager;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600116import android.net.ConnectivityManager.NetworkCallback;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700117import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700118import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700119import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700120import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700121import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700122import android.net.LinkProperties;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600123import android.net.Network;
124import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700125import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700126import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600127import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700128import android.net.NetworkQuotaInfo;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600129import android.net.NetworkRequest;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700130import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700131import android.net.NetworkTemplate;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600132import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700133import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700134import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700135import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700136import android.os.Environment;
137import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700138import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700139import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700140import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700141import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700142import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700143import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700144import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700145import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600146import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800147import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700148import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700149import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600150import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700151import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700152import android.os.ShellCallback;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600153import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700154import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700155import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700156import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700157import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100158import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700159import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600160import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800161import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600162import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700163import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400164import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700165import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700166import android.util.ArrayMap;
167import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700168import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700169import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700170import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700171import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600172import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700173import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600174import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700175import android.util.SparseBooleanArray;
176import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700177import android.util.TrustedTime;
178import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700179
Jeff Sharkey497e4432011-06-14 17:27:29 -0700180import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700181import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800182import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400183import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500184import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700185import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800186import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600187import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700188import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700189import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600190import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700191import com.android.server.DeviceIdleController;
192import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700193import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700194import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800195import com.android.server.SystemConfig;
jackqdyulei455e90a2017-02-09 15:29:16 -0800196import com.android.server.power.BatterySaverPolicy.ServiceType;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600197
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600198import libcore.io.IoUtils;
199
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700200import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700201import org.xmlpull.v1.XmlSerializer;
202
203import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700204import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700205import java.io.FileInputStream;
206import java.io.FileNotFoundException;
207import java.io.FileOutputStream;
208import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700209import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700210import java.lang.annotation.Retention;
211import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100212import java.nio.charset.StandardCharsets;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600213import java.time.ZoneId;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600214import java.time.ZonedDateTime;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700215import java.util.ArrayList;
216import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700217import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600218import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400219import java.util.Objects;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800220import java.util.concurrent.CountDownLatch;
221import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700222
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700223/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700224 * Service that maintains low-level network policy rules, using
225 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700226 * <p>
227 * Derives active rules by combining a given policy with other system status,
228 * and delivers to listeners, such as {@link ConnectivityManager}, for
229 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700230 *
231 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000232 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700233 * <ul>
234 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
235 * rules).
236 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
237 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000238 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
239 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700240 * </ul>
241 *
242 * <p>
243 * As such, methods that require synchronization have the following prefixes:
244 * <ul>
245 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
246 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000247 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
248 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700249 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700250 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700251public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800252 static final String TAG = "NetworkPolicy";
Hugo Benichi5d2f2b52017-04-07 08:53:25 +0900253 private static final boolean LOGD = false;
254 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700255
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700256 private static final int VERSION_INIT = 1;
257 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700258 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800259 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800260 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800261 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700262 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700263 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700264 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700265 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600266 private static final int VERSION_ADDED_CYCLE = 11;
267 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700268
Sudheer Shankae7361852017-03-07 11:51:46 -0800269 /**
270 * Max items written to {@link #ProcStateSeqHistory}.
271 */
272 @VisibleForTesting
273 public static final int MAX_PROC_STATE_SEQ_HISTORY =
274 ActivityManager.isLowRamDeviceStatic() ? 50 : 200;
275
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800276 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400277 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800278 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400279 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800280 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400281 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700282
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700283 private static final String TAG_POLICY_LIST = "policy-list";
284 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600285 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700286 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700287 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800288 private static final String TAG_WHITELIST = "whitelist";
289 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800290 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700291
292 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700293 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700294 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
295 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700296 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600297 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
298 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
299 private static final String ATTR_CYCLE_START = "cycleStart";
300 private static final String ATTR_CYCLE_END = "cycleEnd";
301 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700302 private static final String ATTR_WARNING_BYTES = "warningBytes";
303 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700304 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800305 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
306 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800307 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700308 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700309 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700310 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700311 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600312 private static final String ATTR_SUB_ID = "subId";
313 private static final String ATTR_TITLE = "title";
314 private static final String ATTR_SUMMARY = "summary";
315 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
316 private static final String ATTR_USAGE_BYTES = "usageBytes";
317 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600318 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700319
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800320 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800321 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800322 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800323 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700324
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700325 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
326
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700327 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700328 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800329 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800330 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700331 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700332 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
333 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700334 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700335 private static final int MSG_SET_FIREWALL_RULES = 14;
Felipe Leme03e95e22016-09-09 09:25:31 -0700336 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700337
Makoto Onuki8e777332017-03-28 11:25:47 -0700338 private static final int UID_MSG_STATE_CHANGED = 100;
339 private static final int UID_MSG_GONE = 101;
340
Jeff Sharkey75279902011-05-24 18:39:45 -0700341 private final Context mContext;
342 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700343 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700344 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700345 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700346 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700347 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700348 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700349
350 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700351 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700352 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700353 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800354 @GuardedBy("mUidRulesFirstLock")
355 private PowerSaveState mRestrictBackgroundPowerState;
356
357 // Store the status of restrict background before turning on battery saver.
358 // Used to restore mRestrictBackground when battery saver is turned off.
359 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700360
Felipe Lemef0823852016-06-08 13:43:08 -0700361 // See main javadoc for instructions on how to use these locks.
362 final Object mUidRulesFirstLock = new Object();
363 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700364
Felipe Lemef0823852016-06-08 13:43:08 -0700365 @GuardedBy("allLocks") volatile boolean mSystemReady;
366
Felipe Lemef0823852016-06-08 13:43:08 -0700367 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
368 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
369 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800370 // Store whether user flipped restrict background in battery saver mode
371 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700372
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700373 private final boolean mSuppressDefaultPolicy;
374
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700375 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600376 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800377 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700378
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600379 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600380 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600381 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600382 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600383 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600384 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600385
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700386 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700387 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700388 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700389 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700390
Felipe Lemef0823852016-06-08 13:43:08 -0700391 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700392 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700393 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700394 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700395 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800396 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700397
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700398 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700399 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700400 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
401
Jeff Sharkey32566012014-12-02 18:30:14 -0800402 /**
403 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700404 * in power save mode, except device idle (doze) still applies.
405 * TODO: An int array might be sufficient
406 */
Felipe Lemef0823852016-06-08 13:43:08 -0700407 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700408 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
409
410 /**
411 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800412 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700413 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800414 */
Felipe Lemef0823852016-06-08 13:43:08 -0700415 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700416 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700417
Felipe Lemef0823852016-06-08 13:43:08 -0700418 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700419 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
420
Felipe Lemeb85a6372016-01-14 16:16:16 -0800421 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800422 * UIDs that have been initially white-listed by system to avoid restricted background.
423 */
Felipe Lemef0823852016-06-08 13:43:08 -0700424 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800425 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
426 new SparseBooleanArray();
427
428 /**
429 * UIDs that have been initially white-listed by system to avoid restricted background,
430 * but later revoked by user.
431 */
Felipe Lemef0823852016-06-08 13:43:08 -0700432 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800433 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
434 new SparseBooleanArray();
435
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700436 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700437 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800438 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700439 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700440 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800441 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700442
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700443 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700444 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400445 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700446
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700447 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700448 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800449 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700450
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600451 /** Map from network ID to last observed meteredness state */
452 @GuardedBy("mNetworkPoliciesSecondLock")
453 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
454
Jeff Sharkey32566012014-12-02 18:30:14 -0800455 private final RemoteCallbackList<INetworkPolicyListener>
456 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700457
Dianne Hackborn497175b2014-07-01 12:56:08 -0700458 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700459 @VisibleForTesting
460 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700461
462 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700463
Felipe Lemef0823852016-06-08 13:43:08 -0700464 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700465 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700466
Svet Ganov16a16892015-04-16 10:32:04 -0700467 private final AppOpsManager mAppOps;
468
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800469 private final IPackageManager mIPm;
470
Sudheer Shankae7361852017-03-07 11:51:46 -0800471 private ActivityManagerInternal mActivityManagerInternal;
472
473 /**
474 * This is used for debugging purposes. Whenever the IUidObserver.onUidStateChanged is called,
475 * the uid and procStateSeq will be written to this and will be printed as part of dump.
476 */
477 @VisibleForTesting
478 public ProcStateSeqHistory mObservedHistory
479 = new ProcStateSeqHistory(MAX_PROC_STATE_SEQ_HISTORY);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800480
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700481 // TODO: keep whitelist of system-critical services that should never have
482 // rules enforced, such as system, phone, and radio UIDs.
483
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700484 // TODO: migrate notifications to SystemUI
485
Jeff Sharkey75279902011-05-24 18:39:45 -0700486 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700487 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
488 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700489 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
490 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700491 }
492
493 private static File getSystemDir() {
494 return new File(Environment.getDataDirectory(), "system");
495 }
496
497 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700498 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700499 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700500 mContext = checkNotNull(context, "missing context");
501 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700502 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700503 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700504 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700505 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700506 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700507 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700508 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700509 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700510
Amith Yamasani450a16b2013-09-18 16:28:50 -0700511 HandlerThread thread = new HandlerThread(TAG);
512 thread.start();
513 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700514
Makoto Onuki8e777332017-03-28 11:25:47 -0700515 // We create another thread for the UID events, which are more time-critical.
516 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
517 /*allowIo=*/ false);
518 mUidEventThread.start();
519 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
520
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700521 mSuppressDefaultPolicy = suppressDefaultPolicy;
522
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700523 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700524
525 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800526
Felipe Lemed17fda42016-04-29 11:12:45 -0700527 // Expose private service for system components to use.
528 LocalServices.addService(NetworkPolicyManagerInternal.class,
529 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700530 }
531
532 public void bindConnectivityManager(IConnectivityManager connManager) {
533 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700534 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700535
Jeff Sharkey497e4432011-06-14 17:27:29 -0700536 public void bindNotificationManager(INotificationManager notifManager) {
537 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
538 }
539
Felipe Lemef0823852016-06-08 13:43:08 -0700540 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700541 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700542 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
543 mPowerSaveWhitelistExceptIdleAppIds.clear();
544 if (whitelist != null) {
545 for (int uid : whitelist) {
546 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
547 }
548 }
549 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700550 mPowerSaveWhitelistAppIds.clear();
551 if (whitelist != null) {
552 for (int uid : whitelist) {
553 mPowerSaveWhitelistAppIds.put(uid, true);
554 }
555 }
556 } catch (RemoteException e) {
557 }
558 }
559
Felipe Lemea9505cc2016-02-26 10:28:41 -0800560 /**
561 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
562 * revoke the whitelist.
563 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700564 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800565 */
Felipe Lemef0823852016-06-08 13:43:08 -0700566 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800567 final List<UserInfo> users = mUserManager.getUsers();
568 final int numberUsers = users.size();
569
Felipe Lemea110eec2016-04-29 09:58:06 -0700570 boolean changed = false;
571 for (int i = 0; i < numberUsers; i++) {
572 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700573 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700574 }
575 return changed;
576 }
577
Felipe Lemef0823852016-06-08 13:43:08 -0700578 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700579 final SystemConfig sysConfig = SystemConfig.getInstance();
580 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800581 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
582 boolean changed = false;
583 for (int i = 0; i < allowDataUsage.size(); i++) {
584 final String pkg = allowDataUsage.valueAt(i);
585 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700586 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
587 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800588 final ApplicationInfo app;
589 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700590 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800591 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700592 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
593 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800594 continue;
595 }
596 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700597 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
598 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800599 continue;
600 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700601 final int uid = UserHandle.getUid(userId, app.uid);
602 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
603 if (LOGD)
604 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
605 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800606 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700607 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700608 if (LOGD)
609 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
610 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700611 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700612 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800613 }
614 }
615 return changed;
616 }
617
Felipe Lemef0823852016-06-08 13:43:08 -0700618 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700619 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700620 // Clear the states of the current whitelist
621 final int N = mPowerSaveTempWhitelistAppIds.size();
622 for (int i = 0; i < N; i++) {
623 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
624 }
625 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700626 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700627 if (whitelist != null) {
628 for (int uid : whitelist) {
629 mPowerSaveTempWhitelistAppIds.put(uid, true);
630 }
631 }
632 } catch (RemoteException e) {
633 }
634 }
635
Amith Yamasani06f08062015-06-12 13:23:33 -0700636 /**
637 * Remove unnecessary entries in the temp whitelist
638 */
Felipe Lemef0823852016-06-08 13:43:08 -0700639 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700640 final int N = mPowerSaveTempWhitelistAppIds.size();
641 for (int i = N - 1; i >= 0; i--) {
642 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
643 mPowerSaveTempWhitelistAppIds.removeAt(i);
644 }
645 }
646 }
647
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800648 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700649 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800650 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700651 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800652 // Boost thread's priority during system server init
653 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700654 if (!isBandwidthControlEnabled()) {
655 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
656 return;
657 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700658
Felipe Leme873a83a2016-09-07 11:34:10 -0700659 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700660
Felipe Leme873a83a2016-09-07 11:34:10 -0700661 synchronized (mUidRulesFirstLock) {
662 synchronized (mNetworkPoliciesSecondLock) {
663 updatePowerSaveWhitelistUL();
664 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
665 mPowerManagerInternal.registerLowPowerModeObserver(
666 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800667 @Override
668 public int getServiceType() {
669 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700670 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800671
672 @Override
673 public void onLowPowerModeChanged(PowerSaveState result) {
674 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800675 if (LOGD) {
676 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
677 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800678 synchronized (mUidRulesFirstLock) {
679 if (mRestrictPower != enabled) {
680 mRestrictPower = enabled;
681 updateRulesForRestrictPowerUL();
682 }
683 }
684 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800685 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800686 mRestrictPower = mPowerManagerInternal.getLowPowerState(
687 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700688
689 mSystemReady = true;
690
691 // read policy from disk
692 readPolicyAL();
693
jackqdyulei29c82ab2017-03-10 14:09:16 -0800694 // Update the restrictBackground if battery saver is turned on
695 mRestrictBackgroundBeforeBsm = mRestrictBackground;
696 mRestrictBackgroundPowerState = mPowerManagerInternal
697 .getLowPowerState(ServiceType.DATA_SAVER);
698 final boolean localRestrictBackground =
699 mRestrictBackgroundPowerState.batterySaverEnabled;
700 if (localRestrictBackground && localRestrictBackground != mRestrictBackground) {
701 mRestrictBackground = localRestrictBackground;
702 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
703 mRestrictBackground ? 1 : 0, 0).sendToTarget();
704 }
705 mPowerManagerInternal.registerLowPowerModeObserver(
706 new PowerManagerInternal.LowPowerModeListener() {
707 @Override
708 public int getServiceType() {
709 return ServiceType.DATA_SAVER;
710 }
711
712 @Override
713 public void onLowPowerModeChanged(PowerSaveState result) {
714 synchronized (mUidRulesFirstLock) {
715 updateRestrictBackgroundByLowPowerModeUL(result);
716 }
717 }
718 });
719
Felipe Leme873a83a2016-09-07 11:34:10 -0700720 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
721 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700722 }
Felipe Lemef0823852016-06-08 13:43:08 -0700723
Felipe Leme873a83a2016-09-07 11:34:10 -0700724 setRestrictBackgroundUL(mRestrictBackground);
725 updateRulesForGlobalChangeAL(false);
726 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700727 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800728 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700729
Sudheer Shankae7361852017-03-07 11:51:46 -0800730 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700731 try {
732 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000733 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800734 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700735 mNetworkManager.registerObserver(mAlertObserver);
736 } catch (RemoteException e) {
737 // ignored; both services live in system_server
738 }
739
740 // listen for changes to power save whitelist
741 final IntentFilter whitelistFilter = new IntentFilter(
742 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
743 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
744
745 DeviceIdleController.LocalService deviceIdleService
746 = LocalServices.getService(DeviceIdleController.LocalService.class);
747 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
748
749 // watch for network interfaces to be claimed
750 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
751 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
752
753 // listen for package changes to update policy
754 final IntentFilter packageFilter = new IntentFilter();
755 packageFilter.addAction(ACTION_PACKAGE_ADDED);
756 packageFilter.addDataScheme("package");
757 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
758
759 // listen for UID changes to update policy
760 mContext.registerReceiver(
761 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
762
763 // listen for user changes to update policy
764 final IntentFilter userFilter = new IntentFilter();
765 userFilter.addAction(ACTION_USER_ADDED);
766 userFilter.addAction(ACTION_USER_REMOVED);
767 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
768
769 // listen for stats update events
770 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
771 mContext.registerReceiver(
772 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
773
774 // listen for restrict background changes from notifications
775 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
776 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
777
778 // listen for snooze warning from notifications
779 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
780 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
781 MANAGE_NETWORK_POLICY, mHandler);
782
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600783 // listen for configured wifi networks to be loaded
784 final IntentFilter wifiFilter =
785 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
786 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700787
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700788 // listen for carrier config changes to update data cycle information
789 final IntentFilter carrierConfigFilter = new IntentFilter(
790 ACTION_CARRIER_CONFIG_CHANGED);
791 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
792
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600793 // listen for meteredness changes
794 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
795 new NetworkRequest.Builder().build(), mNetworkCallback);
796
Felipe Leme873a83a2016-09-07 11:34:10 -0700797 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800798 // tell systemReady() that the service has been initialized
799 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700800 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800801 // Restore the default priority after init is done
802 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700803 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700804 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700805 }
806
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800807 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
808 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
809 mHandler.post(() -> initService(initCompleteSignal));
810 return initCompleteSignal;
811 }
812
813 public void systemReady(CountDownLatch initCompleteSignal) {
814 // wait for initService to complete
815 try {
816 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
817 throw new IllegalStateException("Service " + TAG +" init timeout");
818 }
819 } catch (InterruptedException e) {
820 Thread.currentThread().interrupt();
821 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
822 }
823 }
824
Sudheer Shankac9d94072017-02-22 22:13:55 +0000825 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700826 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700827 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
828 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700829 }
830
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700831 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700832 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700833 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700834
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700835 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700836 }
837
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700838 @Override public void onUidIdle(int uid, boolean disabled) {
839 }
840
841 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700842 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700843 };
844
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700845 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700846 @Override
847 public void onReceive(Context context, Intent intent) {
848 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700849 synchronized (mUidRulesFirstLock) {
850 updatePowerSaveWhitelistUL();
851 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700852 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700853 }
854 }
855 };
856
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700857 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
858 @Override
859 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700860 synchronized (mUidRulesFirstLock) {
861 updatePowerSaveTempWhitelistUL();
862 updateRulesForTempWhitelistChangeUL();
863 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700864 }
865 }
866 };
867
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700868 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700869 @Override
870 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700871 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700872
873 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700874 final int uid = intent.getIntExtra(EXTRA_UID, -1);
875 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700876
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700877 if (ACTION_PACKAGE_ADDED.equals(action)) {
878 // update rules for UID, since it might be subject to
879 // global background data policy
880 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700881 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700882 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700883 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700884 }
885 }
886 };
887
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700888 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700889 @Override
890 public void onReceive(Context context, Intent intent) {
891 // on background handler thread, and UID_REMOVED is protected
892
893 final int uid = intent.getIntExtra(EXTRA_UID, -1);
894 if (uid == -1) return;
895
896 // remove any policy and update rules to clean up
897 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700898 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700899 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700900 synchronized (mNetworkPoliciesSecondLock) {
901 writePolicyAL();
902 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700903 }
904 }
905 };
906
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700907 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700908 @Override
909 public void onReceive(Context context, Intent intent) {
910 // on background handler thread, and USER_ADDED and USER_REMOVED
911 // broadcasts are protected
912
913 final String action = intent.getAction();
914 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
915 if (userId == -1) return;
916
Amith Yamasani15e472352015-04-24 19:06:07 -0700917 switch (action) {
918 case ACTION_USER_REMOVED:
919 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700920 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800921 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700922 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700923 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700924 if (action == ACTION_USER_ADDED) {
925 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700926 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700927 }
928 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700929 synchronized (mNetworkPoliciesSecondLock) {
930 updateRulesForGlobalChangeAL(true);
931 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700932 }
933 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700934 }
935 }
936 };
937
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700938 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700939 * Receiver that watches for {@link INetworkStatsService} updates, which we
940 * use to check against {@link NetworkPolicy#warningBytes}.
941 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700942 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700943 @Override
944 public void onReceive(Context context, Intent intent) {
945 // on background handler thread, and verified
946 // READ_NETWORK_USAGE_HISTORY permission above.
947
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800948 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700949 synchronized (mNetworkPoliciesSecondLock) {
950 updateNetworkEnabledNL();
951 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700952 }
953 }
954 };
955
956 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700957 * Receiver that watches for {@link Notification} control of
958 * {@link #mRestrictBackground}.
959 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700960 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700961 @Override
962 public void onReceive(Context context, Intent intent) {
963 // on background handler thread, and verified MANAGE_NETWORK_POLICY
964 // permission above.
965
966 setRestrictBackground(false);
967 }
968 };
969
970 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800971 * Receiver that watches for {@link Notification} control of
972 * {@link NetworkPolicy#lastWarningSnooze}.
973 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700974 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800975 @Override
976 public void onReceive(Context context, Intent intent) {
977 // on background handler thread, and verified MANAGE_NETWORK_POLICY
978 // permission above.
979
980 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
981 performSnooze(template, TYPE_WARNING);
982 }
983 };
984
985 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600986 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -0600987 * we can perform upgrade logic. After initial upgrade logic, it updates
988 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700989 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600990 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700991 @Override
992 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900993 synchronized (mUidRulesFirstLock) {
994 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600995 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600996 }
997 }
998 // Only need to perform upgrade logic once
999 mContext.unregisterReceiver(this);
1000 }
1001 };
1002
1003 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1004 @Override
1005 public void onCapabilitiesChanged(Network network,
1006 NetworkCapabilities networkCapabilities) {
1007 if (network == null || networkCapabilities == null) return;
1008
1009 synchronized (mNetworkPoliciesSecondLock) {
1010 final boolean oldMetered = mNetworkMetered.get(network.netId, false);
1011 final boolean newMetered = !networkCapabilities
1012 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1013
1014 if ((oldMetered != newMetered) || mNetworkMetered.indexOfKey(network.netId) < 0) {
1015 mNetworkMetered.put(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001016 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001017 }
1018 }
1019 }
1020 };
1021
1022 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001023 * Observer that watches for {@link INetworkManagementService} alerts.
1024 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001025 final private INetworkManagementEventObserver mAlertObserver
1026 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001027 @Override
1028 public void limitReached(String limitName, String iface) {
1029 // only someone like NMS should be calling us
1030 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1031
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001032 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1033 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001034 }
1035 }
1036 };
1037
1038 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001039 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1040 * to show visible notifications as needed.
1041 */
Felipe Lemef0823852016-06-08 13:43:08 -07001042 void updateNotificationsNL() {
1043 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001044
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001045 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001046 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001047 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001048
1049 // TODO: when switching to kernel notifications, compute next future
1050 // cycle boundary to recompute notifications.
1051
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001052 // examine stats for each active policy
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001053 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1054 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001055 // ignore policies that aren't relevant to user
1056 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001057 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001058
Jeff Sharkey53313d72017-07-13 16:47:32 -06001059 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1060 .cycleIterator(policy).next();
1061 final long start = cycle.first.toInstant().toEpochMilli();
1062 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001063 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001064
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001065 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001066 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001067 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1068 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001069 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001070 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001071 }
1072
Jeff Sharkey497e4432011-06-14 17:27:29 -07001073 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001074 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001075
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001076 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001077 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001078 }
1079 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001080 }
1081
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001082 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001083 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001084 final NotificationId notificationId = beforeNotifs.valueAt(i);
1085 if (!mActiveNotifs.contains(notificationId)) {
1086 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001087 }
1088 }
1089 }
1090
1091 /**
1092 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001093 * current device state, such as when
1094 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1095 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001096 */
1097 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001098 if (template.isMatchRuleMobile()) {
1099 final TelephonyManager tele = TelephonyManager.from(mContext);
1100 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001101
Jeff Sharkey32566012014-12-02 18:30:14 -08001102 // Mobile template is relevant when any active subscriber matches
1103 final int[] subIds = sub.getActiveSubscriptionIdList();
1104 for (int subId : subIds) {
1105 final String subscriberId = tele.getSubscriberId(subId);
1106 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001107 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001108 if (template.matches(probeIdent)) {
1109 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001110 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001111 }
1112 return false;
1113 } else {
1114 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001115 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001116 }
1117
1118 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001119 * Notify that given {@link NetworkTemplate} is over
1120 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1121 */
Felipe Lemef0823852016-06-08 13:43:08 -07001122 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001123 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001124 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001125 mOverLimitNotified.add(template);
1126 }
1127 }
1128
Felipe Lemef0823852016-06-08 13:43:08 -07001129 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001130 mOverLimitNotified.remove(template);
1131 }
1132
1133 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001134 * Show notification for combined {@link NetworkPolicy} and specific type,
1135 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1136 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001137 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001138 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001139 final Notification.Builder builder =
1140 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001141 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001142 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001143 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001144 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001145
1146 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001147 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001148 switch (type) {
1149 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001150 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001151 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001152
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001153 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001154 builder.setTicker(title);
1155 builder.setContentTitle(title);
1156 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001157 builder.setDefaults(Notification.DEFAULT_ALL);
Julia Reynoldsbad42972017-04-25 13:52:49 -04001158 builder.setChannelId(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001159
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001160 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1161 builder.setDeleteIntent(PendingIntent.getBroadcast(
1162 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1163
Wei Liu546cb772016-07-21 16:19:01 -07001164 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001165 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001166 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1167
Jeff Sharkey497e4432011-06-14 17:27:29 -07001168 break;
1169 }
1170 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001171 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001172
1173 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001174 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001175 switch (policy.template.getMatchRule()) {
1176 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001177 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001178 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001179 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001180 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001181 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001182 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001183 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001184 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001185 case MATCH_WIFI:
1186 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001187 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001188 break;
1189 default:
1190 title = null;
1191 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001192 }
1193
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001194 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001195 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001196 builder.setTicker(title);
1197 builder.setContentTitle(title);
1198 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001199
Wei Liu546cb772016-07-21 16:19:01 -07001200 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001201 builder.setContentIntent(PendingIntent.getActivity(
1202 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1203 break;
1204 }
1205 case TYPE_LIMIT_SNOOZED: {
1206 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001207 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001208 Formatter.formatFileSize(mContext, overBytes));
1209
1210 final CharSequence title;
1211 switch (policy.template.getMatchRule()) {
1212 case MATCH_MOBILE_3G_LOWER:
1213 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1214 break;
1215 case MATCH_MOBILE_4G:
1216 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1217 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001218 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001219 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1220 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001221 case MATCH_WIFI:
1222 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1223 break;
1224 default:
1225 title = null;
1226 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001227 }
1228
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001229 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001230 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001231 builder.setTicker(title);
1232 builder.setContentTitle(title);
1233 builder.setContentText(body);
1234
Wei Liu546cb772016-07-21 16:19:01 -07001235 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001236 builder.setContentIntent(PendingIntent.getActivity(
1237 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001238 break;
1239 }
1240 }
1241
1242 // TODO: move to NotificationManager once we can mock it
1243 try {
1244 final String packageName = mContext.getPackageName();
Chris Wren193ae6b2017-03-31 15:17:11 -04001245 if (!TextUtils.isEmpty(body)) {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001246 builder.setStyle(new Notification.BigTextStyle()
1247 .bigText(body));
1248 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001249 mNotifManager.enqueueNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001250 packageName, packageName, notificationId.getTag(), notificationId.getId(),
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001251 builder.build(), UserHandle.USER_ALL);
Chris Wren193ae6b2017-03-31 15:17:11 -04001252 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001253 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001254 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001255 }
1256 }
1257
Chris Wren193ae6b2017-03-31 15:17:11 -04001258 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001259 // TODO: move to NotificationManager once we can mock it
1260 try {
1261 final String packageName = mContext.getPackageName();
1262 mNotifManager.cancelNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001263 packageName, notificationId.getTag(), notificationId.getId(),
1264 UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001265 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001266 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001267 }
1268 }
1269
1270 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001271 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001272 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001273 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001274 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001275 @Override
1276 public void onReceive(Context context, Intent intent) {
1277 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1278 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001279
1280 maybeRefreshTrustedTime();
Hugo Benichi446c9c92017-04-10 09:41:10 +09001281 synchronized (mUidRulesFirstLock) {
1282 synchronized (mNetworkPoliciesSecondLock) {
1283 ensureActiveMobilePolicyAL();
1284 normalizePoliciesNL();
1285 updateNetworkEnabledNL();
1286 updateNetworkRulesNL();
1287 updateNotificationsNL();
1288 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001289 }
1290 }
1291 };
1292
1293 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001294 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1295 * if necessary.
1296 *
1297 * @param subId that has its associated NetworkPolicy updated if necessary
1298 * @return if any policies were updated
1299 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001300 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1301 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001302
1303 boolean policyUpdated = false;
1304 final String subscriberId = TelephonyManager.from(mContext).getSubscriberId(subId);
1305
1306 // find and update the mobile NetworkPolicy for this subscriber id
1307 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1308 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1309 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1310 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1311 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001312 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1313 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001314 }
1315 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001316 return policyUpdated;
1317 }
1318
1319 /**
1320 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1321 *
1322 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1323 * to do so, it returns the fallback value.
1324 *
1325 * @param config The CarrierConfig to read the value from.
1326 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1327 * @return cycleDay to use in the mobile NetworkPolicy.
1328 */
1329 @VisibleForTesting
1330 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1331 int fallbackCycleDay) {
1332 if (config == null) {
1333 return fallbackCycleDay;
1334 }
1335 int cycleDay =
1336 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1337 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1338 return fallbackCycleDay;
1339 }
1340 // validate cycleDay value
1341 final Calendar cal = Calendar.getInstance();
1342 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1343 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1344 Slog.e(TAG, "Invalid date in "
1345 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1346 return fallbackCycleDay;
1347 }
1348 return cycleDay;
1349 }
1350
1351 /**
1352 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1353 *
1354 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1355 * to do so, it returns the fallback value.
1356 *
1357 * @param config The CarrierConfig to read the value from.
1358 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1359 * @return warningBytes to use in the mobile NetworkPolicy.
1360 */
1361 @VisibleForTesting
1362 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1363 long fallbackWarningBytes) {
1364 if (config == null) {
1365 return fallbackWarningBytes;
1366 }
1367 long warningBytes =
1368 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1369
1370 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1371 return WARNING_DISABLED;
1372 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1373 return getPlatformDefaultWarningBytes();
1374 } else if (warningBytes < 0) {
1375 Slog.e(TAG, "Invalid value in "
1376 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1377 + "non-negative value but got: " + warningBytes);
1378 return fallbackWarningBytes;
1379 }
1380
1381 return warningBytes;
1382 }
1383
1384 /**
1385 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1386 *
1387 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1388 * to do so, it returns the fallback value.
1389 *
1390 * @param config The CarrierConfig to read the value from.
1391 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1392 * @return limitBytes to use in the mobile NetworkPolicy.
1393 */
1394 @VisibleForTesting
1395 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1396 long fallbackLimitBytes) {
1397 if (config == null) {
1398 return fallbackLimitBytes;
1399 }
1400 long limitBytes =
1401 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1402
1403 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1404 return LIMIT_DISABLED;
1405 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1406 return getPlatformDefaultLimitBytes();
1407 } else if (limitBytes < 0) {
1408 Slog.e(TAG, "Invalid value in "
1409 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1410 + "non-negative value but got: " + limitBytes);
1411 return fallbackLimitBytes;
1412 }
1413 return limitBytes;
1414 }
1415
1416 /**
1417 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1418 */
1419 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1420 @Override
1421 public void onReceive(Context context, Intent intent) {
1422 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1423 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1424
1425 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1426 return;
1427 }
1428 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
1429 final TelephonyManager tele = TelephonyManager.from(mContext);
1430 final String subscriberId = tele.getSubscriberId(subId);
1431
1432 maybeRefreshTrustedTime();
1433 synchronized (mUidRulesFirstLock) {
1434 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001435 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001436 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001437 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001438 if (!updated) return;
1439 // update network and notification rules, as the data cycle changed and it's
1440 // possible that we should be triggering warnings/limits now
1441 handleNetworkPoliciesUpdateAL(true);
1442 }
1443 }
1444 }
1445 };
1446
1447 /**
1448 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1449 * one has been updated.
1450 *
1451 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1452 * update.
1453 */
1454 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1455 if (shouldNormalizePolicies) {
1456 normalizePoliciesNL();
1457 }
1458 updateNetworkEnabledNL();
1459 updateNetworkRulesNL();
1460 updateNotificationsNL();
1461 writePolicyAL();
1462 }
1463
1464 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001465 * Proactively control network data connections when they exceed
1466 * {@link NetworkPolicy#limitBytes}.
1467 */
Felipe Lemef0823852016-06-08 13:43:08 -07001468 void updateNetworkEnabledNL() {
1469 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001470
1471 // TODO: reset any policy-disabled networks when any policy is removed
1472 // completely, which is currently rare case.
1473
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001474 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1475 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001476 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001477 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001478 setNetworkTemplateEnabled(policy.template, true);
1479 continue;
1480 }
1481
Jeff Sharkey53313d72017-07-13 16:47:32 -06001482 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1483 .cycleIterator(policy).next();
1484 final long start = cycle.first.toInstant().toEpochMilli();
1485 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001486 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001487
1488 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001489 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1490 && policy.lastLimitSnooze < start;
1491 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001492
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001493 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001494 }
1495 }
1496
1497 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001498 * Proactively disable networks that match the given
1499 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001500 */
1501 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001502 // TODO: reach into ConnectivityManager to proactively disable bringing
1503 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001504
1505 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1506 // If mobile data usage hits the limit or if the user resumes the data, we need to
1507 // notify telephony.
1508 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1509 final TelephonyManager tm = TelephonyManager.from(mContext);
1510
1511 final int[] subIds = sm.getActiveSubscriptionIdList();
1512 for (int subId : subIds) {
1513 final String subscriberId = tm.getSubscriberId(subId);
1514 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1515 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1516 // Template is matched when subscriber id matches.
1517 if (template.matches(probeIdent)) {
1518 tm.setPolicyDataEnabled(enabled, subId);
1519 }
1520 }
1521 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001522 }
1523
1524 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001525 * Collect all ifaces from a {@link NetworkState} into the given set.
1526 */
1527 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1528 final String baseIface = state.linkProperties.getInterfaceName();
1529 if (baseIface != null) {
1530 ifaces.add(baseIface);
1531 }
1532 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1533 final String stackedIface = stackedLink.getInterfaceName();
1534 if (stackedIface != null) {
1535 ifaces.add(stackedIface);
1536 }
1537 }
1538 }
1539
1540 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001541 * Examine all connected {@link NetworkState}, looking for
1542 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1543 * remaining quota based on usage cycle and historical stats.
1544 */
Felipe Lemef0823852016-06-08 13:43:08 -07001545 void updateNetworkRulesNL() {
1546 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001547
1548 final NetworkState[] states;
1549 try {
1550 states = mConnManager.getAllNetworkState();
1551 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001552 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001553 return;
1554 }
1555
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001556 // First, generate identities of all connected networks so we can
1557 // quickly compare them against all defined policies below.
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001558 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001559 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001560 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001561 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001562 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001563 }
1564 }
1565
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001566 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001567 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001568
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001569 // For every well-defined policy, compute remaining data based on
1570 // current cycle and historical stats, and push to kernel.
1571 final ArraySet<String> matchingIfaces = new ArraySet<>();
1572 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1573 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1574
1575 // Collect all ifaces that match this policy
1576 matchingIfaces.clear();
1577 for (int j = identified.size() - 1; j >= 0; j--) {
1578 if (policy.template.matches(identified.valueAt(j))) {
1579 collectIfaces(matchingIfaces, identified.keyAt(j));
1580 }
1581 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001582
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001583 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001584 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001585 }
1586
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001587 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001588 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001589 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001590 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001591 if (hasLimit && policy.hasCycle()) {
1592 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1593 .cycleIterator(policy).next();
1594 final long start = cycle.first.toInstant().toEpochMilli();
1595 final long end = cycle.second.toInstant().toEpochMilli();
1596 final long totalBytes = getTotalBytes(policy.template, start, end);
1597
1598 if (policy.lastLimitSnooze >= start) {
1599 // snoozing past quota, but we still need to restrict apps,
1600 // so push really high quota.
1601 quotaBytes = Long.MAX_VALUE;
1602 } else {
1603 // remaining "quota" bytes are based on total usage in
1604 // current cycle. kernel doesn't like 0-byte rules, so we
1605 // set 1-byte quota and disable the radio later.
1606 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1607 }
1608 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001609 // metered network, but no policy limit; we still need to
1610 // restrict apps, so push really high quota.
1611 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001612 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001613
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001614 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001615 // TODO: switch to shared quota once NMS supports
1616 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001617 }
1618
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001619 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1620 final String iface = matchingIfaces.valueAt(j);
1621 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001622 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001623 }
1624 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001625
1626 // keep track of lowest warning or limit of active policies
1627 if (hasWarning && policy.warningBytes < lowestRule) {
1628 lowestRule = policy.warningBytes;
1629 }
1630 if (hasLimit && policy.limitBytes < lowestRule) {
1631 lowestRule = policy.limitBytes;
1632 }
1633 }
1634
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001635 // One final pass to catch any metered ifaces that don't have explicitly
1636 // defined policies; typically Wi-Fi networks.
1637 for (NetworkState state : states) {
1638 if (state.networkInfo != null && state.networkInfo.isConnected()
1639 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1640 matchingIfaces.clear();
1641 collectIfaces(matchingIfaces, state);
1642 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1643 final String iface = matchingIfaces.valueAt(j);
1644 if (!newMeteredIfaces.contains(iface)) {
1645 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1646 newMeteredIfaces.add(iface);
1647 }
1648 }
1649 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001650 }
1651
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001652 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001653 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1654 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001655 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001656 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001657 }
1658 }
1659 mMeteredIfaces = newMeteredIfaces;
1660
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001661 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001662 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001663
1664 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001665 }
1666
1667 /**
1668 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1669 * have at least a default mobile policy defined.
1670 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001671 private void ensureActiveMobilePolicyAL() {
1672 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001673 if (mSuppressDefaultPolicy) return;
1674
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001675 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001676 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001677
Jeff Sharkey32566012014-12-02 18:30:14 -08001678 final int[] subIds = sub.getActiveSubscriptionIdList();
1679 for (int subId : subIds) {
1680 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001681 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001682 }
1683 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001684
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001685 /**
1686 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1687 * have at least a default mobile policy defined.
1688 *
1689 * @param subId to build a default policy for
1690 * @param subscriberId that we check for an existing policy
1691 * @return true if a mobile network policy was added, or false one already existed.
1692 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001693 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001694 // Poke around to see if we already have a policy
1695 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001696 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001697 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1698 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1699 if (template.matches(probeIdent)) {
1700 if (LOGD) {
1701 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1702 + NetworkIdentity.scrubSubscriberId(subscriberId));
1703 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001704 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001705 }
1706 }
1707
Jeff Sharkey32566012014-12-02 18:30:14 -08001708 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1709 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001710 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001711 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001712 return true;
1713 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001714
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001715 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001716 final int dataWarningConfig = mContext.getResources().getInteger(
1717 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001718 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001719 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001720 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001721 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001722 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001723 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001724
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001725 private long getPlatformDefaultLimitBytes() {
1726 return LIMIT_DISABLED;
1727 }
1728
1729 @VisibleForTesting
1730 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001731 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001732 final RecurrenceRule cycleRule = NetworkPolicy
1733 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001734 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001735 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1736 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1737 synchronized (mUidRulesFirstLock) {
1738 synchronized (mNetworkPoliciesSecondLock) {
1739 updateDefaultMobilePolicyAL(subId, policy);
1740 }
1741 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001742 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001743 }
1744
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001745 /**
1746 * Update the given {@link NetworkPolicy} based on any carrier-provided
1747 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1748 * Leaves policy untouched if the user has modified it.
1749 *
1750 * @return if the policy was modified
1751 */
1752 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1753 if (!policy.inferred) {
1754 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1755 return false;
1756 }
1757
1758 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1759 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1760 policy.lastLimitSnooze, policy.metered, policy.inferred);
1761
1762 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1763 if (!ArrayUtils.isEmpty(plans)) {
1764 final SubscriptionPlan plan = plans[0];
1765 policy.cycleRule = plan.getCycleRule();
1766 final long planLimitBytes = plan.getDataLimitBytes();
1767 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1768 policy.warningBytes = getPlatformDefaultWarningBytes();
1769 policy.limitBytes = getPlatformDefaultLimitBytes();
1770 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1771 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1772 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1773 } else {
1774 policy.warningBytes = (planLimitBytes * 9) / 10;
1775 switch (plan.getDataLimitBehavior()) {
1776 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1777 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1778 policy.limitBytes = planLimitBytes;
1779 break;
1780 default:
1781 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1782 break;
1783 }
1784 }
1785 } else {
1786 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1787 final int currentCycleDay;
1788 if (policy.cycleRule.isMonthly()) {
1789 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1790 } else {
1791 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1792 }
1793 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1794 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1795 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1796 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1797 }
1798
1799 if (policy.equals(original)) {
1800 return false;
1801 } else {
1802 Slog.d(TAG, "Updated " + original + " to " + policy);
1803 return true;
1804 }
1805 }
1806
Felipe Lemef0823852016-06-08 13:43:08 -07001807 private void readPolicyAL() {
1808 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001809
1810 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001811 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001812 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001813 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001814 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001815
1816 FileInputStream fis = null;
1817 try {
1818 fis = mPolicyFile.openRead();
1819 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001820 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001821
Felipe Leme46b451f2016-08-19 08:46:17 -07001822 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1823 // to skip UIDs that were explicitly blacklisted.
1824 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1825
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001826 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001827 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001828 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001829 while ((type = in.next()) != END_DOCUMENT) {
1830 final String tag = in.getName();
1831 if (type == START_TAG) {
1832 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001833 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001834 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001835 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1836 mRestrictBackground = readBooleanAttribute(
1837 in, ATTR_RESTRICT_BACKGROUND);
1838 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001839 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001840 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001841 if (mRestrictBackground != oldValue) {
1842 // Some early services may have read the default value,
1843 // so notify them that it's changed
1844 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1845 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1846 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001847
1848 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1849 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1850 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001851 final String networkId;
1852 if (version >= VERSION_ADDED_NETWORK_ID) {
1853 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1854 } else {
1855 networkId = null;
1856 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001857 final RecurrenceRule cycleRule;
1858 if (version >= VERSION_ADDED_CYCLE) {
1859 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1860 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1861 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1862 cycleRule = new RecurrenceRule(
1863 RecurrenceRule.convertZonedDateTime(start),
1864 RecurrenceRule.convertZonedDateTime(end),
1865 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001866 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001867 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1868 final String cycleTimezone;
1869 if (version >= VERSION_ADDED_TIMEZONE) {
1870 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1871 } else {
1872 cycleTimezone = "UTC";
1873 }
1874 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001875 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001876 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1877 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001878 final long lastLimitSnooze;
1879 if (version >= VERSION_SPLIT_SNOOZE) {
1880 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1881 } else if (version >= VERSION_ADDED_SNOOZE) {
1882 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001883 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001884 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001885 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001886 final boolean metered;
1887 if (version >= VERSION_ADDED_METERED) {
1888 metered = readBooleanAttribute(in, ATTR_METERED);
1889 } else {
1890 switch (networkTemplate) {
1891 case MATCH_MOBILE_3G_LOWER:
1892 case MATCH_MOBILE_4G:
1893 case MATCH_MOBILE_ALL:
1894 metered = true;
1895 break;
1896 default:
1897 metered = false;
1898 }
1899 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001900 final long lastWarningSnooze;
1901 if (version >= VERSION_SPLIT_SNOOZE) {
1902 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1903 } else {
1904 lastWarningSnooze = SNOOZE_NEVER;
1905 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001906 final boolean inferred;
1907 if (version >= VERSION_ADDED_INFERRED) {
1908 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1909 } else {
1910 inferred = false;
1911 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001912
Jeff Sharkey32566012014-12-02 18:30:14 -08001913 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1914 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001915 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001916 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
1917 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001918 lastLimitSnooze, metered, inferred));
1919 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001920
1921 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
1922 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1923 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1924 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1925 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
1926 RecurrenceRule.convertZonedDateTime(start),
1927 RecurrenceRule.convertZonedDateTime(end),
1928 RecurrenceRule.convertPeriod(period));
1929 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
1930 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
1931
1932 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
1933 SubscriptionPlan.BYTES_UNKNOWN);
1934 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
1935 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
1936 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
1937 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
1938 builder.setDataLimit(limitBytes, limitBehavior);
1939 }
1940
1941 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
1942 SubscriptionPlan.BYTES_UNKNOWN);
1943 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
1944 SubscriptionPlan.TIME_UNKNOWN);
1945 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
1946 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
1947 builder.setDataUsage(usageBytes, usageTime);
1948 }
1949
1950 final int subId = readIntAttribute(in, ATTR_SUB_ID);
1951 final SubscriptionPlan plan = builder.build();
1952 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
1953 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
1954
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001955 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
1956 mSubscriptionPlansOwner.put(subId, ownerPackage);
1957
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001958 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001959 final int uid = readIntAttribute(in, ATTR_UID);
1960 final int policy = readIntAttribute(in, ATTR_POLICY);
1961
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001962 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001963 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001964 } else {
1965 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1966 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001967 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001968 final int appId = readIntAttribute(in, ATTR_APP_ID);
1969 final int policy = readIntAttribute(in, ATTR_POLICY);
1970
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001971 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001972 // app policy is deprecated so this is only used in pre system user split.
1973 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001974 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001975 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001976 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001977 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001978 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001979 } else if (TAG_WHITELIST.equals(tag)) {
1980 insideWhitelist = true;
1981 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1982 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001983 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001984 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1985 final int uid = readIntAttribute(in, ATTR_UID);
1986 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001987 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001988 } else if (type == END_TAG) {
1989 if (TAG_WHITELIST.equals(tag)) {
1990 insideWhitelist = false;
1991 }
1992
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001993 }
1994 }
1995
Felipe Leme46b451f2016-08-19 08:46:17 -07001996 final int size = whitelistedRestrictBackground.size();
1997 for (int i = 0; i < size; i++) {
1998 final int uid = whitelistedRestrictBackground.keyAt(i);
1999 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2000 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2001 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2002 + " because its policy is " + uidPoliciesToString(policy));
2003 continue;
2004 }
2005 if (UserHandle.isApp(uid)) {
2006 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2007 if (LOGV)
2008 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2009 setUidPolicyUncheckedUL(uid, newPolicy, false);
2010 } else {
2011 Slog.w(TAG, "unable to update policy on UID " + uid);
2012 }
2013 }
2014
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002015 } catch (FileNotFoundException e) {
2016 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002017 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002018 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002019 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002020 } finally {
2021 IoUtils.closeQuietly(fis);
2022 }
2023 }
2024
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002025 /**
2026 * Upgrade legacy background data flags, notifying listeners of one last
2027 * change to always-true.
2028 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002029 private void upgradeDefaultBackgroundDataUL() {
2030 // This method is only called when we're unable to find the network policy flag, which
2031 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002032
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002033 // Seed from the default value configured for this device.
2034 mRestrictBackground = Settings.Global.getInt(
2035 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2036
2037 // NOTE: We used to read the legacy setting here :
2038 //
2039 // final int legacyFlagValue = Settings.Secure.getInt(
2040 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2041 //
2042 // This is no longer necessary because we will never upgrade directly from Gingerbread
2043 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2044 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002045 }
2046
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002047 /**
2048 * Perform upgrade step of moving any user-defined meterness overrides over
2049 * into {@link WifiConfiguration}.
2050 */
2051 private void upgradeWifiMeteredOverrideAL() {
2052 boolean modified = false;
2053 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2054 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2055 for (int i = 0; i < mNetworkPolicy.size(); ) {
2056 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2057 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2058 && !policy.inferred) {
2059 mNetworkPolicy.removeAt(i);
2060 modified = true;
2061
2062 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2063 for (WifiConfiguration config : configs) {
2064 if (Objects.equals(resolveNetworkId(config), networkId)) {
2065 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2066 config.meteredOverride = policy.metered
2067 ? WifiConfiguration.METERED_OVERRIDE_METERED
2068 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2069 wm.updateNetwork(config);
2070 }
2071 }
2072 } else {
2073 i++;
2074 }
2075 }
2076 if (modified) {
2077 writePolicyAL();
2078 }
2079 }
2080
Felipe Lemef0823852016-06-08 13:43:08 -07002081 void writePolicyAL() {
2082 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002083
2084 FileOutputStream fos = null;
2085 try {
2086 fos = mPolicyFile.startWrite();
2087
2088 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002089 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002090 out.startDocument(null, true);
2091
2092 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002093 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002094 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002095
2096 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002097 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2098 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002099 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002100 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002101
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002102 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002103 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2104 final String subscriberId = template.getSubscriberId();
2105 if (subscriberId != null) {
2106 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002107 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002108 final String networkId = template.getNetworkId();
2109 if (networkId != null) {
2110 out.attribute(null, ATTR_NETWORK_ID, networkId);
2111 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002112 writeStringAttribute(out, ATTR_CYCLE_START,
2113 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2114 writeStringAttribute(out, ATTR_CYCLE_END,
2115 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2116 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2117 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002118 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2119 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002120 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2121 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002122 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002123 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002124 out.endTag(null, TAG_NETWORK_POLICY);
2125 }
2126
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002127 // write all known subscription plans
2128 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2129 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002130 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002131 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2132 if (ArrayUtils.isEmpty(plans)) continue;
2133
2134 for (SubscriptionPlan plan : plans) {
2135 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2136 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002137 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002138 final RecurrenceRule cycleRule = plan.getCycleRule();
2139 writeStringAttribute(out, ATTR_CYCLE_START,
2140 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2141 writeStringAttribute(out, ATTR_CYCLE_END,
2142 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2143 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2144 RecurrenceRule.convertPeriod(cycleRule.period));
2145 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2146 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2147 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2148 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2149 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2150 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2151 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2152 }
2153 }
2154
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002155 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002156 for (int i = 0; i < mUidPolicy.size(); i++) {
2157 final int uid = mUidPolicy.keyAt(i);
2158 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002159
Jeff Sharkey497e4432011-06-14 17:27:29 -07002160 // skip writing empty policies
2161 if (policy == POLICY_NONE) continue;
2162
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002163 out.startTag(null, TAG_UID_POLICY);
2164 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002165 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002166 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002167 }
2168
2169 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002170
2171 // write all whitelists
2172 out.startTag(null, TAG_WHITELIST);
2173
Felipe Lemea9505cc2016-02-26 10:28:41 -08002174 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002175 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002176 for (int i = 0; i < size; i++) {
2177 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2178 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2179 writeIntAttribute(out, ATTR_UID, uid);
2180 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2181 }
2182
Felipe Lemeb85a6372016-01-14 16:16:16 -08002183 out.endTag(null, TAG_WHITELIST);
2184
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002185 out.endDocument();
2186
2187 mPolicyFile.finishWrite(fos);
2188 } catch (IOException e) {
2189 if (fos != null) {
2190 mPolicyFile.failWrite(fos);
2191 }
2192 }
2193 }
2194
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002195 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002196 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002197 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002198
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002199 if (!UserHandle.isApp(uid)) {
2200 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002201 }
Felipe Lemef0823852016-06-08 13:43:08 -07002202 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002203 final long token = Binder.clearCallingIdentity();
2204 try {
2205 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2206 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002207 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002208 }
2209 } finally {
2210 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002211 }
2212 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002213 }
2214
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002215 @Override
2216 public void addUidPolicy(int uid, int policy) {
2217 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002218
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002219 if (!UserHandle.isApp(uid)) {
2220 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2221 }
2222
Felipe Lemef0823852016-06-08 13:43:08 -07002223 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002224 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2225 policy |= oldPolicy;
2226 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002227 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002228 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002229 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002230 }
2231
2232 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002233 public void removeUidPolicy(int uid, int policy) {
2234 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2235
2236 if (!UserHandle.isApp(uid)) {
2237 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2238 }
2239
Felipe Lemef0823852016-06-08 13:43:08 -07002240 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002241 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2242 policy = oldPolicy & ~policy;
2243 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002244 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002245 }
2246 }
2247 }
2248
Felipe Lemef0823852016-06-08 13:43:08 -07002249 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2250 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002251
Felipe Leme57e3d312016-08-23 14:42:52 -07002252 final boolean notifyApp;
2253 if (!isUidValidForWhitelistRules(uid)) {
2254 notifyApp = false;
2255 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002256 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2257 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2258 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2259 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002260 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2261 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002262 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2263 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2264 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2265 if (LOGD)
2266 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2267 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2268 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002269 notifyApp = wasBlocked != isBlocked;
2270 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002271 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2272 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002273 }
2274
Felipe Lemef0823852016-06-08 13:43:08 -07002275 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002276 if (policy == POLICY_NONE) {
2277 mUidPolicy.delete(uid);
2278 } else {
2279 mUidPolicy.put(uid, policy);
2280 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002281
2282 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002283 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002284 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002285 synchronized (mNetworkPoliciesSecondLock) {
2286 writePolicyAL();
2287 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002288 }
2289 }
2290
2291 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002292 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002293 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2294
Felipe Lemef0823852016-06-08 13:43:08 -07002295 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002296 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002297 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002298 }
2299
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002300 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002301 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002302 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2303
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002304 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002305 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002306 for (int i = 0; i < mUidPolicy.size(); i++) {
2307 final int uid = mUidPolicy.keyAt(i);
2308 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002309 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2310 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002311 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002312 }
2313 }
2314 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002315 return uids;
2316 }
2317
2318 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002319 * Removes any persistable state associated with given {@link UserHandle}, persisting
2320 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002321 */
Felipe Lemef0823852016-06-08 13:43:08 -07002322 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002323
Felipe Lemef0823852016-06-08 13:43:08 -07002324 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07002325 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002326
Felipe Lemea110eec2016-04-29 09:58:06 -07002327 // Remove entries from revoked default restricted background UID whitelist
2328 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2329 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2330 if (UserHandle.getUserId(uid) == userId) {
2331 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002332 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002333 }
2334 }
2335
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002336 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002337 int[] uids = new int[0];
2338 for (int i = 0; i < mUidPolicy.size(); i++) {
2339 final int uid = mUidPolicy.keyAt(i);
2340 if (UserHandle.getUserId(uid) == userId) {
2341 uids = appendInt(uids, uid);
2342 }
2343 }
2344
2345 if (uids.length > 0) {
2346 for (int uid : uids) {
2347 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002348 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002349 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002350 }
Felipe Lemef0823852016-06-08 13:43:08 -07002351 synchronized (mNetworkPoliciesSecondLock) {
2352 updateRulesForGlobalChangeAL(true);
2353 if (writePolicy && changed) {
2354 writePolicyAL();
2355 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002356 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002357 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002358 }
2359
2360 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002361 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002362 // TODO: create permission for observing network policy
2363 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002364 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002365 }
2366
2367 @Override
2368 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002369 // TODO: create permission for observing network policy
2370 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002371 mListeners.unregister(listener);
2372 }
2373
Jeff Sharkey1b861272011-05-22 00:34:52 -07002374 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002375 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002376 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2377
Felipe Leme6a05eee2016-02-19 14:43:51 -08002378 final long token = Binder.clearCallingIdentity();
2379 try {
2380 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002381 synchronized (mUidRulesFirstLock) {
2382 synchronized (mNetworkPoliciesSecondLock) {
2383 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002384 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002385 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002386 }
2387 } finally {
2388 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002389 }
2390 }
2391
Hugo Benichi446c9c92017-04-10 09:41:10 +09002392 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002393 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002394 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2395 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002396 }
2397
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002398 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002399 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002400 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002401 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002402 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2403 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2404 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002405 } catch (SecurityException e) {
2406 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002407
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002408 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2409 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2410 return new NetworkPolicy[0];
2411 }
Svet Ganov16a16892015-04-16 10:32:04 -07002412 }
2413
Felipe Lemef0823852016-06-08 13:43:08 -07002414 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002415 final int size = mNetworkPolicy.size();
2416 final NetworkPolicy[] policies = new NetworkPolicy[size];
2417 for (int i = 0; i < size; i++) {
2418 policies[i] = mNetworkPolicy.valueAt(i);
2419 }
2420 return policies;
2421 }
2422 }
2423
Felipe Lemef0823852016-06-08 13:43:08 -07002424 private void normalizePoliciesNL() {
2425 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002426 }
2427
Felipe Lemef0823852016-06-08 13:43:08 -07002428 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002429 final TelephonyManager tele = TelephonyManager.from(mContext);
2430 final String[] merged = tele.getMergedSubscriberIds();
2431
2432 mNetworkPolicy.clear();
2433 for (NetworkPolicy policy : policies) {
2434 // When two normalized templates conflict, prefer the most
2435 // restrictive policy
2436 policy.template = NetworkTemplate.normalize(policy.template, merged);
2437 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2438 if (existing == null || existing.compareTo(policy) > 0) {
2439 if (existing != null) {
2440 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2441 }
2442 mNetworkPolicy.put(policy.template, policy);
2443 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002444 }
2445 }
2446
2447 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002448 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002449 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002450
2451 final long token = Binder.clearCallingIdentity();
2452 try {
2453 performSnooze(template, TYPE_LIMIT);
2454 } finally {
2455 Binder.restoreCallingIdentity(token);
2456 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002457 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002458
Dianne Hackborn497175b2014-07-01 12:56:08 -07002459 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002460 maybeRefreshTrustedTime();
2461 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002462 synchronized (mUidRulesFirstLock) {
2463 synchronized (mNetworkPoliciesSecondLock) {
2464 // find and snooze local policy that matches
2465 final NetworkPolicy policy = mNetworkPolicy.get(template);
2466 if (policy == null) {
2467 throw new IllegalArgumentException("unable to find policy for " + template);
2468 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002469
Felipe Lemef0823852016-06-08 13:43:08 -07002470 switch (type) {
2471 case TYPE_WARNING:
2472 policy.lastWarningSnooze = currentTime;
2473 break;
2474 case TYPE_LIMIT:
2475 policy.lastLimitSnooze = currentTime;
2476 break;
2477 default:
2478 throw new IllegalArgumentException("unexpected type");
2479 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002480
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002481 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002482 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002483 }
2484 }
2485
2486 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002487 public void onTetheringChanged(String iface, boolean tethering) {
2488 // No need to enforce permission because setRestrictBackground() will do it.
2489 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002490 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002491 if (mRestrictBackground && tethering) {
2492 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2493 setRestrictBackground(false);
2494 }
2495 }
2496 }
2497
2498 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002499 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002500 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002501 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002502 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2503 final long token = Binder.clearCallingIdentity();
2504 try {
2505 maybeRefreshTrustedTime();
2506 synchronized (mUidRulesFirstLock) {
2507 if (restrictBackground == mRestrictBackground) {
2508 // Ideally, UI should never allow this scenario...
2509 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2510 return;
2511 }
2512 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002513 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002514
2515 } finally {
2516 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002517 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002518
Felipe Leme29e72ea2016-09-08 13:26:55 -07002519 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2520 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002521 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002522 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002523 }
2524 }
2525
Felipe Lemef0823852016-06-08 13:43:08 -07002526 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002527 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002528 final boolean oldRestrictBackground = mRestrictBackground;
2529 mRestrictBackground = restrictBackground;
2530 // Must whitelist foreground apps before turning data saver mode on.
2531 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2532 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002533 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002534 try {
2535 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2536 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2537 mRestrictBackground = oldRestrictBackground;
2538 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002539 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002540 return;
2541 }
2542 } catch (RemoteException e) {
2543 // ignored; service lives in system_server
2544 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002545
2546 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2547 mRestrictBackgroundChangedInBsm = true;
2548 }
Felipe Lemef0823852016-06-08 13:43:08 -07002549 synchronized (mNetworkPoliciesSecondLock) {
2550 updateNotificationsNL();
2551 writePolicyAL();
2552 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002553 }
2554
Felipe Lemeb85a6372016-01-14 16:16:16 -08002555 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002556 public int getRestrictBackgroundByCaller() {
2557 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2558 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002559
Felipe Lemef0823852016-06-08 13:43:08 -07002560 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002561 // Must clear identity because getUidPolicy() is restricted to system.
2562 final long token = Binder.clearCallingIdentity();
2563 final int policy;
2564 try {
2565 policy = getUidPolicy(uid);
2566 } finally {
2567 Binder.restoreCallingIdentity(token);
2568 }
2569 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2570 // App is blacklisted.
2571 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2572 }
Felipe Leme1b103232016-01-22 09:44:57 -08002573 if (!mRestrictBackground) {
2574 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2575 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002576 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002577 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2578 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2579 }
2580 }
2581
2582 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002583 public boolean getRestrictBackground() {
2584 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2585
Felipe Lemef0823852016-06-08 13:43:08 -07002586 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002587 return mRestrictBackground;
2588 }
2589 }
2590
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002591 @Override
2592 public void setDeviceIdleMode(boolean enabled) {
2593 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002594 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2595 try {
2596 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002597 if (mDeviceIdleMode == enabled) {
2598 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002599 }
Felipe Lemeea014392016-09-06 13:59:54 -07002600 mDeviceIdleMode = enabled;
2601 if (mSystemReady) {
2602 // Device idle change means we need to rebuild rules for all
2603 // known apps, so do a global refresh.
2604 updateRulesForRestrictPowerUL();
2605 }
2606 }
2607 if (enabled) {
2608 EventLogTags.writeDeviceIdleOnPhase("net");
2609 } else {
2610 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002611 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002612 } finally {
2613 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002614 }
2615 }
2616
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002617 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002618 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2619 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002620 final long token = Binder.clearCallingIdentity();
2621 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002622 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2623 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2624 for (WifiConfiguration config : configs) {
2625 if (Objects.equals(resolveNetworkId(config), networkId)) {
2626 config.meteredOverride = meteredOverride;
2627 wm.updateNetwork(config);
2628 }
2629 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002630 } finally {
2631 Binder.restoreCallingIdentity(token);
2632 }
2633 }
2634
Jeff Sharkey46645002011-07-27 21:11:21 -07002635 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002636 @Deprecated
2637 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2638 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2639 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2640 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002641 }
2642
Jeff Sharkey53313d72017-07-13 16:47:32 -06002643 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2644 // Verify they're not lying about package name
2645 mAppOps.checkPackage(callingUid, callingPackage);
2646
Jeff Sharkey53313d72017-07-13 16:47:32 -06002647 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002648 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002649 final long token = Binder.clearCallingIdentity();
2650 try {
2651 si = mContext.getSystemService(SubscriptionManager.class)
2652 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002653 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002654 } finally {
2655 Binder.restoreCallingIdentity(token);
2656 }
2657
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002658 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002659 if (si != null) {
2660 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2661 return;
2662 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002663 }
2664
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002665 // Second check: has the CarrierService delegated access?
2666 if (config != null) {
2667 final String overridePackage = config
2668 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2669 if (!TextUtils.isEmpty(overridePackage)
2670 && Objects.equals(overridePackage, callingPackage)) {
2671 return;
2672 }
2673 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002674
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002675 // Third check: is caller the fallback/default CarrierService?
2676 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2677 if (!TextUtils.isEmpty(defaultPackage)
2678 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002679 return;
2680 }
2681
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002682 // Final check: does the caller hold a permission?
2683 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002684 }
2685
2686 @Override
2687 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2688 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2689
Jeff Sharkey53313d72017-07-13 16:47:32 -06002690 final String fake = SystemProperties.get("fw.fake_plan");
2691 if (!TextUtils.isEmpty(fake)) {
2692 final List<SubscriptionPlan> plans = new ArrayList<>();
2693 if ("month_hard".equals(fake)) {
2694 plans.add(SubscriptionPlan.Builder
2695 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2696 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002697 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2698 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2699 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2700 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2701 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002702 plans.add(SubscriptionPlan.Builder
2703 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2704 .setTitle("G-Mobile Happy")
2705 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2706 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2707 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2708 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2709 .build());
2710 plans.add(SubscriptionPlan.Builder
2711 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2712 .setTitle("G-Mobile, Charged after limit")
2713 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2714 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2715 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2716 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2717 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002718 } else if ("month_soft".equals(fake)) {
2719 plans.add(SubscriptionPlan.Builder
2720 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2721 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2722 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2723 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002724 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2725 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2726 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2727 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2728 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002729 plans.add(SubscriptionPlan.Builder
2730 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2731 .setTitle("G-Mobile, Throttled after limit")
2732 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2733 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2734 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2735 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2736 .build());
2737 plans.add(SubscriptionPlan.Builder
2738 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2739 .setTitle("G-Mobile, No data connection after limit")
2740 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2741 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2742 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2743 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2744 .build());
2745
Jeff Sharkey53313d72017-07-13 16:47:32 -06002746 } else if ("month_none".equals(fake)) {
2747 plans.add(SubscriptionPlan.Builder
2748 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2749 .setTitle("G-Mobile")
2750 .build());
2751 } else if ("prepaid".equals(fake)) {
2752 plans.add(SubscriptionPlan.Builder
2753 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2754 ZonedDateTime.now().plusDays(10))
2755 .setTitle("G-Mobile")
2756 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2757 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2758 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2759 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2760 .build());
2761 } else if ("prepaid_crazy".equals(fake)) {
2762 plans.add(SubscriptionPlan.Builder
2763 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2764 ZonedDateTime.now().plusDays(10))
2765 .setTitle("G-Mobile Anytime")
2766 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2767 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2768 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2769 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2770 .build());
2771 plans.add(SubscriptionPlan.Builder
2772 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2773 ZonedDateTime.now().plusDays(20))
2774 .setTitle("G-Mobile Nickel Nights")
2775 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002776 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2777 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002778 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2779 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2780 .build());
2781 plans.add(SubscriptionPlan.Builder
2782 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2783 ZonedDateTime.now().plusDays(20))
2784 .setTitle("G-Mobile Bonus 3G")
2785 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002786 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002787 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2788 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2789 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2790 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002791 } else if ("unlimited".equals(fake)) {
2792 plans.add(SubscriptionPlan.Builder
2793 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2794 ZonedDateTime.now().plusDays(10))
2795 .setTitle("G-Mobile Awesome")
2796 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2797 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2798 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2799 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2800 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002801 }
2802 return plans.toArray(new SubscriptionPlan[plans.size()]);
2803 }
2804
Jeff Sharkey4635f102017-09-01 11:27:13 -06002805 synchronized (mNetworkPoliciesSecondLock) {
2806 // Only give out plan details to the package that defined them,
2807 // so that we don't risk leaking plans between apps. We always
2808 // let in core system components (like the Settings app).
2809 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2810 if (Objects.equals(ownerPackage, callingPackage)
2811 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2812 return mSubscriptionPlans.get(subId);
2813 } else {
2814 Log.w(TAG, "Not returning plans because caller " + callingPackage
2815 + " doesn't match owner " + ownerPackage);
2816 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002817 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002818 }
2819 }
2820
2821 @Override
2822 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2823 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2824
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002825 for (SubscriptionPlan plan : plans) {
2826 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002827 }
2828
2829 final long token = Binder.clearCallingIdentity();
2830 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002831 maybeRefreshTrustedTime();
2832 synchronized (mUidRulesFirstLock) {
2833 synchronized (mNetworkPoliciesSecondLock) {
2834 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002835 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002836
2837 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
2838 .getSubscriberId(subId);
2839 ensureActiveMobilePolicyAL(subId, subscriberId);
2840 maybeUpdateMobilePolicyCycleAL(subId);
2841 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002842 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002843 }
2844 } finally {
2845 Binder.restoreCallingIdentity(token);
2846 }
2847 }
2848
2849 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002850 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002851 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002852
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002853 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2854
Dianne Hackborn497175b2014-07-01 12:56:08 -07002855 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002856 for (String arg : args) {
2857 argSet.add(arg);
2858 }
2859
Felipe Lemef0823852016-06-08 13:43:08 -07002860 synchronized (mUidRulesFirstLock) {
2861 synchronized (mNetworkPoliciesSecondLock) {
2862 if (argSet.contains("--unsnooze")) {
2863 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2864 mNetworkPolicy.valueAt(i).clearSnooze();
2865 }
2866
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002867 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002868
2869 fout.println("Cleared snooze timestamps");
2870 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002871 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002872
Felipe Lemef0823852016-06-08 13:43:08 -07002873 fout.print("System ready: "); fout.println(mSystemReady);
2874 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2875 fout.print("Restrict power: "); fout.println(mRestrictPower);
2876 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002877 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2878
2879 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07002880 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002881 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002882 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2883 fout.println(mNetworkPolicy.valueAt(i).toString());
2884 }
2885 fout.decreaseIndent();
2886
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002887 fout.println();
2888 fout.println("Subscription plans:");
2889 fout.increaseIndent();
2890 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2891 final int subId = mSubscriptionPlans.keyAt(i);
2892 fout.println("Subscriber ID " + subId + ":");
2893 fout.increaseIndent();
2894 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2895 if (!ArrayUtils.isEmpty(plans)) {
2896 for (SubscriptionPlan plan : plans) {
2897 fout.println(plan);
2898 }
2899 }
2900 fout.decreaseIndent();
2901 }
2902 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002903
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002904 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07002905 fout.println("Policy for UIDs:");
2906 fout.increaseIndent();
2907 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002908 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002909 final int uid = mUidPolicy.keyAt(i);
2910 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002911 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002912 fout.print(uid);
2913 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002914 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002915 fout.println();
2916 }
2917 fout.decreaseIndent();
2918
2919 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2920 if (size > 0) {
2921 fout.println("Power save whitelist (except idle) app ids:");
2922 fout.increaseIndent();
2923 for (int i = 0; i < size; i++) {
2924 fout.print("UID=");
2925 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2926 fout.print(": ");
2927 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2928 fout.println();
2929 }
2930 fout.decreaseIndent();
2931 }
2932
2933 size = mPowerSaveWhitelistAppIds.size();
2934 if (size > 0) {
2935 fout.println("Power save whitelist app ids:");
2936 fout.increaseIndent();
2937 for (int i = 0; i < size; i++) {
2938 fout.print("UID=");
2939 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2940 fout.print(": ");
2941 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2942 fout.println();
2943 }
2944 fout.decreaseIndent();
2945 }
2946
Felipe Lemef0823852016-06-08 13:43:08 -07002947 size = mDefaultRestrictBackgroundWhitelistUids.size();
2948 if (size > 0) {
2949 fout.println("Default restrict background whitelist uids:");
2950 fout.increaseIndent();
2951 for (int i = 0; i < size; i++) {
2952 fout.print("UID=");
2953 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2954 fout.println();
2955 }
2956 fout.decreaseIndent();
2957 }
2958
2959 size = mRestrictBackgroundWhitelistRevokedUids.size();
2960 if (size > 0) {
2961 fout.println("Default restrict background whitelist uids revoked by users:");
2962 fout.increaseIndent();
2963 for (int i = 0; i < size; i++) {
2964 fout.print("UID=");
2965 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2966 fout.println();
2967 }
2968 fout.decreaseIndent();
2969 }
2970
2971 final SparseBooleanArray knownUids = new SparseBooleanArray();
2972 collectKeys(mUidState, knownUids);
2973 collectKeys(mUidRules, knownUids);
2974
2975 fout.println("Status for all known UIDs:");
2976 fout.increaseIndent();
2977 size = knownUids.size();
2978 for (int i = 0; i < size; i++) {
2979 final int uid = knownUids.keyAt(i);
2980 fout.print("UID=");
2981 fout.print(uid);
2982
2983 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2984 fout.print(" state=");
2985 fout.print(state);
2986 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2987 fout.print(" (fg)");
2988 } else {
2989 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2990 ? " (fg svc)" : " (bg)");
2991 }
2992
2993 final int uidRules = mUidRules.get(uid, RULE_NONE);
2994 fout.print(" rules=");
2995 fout.print(uidRulesToString(uidRules));
2996 fout.println();
2997 }
2998 fout.decreaseIndent();
2999
3000 fout.println("Status for just UIDs with rules:");
3001 fout.increaseIndent();
3002 size = mUidRules.size();
3003 for (int i = 0; i < size; i++) {
3004 final int uid = mUidRules.keyAt(i);
3005 fout.print("UID=");
3006 fout.print(uid);
3007 final int uidRules = mUidRules.get(uid, RULE_NONE);
3008 fout.print(" rules=");
3009 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003010 fout.println();
3011 }
3012 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003013
3014 fout.println("Observed uid state changes:");
3015 fout.increaseIndent();
3016 mObservedHistory.dumpUL(fout);
3017 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003018 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003019 }
3020 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003021
3022 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003023 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003024 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003025 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003026 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003027 }
3028
3029 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003030 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07003031 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3032
Felipe Lemef0823852016-06-08 13:43:08 -07003033 synchronized (mUidRulesFirstLock) {
3034 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003035 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003036 }
3037
Felipe Lemef0823852016-06-08 13:43:08 -07003038 private boolean isUidForegroundUL(int uid) {
3039 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07003040 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
3041 }
3042
Felipe Lemef0823852016-06-08 13:43:08 -07003043 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003044 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003045 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003046 }
3047
Felipe Lemef0823852016-06-08 13:43:08 -07003048 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003049 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3050 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3051 }
3052
Felipe Lemef0823852016-06-08 13:43:08 -07003053 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003054 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07003055 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003056 }
3057
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003058 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003059 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003060 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3061 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003062 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003063 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003064 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3065 try {
3066 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3067 if (oldUidState != uidState) {
3068 // state changed, push updated rules
3069 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003070 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3071 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3072 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003073 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003074 if (mDeviceIdleMode) {
3075 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003076 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003077 if (mRestrictPower) {
3078 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003079 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003080 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003081 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003082 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003083 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003084 } finally {
3085 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003086 }
3087 }
3088
Felipe Lemef0823852016-06-08 13:43:08 -07003089 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003090 final int index = mUidState.indexOfKey(uid);
3091 if (index >= 0) {
3092 final int oldUidState = mUidState.valueAt(index);
3093 mUidState.removeAt(index);
3094 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003095 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003096 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003097 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003098 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003099 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003100 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003101 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003102 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003103 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003104 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003105 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003106 }
3107 }
3108
Felipe Lemef28983d2016-03-25 12:18:23 -07003109 // adjust stats accounting based on foreground status
3110 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003111 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3112 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3113 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3114 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003115 try {
3116 mNetworkStats.setUidForeground(uid, uidForeground);
3117 } catch (RemoteException e) {
3118 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003119 } finally {
3120 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003121 }
3122 }
3123
Sudheer Shankac9d94072017-02-22 22:13:55 +00003124 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3125 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003126 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003127 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003128 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003129 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003130 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003131 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003132 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003133 }
3134
Felipe Lemef0823852016-06-08 13:43:08 -07003135 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003136 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3137 try {
3138 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3139 mUidFirewallPowerSaveRules);
3140 } finally {
3141 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3142 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003143 }
3144
Felipe Lemef0823852016-06-08 13:43:08 -07003145 void updateRuleForRestrictPowerUL(int uid) {
3146 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003147 }
3148
Felipe Lemef0823852016-06-08 13:43:08 -07003149 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003150 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3151 try {
3152 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3153 mUidFirewallDozableRules);
3154 } finally {
3155 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3156 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003157 }
3158
Felipe Lemef0823852016-06-08 13:43:08 -07003159 void updateRuleForDeviceIdleUL(int uid) {
3160 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003161 }
3162
Felipe Lemef28983d2016-03-25 12:18:23 -07003163 // NOTE: since both fw_dozable and fw_powersave uses the same map
3164 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003165 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003166 SparseIntArray rules) {
3167 if (enabled) {
3168 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003169 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003170 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003171 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003172 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003173 for (int ui = users.size() - 1; ui >= 0; ui--) {
3174 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003175 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3176 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3177 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3178 updateRulesForWhitelistedAppIds(uidRules,
3179 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003180 }
3181 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003182 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003183 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003184 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3185 }
3186 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003187 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
3188 } else {
3189 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003190 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003191 }
3192
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003193 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3194 final SparseBooleanArray whitelistedAppIds, int userId) {
3195 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3196 if (whitelistedAppIds.valueAt(i)) {
3197 final int appId = whitelistedAppIds.keyAt(i);
3198 final int uid = UserHandle.getUid(userId, appId);
3199 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3200 }
3201 }
3202 }
3203
3204 /**
3205 * @param deviceIdleMode if true then we don't consider
3206 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3207 * whitelisted.
3208 */
3209 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003210 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003211 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3212 || mPowerSaveWhitelistAppIds.get(appId);
3213 if (!deviceIdleMode) {
3214 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3215 }
3216 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003217 }
3218
Felipe Lemef28983d2016-03-25 12:18:23 -07003219 // NOTE: since both fw_dozable and fw_powersave uses the same map
3220 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003221 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003222 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003223 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3224 chain == FIREWALL_CHAIN_DOZABLE);
3225 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003226 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003227 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003228 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003229 }
3230 }
3231 }
3232
Felipe Lemef0823852016-06-08 13:43:08 -07003233 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003234 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3235 try {
3236 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3237 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003238
Felipe Leme873a83a2016-09-07 11:34:10 -07003239 // Fully update the app idle firewall chain.
3240 final List<UserInfo> users = mUserManager.getUsers();
3241 for (int ui = users.size() - 1; ui >= 0; ui--) {
3242 UserInfo user = users.get(ui);
3243 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3244 for (int uid : idleUids) {
3245 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3246 // quick check: if this uid doesn't have INTERNET permission, it
3247 // doesn't have network access anyway, so it is a waste to mess
3248 // with it here.
3249 if (hasInternetPermissions(uid)) {
3250 uidRules.put(uid, FIREWALL_RULE_DENY);
3251 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003252 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003253 }
3254 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003255
Felipe Lemebc853dd2016-09-08 13:26:55 -07003256 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003257 } finally {
3258 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3259 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003260 }
3261
Felipe Lemef0823852016-06-08 13:43:08 -07003262 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003263 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003264
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003265 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3266 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3267 }
3268 try {
3269 int appId = UserHandle.getAppId(uid);
3270 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3271 && !isUidForegroundOnRestrictPowerUL(uid)) {
3272 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3273 } else {
3274 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3275 }
3276 } finally {
3277 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003278 }
3279 }
3280
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003281 /**
3282 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3283 * changed.
3284 */
Felipe Lemef0823852016-06-08 13:43:08 -07003285 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003286 boolean paroled = mUsageStats.isAppIdleParoleOn();
3287 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003288 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003289
3290 int ruleCount = mUidFirewallStandbyRules.size();
3291 for (int i = 0; i < ruleCount; i++) {
3292 int uid = mUidFirewallStandbyRules.keyAt(i);
3293 int oldRules = mUidRules.get(uid);
3294 if (enableChain) {
3295 // Chain wasn't enabled before and the other power-related
3296 // chains are whitelists, so we can clear the
3297 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3298 // the effective rules result in blocking network access.
3299 oldRules &= MASK_METERED_NETWORKS;
3300 } else {
3301 // Skip if it had no restrictions to begin with
3302 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3303 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003304 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3305 if (newUidRules == RULE_NONE) {
3306 mUidRules.delete(uid);
3307 } else {
3308 mUidRules.put(uid, newUidRules);
3309 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003310 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003311 }
3312
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003313 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003314 * Update rules that might be changed by {@link #mRestrictBackground},
3315 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003316 */
Felipe Lemef0823852016-06-08 13:43:08 -07003317 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003318 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3319 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3320 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3321 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003322 try {
Felipe Leme09700462016-09-08 09:33:48 -07003323 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003324 updateRulesForRestrictPowerUL();
3325 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003326
Felipe Leme873a83a2016-09-07 11:34:10 -07003327 // If the set of restricted networks may have changed, re-evaluate those.
3328 if (restrictedNetworksChanged) {
3329 normalizePoliciesNL();
3330 updateNetworkRulesNL();
3331 }
3332 } finally {
3333 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003334 }
3335 }
3336
Felipe Leme09700462016-09-08 09:33:48 -07003337 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003338 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003339 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3340 try {
3341 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003342 updateRulesForPowerSaveUL();
3343 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3344 } finally {
3345 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3346 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003347 }
3348
Felipe Lemef0823852016-06-08 13:43:08 -07003349 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003350 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3351 try {
3352 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3353 } finally {
3354 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3355 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003356 }
3357
3358 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3359 private static final int TYPE_RESTRICT_POWER = 2;
3360 @Retention(RetentionPolicy.SOURCE)
3361 @IntDef(flag = false, value = {
3362 TYPE_RESTRICT_BACKGROUND,
3363 TYPE_RESTRICT_POWER,
3364 })
3365 public @interface RestrictType {
3366 }
3367
3368 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003369 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003370 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3371 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3372 }
3373 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003374 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003375
3376 final PackageManager pm = mContext.getPackageManager();
3377 final List<UserInfo> users;
3378 final List<ApplicationInfo> apps;
3379
3380 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3381 try {
3382 users = mUserManager.getUsers();
3383 } finally {
3384 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3385 }
3386 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3387 try {
3388 apps = pm.getInstalledApplications(
3389 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3390 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3391 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3392 } finally {
3393 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3394 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003395
Felipe Leme873a83a2016-09-07 11:34:10 -07003396 final int usersSize = users.size();
3397 final int appsSize = apps.size();
3398 for (int i = 0; i < usersSize; i++) {
3399 final UserInfo user = users.get(i);
3400 for (int j = 0; j < appsSize; j++) {
3401 final ApplicationInfo app = apps.get(j);
3402 final int uid = UserHandle.getUid(user.id, app.uid);
3403 switch (type) {
3404 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003405 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003406 break;
3407 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003408 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003409 break;
3410 default:
3411 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3412 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003413 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003414 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003415 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003416 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003417 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003418 }
3419
Felipe Lemef0823852016-06-08 13:43:08 -07003420 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003421 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08003422 for (int i = 0; i < users.size(); i++) {
3423 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08003424 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003425 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003426 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07003427 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07003428 updateRuleForAppIdleUL(uid);
3429 updateRuleForDeviceIdleUL(uid);
3430 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003431 // Update internal rules.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003432 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003433 }
3434 }
3435 }
3436
Felipe Leme70c57c22016-03-29 10:45:13 -07003437 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3438 // methods below could be merged into a isUidValidForRules() method.
3439 private boolean isUidValidForBlacklistRules(int uid) {
3440 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003441 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003442 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003443 return true;
3444 }
3445
3446 return false;
3447 }
3448
Felipe Leme70c57c22016-03-29 10:45:13 -07003449 private boolean isUidValidForWhitelistRules(int uid) {
3450 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3451 }
3452
Amith Yamasani15e472352015-04-24 19:06:07 -07003453 private boolean isUidIdle(int uid) {
3454 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3455 final int userId = UserHandle.getUserId(uid);
3456
songjinshi0655edd2016-05-18 19:55:32 +08003457 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003458 for (String packageName : packages) {
3459 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3460 return false;
3461 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003462 }
3463 }
3464 return true;
3465 }
3466
3467 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003468 * Checks if an uid has INTERNET permissions.
3469 * <p>
3470 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003471 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003472 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003473 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003474 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003475 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003476 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003477 }
3478 } catch (RemoteException e) {
3479 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003480 return true;
3481 }
3482
3483 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003484 * Clears all state - internal and external - associated with an UID.
3485 */
3486 private void onUidDeletedUL(int uid) {
3487 // First cleanup in-memory state synchronously...
3488 mUidRules.delete(uid);
3489 mUidPolicy.delete(uid);
3490 mUidFirewallStandbyRules.delete(uid);
3491 mUidFirewallDozableRules.delete(uid);
3492 mUidFirewallPowerSaveRules.delete(uid);
3493 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3494 mPowerSaveWhitelistAppIds.delete(uid);
3495 mPowerSaveTempWhitelistAppIds.delete(uid);
3496
3497 // ...then update iptables asynchronously.
3498 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3499 }
3500
3501 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003502 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003503 *
Felipe Leme781ba142016-05-09 16:24:48 -07003504 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003505 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003506 * <li>Doze mode
3507 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003508 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003509 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003510 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003511 *
3512 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003513 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003514 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003515 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003516 updateRuleForDeviceIdleUL(uid);
3517 updateRuleForAppIdleUL(uid);
3518 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003519
3520 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003521 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003522
3523 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003524 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003525 }
3526
Felipe Leme70c57c22016-03-29 10:45:13 -07003527 /**
3528 * Applies network rules to bandwidth controllers based on process state and user-defined
3529 * restrictions (blacklist / whitelist).
3530 *
3531 * <p>
3532 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3533 * networks:
3534 * <ul>
3535 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3536 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3537 * also blacklisted.
3538 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3539 * no UIDs other those whitelisted will have access.
3540 * <ul>
3541 *
3542 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3543 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3544 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3545 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003546 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003547 * {@link INetworkManagementService}, but this method should also be called in events (like
3548 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3549 * following rules should also be applied:
3550 *
3551 * <ul>
3552 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3553 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3554 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3555 * {@code bw_penalty_box}.
3556 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3557 * </ul>
3558 *
3559 * <p>For optimization, the rules are only applied on user apps that have internet access
3560 * permission, since there is no need to change the {@code iptables} rule if the app does not
3561 * have permission to use the internet.
3562 *
3563 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003564 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003565 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003566 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003567 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3568 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3569 "updateRulesForDataUsageRestrictionsUL: " + uid);
3570 }
3571 try {
3572 updateRulesForDataUsageRestrictionsULInner(uid);
3573 } finally {
3574 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3575 }
3576 }
3577
3578 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003579 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003580 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003581 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003582 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003583
Dianne Hackborn497175b2014-07-01 12:56:08 -07003584 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003585 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003586 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003587
Felipe Leme781ba142016-05-09 16:24:48 -07003588 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003589 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003590 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3591 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003592
Felipe Leme70c57c22016-03-29 10:45:13 -07003593 // First step: define the new rule based on user restrictions and foreground state.
3594 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003595 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3596 newRule = RULE_TEMPORARY_ALLOW_METERED;
3597 } else if (isWhitelisted) {
3598 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003599 }
3600 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003601 if (isBlacklisted) {
3602 newRule = RULE_REJECT_METERED;
3603 } else if (mRestrictBackground && isWhitelisted) {
3604 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003605 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003606 }
Felipe Leme781ba142016-05-09 16:24:48 -07003607 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003608
Felipe Lemef28983d2016-03-25 12:18:23 -07003609 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003610 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003611 + ": isForeground=" +isForeground
3612 + ", isBlacklisted=" + isBlacklisted
3613 + ", isWhitelisted=" + isWhitelisted
3614 + ", oldRule=" + uidRulesToString(oldRule)
3615 + ", newRule=" + uidRulesToString(newRule)
3616 + ", newUidRules=" + uidRulesToString(newUidRules)
3617 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003618 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003619
Felipe Leme46c4fc32016-05-04 09:21:43 -07003620 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003621 mUidRules.delete(uid);
3622 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003623 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003624 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003625
Felipe Leme70c57c22016-03-29 10:45:13 -07003626 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003627 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003628 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003629 // Temporarily whitelist foreground app, removing from blacklist if necessary
3630 // (since bw_penalty_box prevails over bw_happy_box).
3631
3632 setMeteredNetworkWhitelist(uid, true);
3633 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3634 // but ideally it should be just:
3635 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003636 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003637 setMeteredNetworkBlacklist(uid, false);
3638 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003639 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003640 // Remove temporary whitelist from app that is not on foreground anymore.
3641
3642 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3643 // but ideally they should be just:
3644 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3645 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003646 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003647 setMeteredNetworkWhitelist(uid, false);
3648 }
Felipe Leme781ba142016-05-09 16:24:48 -07003649 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003650 setMeteredNetworkBlacklist(uid, true);
3651 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003652 } else if (hasRule(newRule, RULE_REJECT_METERED)
3653 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003654 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003655 setMeteredNetworkBlacklist(uid, isBlacklisted);
Hugo Benichi2966c182017-03-28 17:17:13 +09003656 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003657 // Since blacklist prevails over whitelist, we need to handle the special case
3658 // where app is whitelisted and blacklisted at the same time (although such
3659 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003660 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003661 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003662 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3663 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003664 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003665 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003666 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003667 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003668 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3669 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003670 + ", whitelisted=" + isWhitelisted
3671 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003672 + ", newRule=" + uidRulesToString(newUidRules)
3673 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003674 }
Felipe Leme781ba142016-05-09 16:24:48 -07003675
Sudheer Shankac9d94072017-02-22 22:13:55 +00003676 // Dispatch changed rule to existing listeners.
3677 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003678 }
3679 }
3680
3681 /**
3682 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3683 * listeners in case of change.
3684 * <p>
3685 * There are 3 power-related rules that affects whether an app has background access on
3686 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3687 * restriction, it's added to the equivalent firewall chain:
3688 * <ul>
3689 * <li>App is idle: {@code fw_standby} firewall chain.
3690 * <li>Device is idle: {@code fw_dozable} firewall chain.
3691 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3692 * </ul>
3693 * <p>
3694 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3695 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3696 * <p>
3697 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3698 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003699 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003700 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3701
Sudheer Shankac9d94072017-02-22 22:13:55 +00003702 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003703
Sudheer Shankac9d94072017-02-22 22:13:55 +00003704 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003705 mUidRules.delete(uid);
3706 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003707 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003708 }
3709 }
3710
3711 /**
3712 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3713 *
3714 * @param uid the uid of the app to update rules for
3715 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3716 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3717 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003718 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003719 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003720 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003721 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3722 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3723 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3724 + (paroled ? "P" : "-"));
3725 }
3726 try {
3727 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3728 } finally {
3729 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3730 }
3731 }
3732
3733 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003734 if (!isUidValidForBlacklistRules(uid)) {
3735 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003736 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003737 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003738
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003739 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003740 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003741 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003742
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003743 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003744 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3745 int newRule = RULE_NONE;
3746
3747 // First step: define the new rule based on user restrictions and foreground state.
3748
3749 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3750 // by considering the foreground and non-foreground states.
3751 if (isForeground) {
3752 if (restrictMode) {
3753 newRule = RULE_ALLOW_ALL;
3754 }
3755 } else if (restrictMode) {
3756 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3757 }
3758
3759 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3760
3761 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003762 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003763 + ", isIdle: " + isIdle
3764 + ", mRestrictPower: " + mRestrictPower
3765 + ", mDeviceIdleMode: " + mDeviceIdleMode
3766 + ", isForeground=" + isForeground
3767 + ", isWhitelisted=" + isWhitelisted
3768 + ", oldRule=" + uidRulesToString(oldRule)
3769 + ", newRule=" + uidRulesToString(newRule)
3770 + ", newUidRules=" + uidRulesToString(newUidRules)
3771 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3772 }
3773
Felipe Leme781ba142016-05-09 16:24:48 -07003774 // Second step: notify listeners if state changed.
3775 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003776 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003777 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003778 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003779 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3780 } else {
3781 // All scenarios should have been covered above
3782 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3783 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003784 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003785 + ", newRule=" + uidRulesToString(newUidRules)
3786 + ", oldRule=" + uidRulesToString(oldUidRules));
3787 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003788 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003789 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003790
Sudheer Shankac9d94072017-02-22 22:13:55 +00003791 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003792 }
3793
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003794 private class AppIdleStateChangeListener
3795 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3796
3797 @Override
3798 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3799 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003800 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3801 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003802 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003803 synchronized (mUidRulesFirstLock) {
3804 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003805 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003806 }
3807 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003808 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003809 }
3810
3811 @Override
3812 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003813 synchronized (mUidRulesFirstLock) {
3814 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003815 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003816 }
3817 }
3818
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003819 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3820 if (listener != null) {
3821 try {
3822 listener.onUidRulesChanged(uid, uidRules);
3823 } catch (RemoteException ignored) {
3824 }
3825 }
3826 }
3827
3828 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3829 String[] meteredIfaces) {
3830 if (listener != null) {
3831 try {
3832 listener.onMeteredIfacesChanged(meteredIfaces);
3833 } catch (RemoteException ignored) {
3834 }
3835 }
3836 }
3837
3838 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3839 boolean restrictBackground) {
3840 if (listener != null) {
3841 try {
3842 listener.onRestrictBackgroundChanged(restrictBackground);
3843 } catch (RemoteException ignored) {
3844 }
3845 }
3846 }
3847
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003848 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3849 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003850 if (listener != null) {
3851 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003852 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003853 } catch (RemoteException ignored) {
3854 }
3855 }
3856 }
3857
Makoto Onuki8e777332017-03-28 11:25:47 -07003858 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003859 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003860 public boolean handleMessage(Message msg) {
3861 switch (msg.what) {
3862 case MSG_RULES_CHANGED: {
3863 final int uid = msg.arg1;
3864 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003865 final int length = mListeners.beginBroadcast();
3866 for (int i = 0; i < length; i++) {
3867 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3868 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003869 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003870 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003871 return true;
3872 }
3873 case MSG_METERED_IFACES_CHANGED: {
3874 final String[] meteredIfaces = (String[]) msg.obj;
3875 final int length = mListeners.beginBroadcast();
3876 for (int i = 0; i < length; i++) {
3877 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003878 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003879 }
3880 mListeners.finishBroadcast();
3881 return true;
3882 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003883 case MSG_LIMIT_REACHED: {
3884 final String iface = (String) msg.obj;
3885
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003886 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003887 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003888 if (mMeteredIfaces.contains(iface)) {
3889 try {
3890 // force stats update to make sure we have
3891 // numbers that caused alert to trigger.
3892 mNetworkStats.forceUpdate();
3893 } catch (RemoteException e) {
3894 // ignored; service lives in system_server
3895 }
3896
Felipe Lemef0823852016-06-08 13:43:08 -07003897 updateNetworkEnabledNL();
3898 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003899 }
3900 }
3901 return true;
3902 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003903 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3904 final boolean restrictBackground = msg.arg1 != 0;
3905 final int length = mListeners.beginBroadcast();
3906 for (int i = 0; i < length; i++) {
3907 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003908 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003909 }
3910 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003911 final Intent intent =
3912 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3913 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3914 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3915 return true;
3916 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003917 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003918 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003919 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003920 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003921 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07003922 final int length = mListeners.beginBroadcast();
3923 for (int i = 0; i < length; i++) {
3924 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003925 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003926 }
3927 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003928 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3929 if (notifyApp.booleanValue()) {
3930 broadcastRestrictBackgroundChanged(uid, notifyApp);
3931 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003932 return true;
3933 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003934 case MSG_ADVISE_PERSIST_THRESHOLD: {
3935 final long lowestRule = (Long) msg.obj;
3936 try {
3937 // make sure stats are recorded frequently enough; we aim
3938 // for 2MB threshold for 2GB/month rules.
3939 final long persistThreshold = lowestRule / 1000;
3940 mNetworkStats.advisePersistThreshold(persistThreshold);
3941 } catch (RemoteException e) {
3942 // ignored; service lives in system_server
3943 }
3944 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003945 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003946 case MSG_UPDATE_INTERFACE_QUOTA: {
3947 removeInterfaceQuota((String) msg.obj);
3948 // int params need to be stitched back into a long
3949 setInterfaceQuota((String) msg.obj,
3950 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3951 return true;
3952 }
3953 case MSG_REMOVE_INTERFACE_QUOTA: {
3954 removeInterfaceQuota((String) msg.obj);
3955 return true;
3956 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003957 case MSG_SET_FIREWALL_RULES: {
3958 final int chain = msg.arg1;
3959 final int toggle = msg.arg2;
3960 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3961 if (uidRules != null) {
3962 setUidFirewallRules(chain, uidRules);
3963 }
3964 if (toggle != CHAIN_TOGGLE_NONE) {
3965 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3966 }
3967 return true;
3968 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003969 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3970 resetUidFirewallRules(msg.arg1);
3971 return true;
3972 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003973 default: {
3974 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003975 }
3976 }
3977 }
Makoto Onuki8e777332017-03-28 11:25:47 -07003978 };
3979
3980 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
3981 @Override
3982 public boolean handleMessage(Message msg) {
3983 switch (msg.what) {
3984 case UID_MSG_STATE_CHANGED: {
3985 final int uid = msg.arg1;
3986 final int procState = msg.arg2;
3987 final long procStateSeq = (Long) msg.obj;
3988
3989 handleUidChanged(uid, procState, procStateSeq);
3990 return true;
3991 }
3992 case UID_MSG_GONE: {
3993 final int uid = msg.arg1;
3994 handleUidGone(uid);
3995 return true;
3996 }
3997 default: {
3998 return false;
3999 }
4000 }
4001 }
Felipe Leme57e3d312016-08-23 14:42:52 -07004002
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004003 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004004
Makoto Onuki8e777332017-03-28 11:25:47 -07004005 void handleUidChanged(int uid, int procState, long procStateSeq) {
4006 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4007 try {
4008 synchronized (mUidRulesFirstLock) {
4009 // We received a uid state change callback, add it to the history so that it
4010 // will be useful for debugging.
4011 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
4012 // Now update the network policy rules as per the updated uid state.
4013 updateUidStateUL(uid, procState);
4014 // Updating the network rules is done, so notify AMS about this.
4015 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4016 }
4017 } finally {
4018 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4019 }
4020 }
4021
4022 void handleUidGone(int uid) {
4023 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4024 try {
4025 synchronized (mUidRulesFirstLock) {
4026 removeUidStateUL(uid);
4027 }
4028 } finally {
4029 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4030 }
4031 }
4032
Felipe Leme57e3d312016-08-23 14:42:52 -07004033 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4034 final PackageManager pm = mContext.getPackageManager();
4035 final String[] packages = pm.getPackagesForUid(uid);
4036 if (packages != null) {
4037 final int userId = UserHandle.getUserId(uid);
4038 for (String packageName : packages) {
4039 final Intent intent =
4040 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4041 intent.setPackage(packageName);
4042 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4043 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4044 }
4045 }
4046 }
4047
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004048 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4049 // long quotaBytes split up into two ints to fit in message
4050 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4051 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4052 }
4053
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004054 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004055 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004056 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004057 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004058 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004059 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004060 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004061 }
4062 }
4063
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004064 private void removeInterfaceQuotaAsync(String iface) {
4065 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4066 }
4067
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004068 private void removeInterfaceQuota(String iface) {
4069 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004070 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004071 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004072 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004073 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004074 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004075 }
4076 }
4077
Felipe Leme70c57c22016-03-29 10:45:13 -07004078 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4079 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004080 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004081 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004082 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004083 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4084 } catch (RemoteException e) {
4085 // ignored; service lives in system_server
4086 }
4087 }
4088
4089 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4090 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4091 try {
4092 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4093 } catch (IllegalStateException e) {
4094 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004095 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004096 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004097 }
4098 }
4099
Felipe Lemebc853dd2016-09-08 13:26:55 -07004100 private static final int CHAIN_TOGGLE_NONE = 0;
4101 private static final int CHAIN_TOGGLE_ENABLE = 1;
4102 private static final int CHAIN_TOGGLE_DISABLE = 2;
4103 @Retention(RetentionPolicy.SOURCE)
4104 @IntDef(flag = false, value = {
4105 CHAIN_TOGGLE_NONE,
4106 CHAIN_TOGGLE_ENABLE,
4107 CHAIN_TOGGLE_DISABLE
4108 })
4109 public @interface ChainToggleType {
4110 }
4111
4112 /**
4113 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
4114 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
4115 *
4116 * @param chain firewall chain.
4117 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4118 * @param toggle whether the chain should be enabled, disabled, or not changed.
4119 */
4120 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
4121 @ChainToggleType int toggle) {
4122 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
4123 }
4124
Amith Yamasani15e472352015-04-24 19:06:07 -07004125 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004126 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4127 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4128 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004129 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004130 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004131 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004132 int size = uidRules.size();
4133 int[] uids = new int[size];
4134 int[] rules = new int[size];
4135 for(int index = size - 1; index >= 0; --index) {
4136 uids[index] = uidRules.keyAt(index);
4137 rules[index] = uidRules.valueAt(index);
4138 }
4139 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004140 } catch (IllegalStateException e) {
4141 Log.wtf(TAG, "problem setting firewall uid rules", e);
4142 } catch (RemoteException e) {
4143 // ignored; service lives in system_server
4144 }
4145 }
4146
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004147 /**
4148 * Add or remove a uid to the firewall blacklist for all network ifaces.
4149 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004150 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004151 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4152 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4153 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004154 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004155 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004156 if (chain == FIREWALL_CHAIN_DOZABLE) {
4157 mUidFirewallDozableRules.put(uid, rule);
4158 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4159 mUidFirewallStandbyRules.put(uid, rule);
4160 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4161 mUidFirewallPowerSaveRules.put(uid, rule);
4162 }
4163
4164 try {
4165 mNetworkManager.setFirewallUidRule(chain, uid, rule);
4166 } catch (IllegalStateException e) {
4167 Log.wtf(TAG, "problem setting firewall uid rules", e);
4168 } catch (RemoteException e) {
4169 // ignored; service lives in system_server
4170 }
4171 } finally {
4172 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004173 }
4174 }
4175
4176 /**
4177 * Add or remove a uid to the firewall blacklist for all network ifaces.
4178 */
Felipe Lemef0823852016-06-08 13:43:08 -07004179 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004180 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4181 mFirewallChainStates.get(chain) == enable) {
4182 // All is the same, nothing to do.
4183 return;
4184 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004185 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004186 try {
4187 mNetworkManager.setFirewallChainEnabled(chain, enable);
4188 } catch (IllegalStateException e) {
4189 Log.wtf(TAG, "problem enable firewall chain", e);
4190 } catch (RemoteException e) {
4191 // ignored; service lives in system_server
4192 }
4193 }
4194
Felipe Leme03e95e22016-09-09 09:25:31 -07004195 /**
4196 * Resets all firewall rules associated with an UID.
4197 */
4198 private void resetUidFirewallRules(int uid) {
4199 try {
4200 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4201 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4202 mNetworkManager
4203 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4204 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4205 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4206 } catch (IllegalStateException e) {
4207 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4208 } catch (RemoteException e) {
4209 // ignored; service lives in system_server
4210 }
4211 }
4212
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004213 private long getTotalBytes(NetworkTemplate template, long start, long end) {
4214 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004215 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004216 } catch (RuntimeException e) {
4217 Slog.w(TAG, "problem reading network stats: " + e);
4218 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004219 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004220 // ignored; service lives in system_server
4221 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004222 }
4223 }
4224
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004225 private boolean isBandwidthControlEnabled() {
4226 final long token = Binder.clearCallingIdentity();
4227 try {
4228 return mNetworkManager.isBandwidthControlEnabled();
4229 } catch (RemoteException e) {
4230 // ignored; service lives in system_server
4231 return false;
4232 } finally {
4233 Binder.restoreCallingIdentity(token);
4234 }
4235 }
4236
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004237 /**
4238 * Try refreshing {@link #mTime} when stale.
4239 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07004240 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004241 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004242 mTime.forceRefresh();
4243 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004244 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004245
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004246 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004247 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
4248 }
4249
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004250 private static Intent buildAllowBackgroundDataIntent() {
4251 return new Intent(ACTION_ALLOW_BACKGROUND);
4252 }
4253
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004254 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4255 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
4256 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4257 return intent;
4258 }
4259
Wei Liu546cb772016-07-21 16:19:01 -07004260 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004261 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004262 intent.setComponent(ComponentName.unflattenFromString(
4263 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004264 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4265 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4266 return intent;
4267 }
4268
Wei Liu546cb772016-07-21 16:19:01 -07004269 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004270 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004271 intent.setComponent(ComponentName.unflattenFromString(
4272 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004273 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4274 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4275 return intent;
4276 }
4277
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004278 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004279 public void addIdleHandler(IdleHandler handler) {
4280 mHandler.getLooper().getQueue().addIdleHandler(handler);
4281 }
4282
jackqdyulei29c82ab2017-03-10 14:09:16 -08004283 @VisibleForTesting
4284 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4285 mRestrictBackgroundPowerState = result;
4286
4287 boolean restrictBackground = result.batterySaverEnabled;
4288 boolean shouldInvokeRestrictBackground;
4289 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4290 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4291
4292 if (result.globalBatterySaverEnabled) {
4293 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4294 // turn it on.
4295 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4296 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4297 localRestrictBgChangedInBsm = false;
4298 } else {
4299 // Try to restore the restrictBackground if it doesn't change in bsm
4300 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4301 restrictBackground = mRestrictBackgroundBeforeBsm;
4302 }
4303
4304 if (shouldInvokeRestrictBackground) {
4305 setRestrictBackground(restrictBackground);
4306 }
4307
4308 // Change it at last so setRestrictBackground() won't affect this variable
4309 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4310 }
4311
Jeff Sharkey1b861272011-05-22 00:34:52 -07004312 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4313 final int size = source.size();
4314 for (int i = 0; i < size; i++) {
4315 target.put(source.keyAt(i), true);
4316 }
4317 }
4318
Stuart Scottf1fb3972015-04-02 18:00:02 -07004319 @Override
4320 public void factoryReset(String subscriber) {
4321 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4322
Stuart Scotte3e314d2015-04-20 14:07:45 -07004323 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4324 return;
4325 }
4326
Stuart Scottf1fb3972015-04-02 18:00:02 -07004327 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004328 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004329 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4330 for (NetworkPolicy policy : policies) {
4331 if (policy.template.equals(template)) {
4332 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4333 policy.inferred = false;
4334 policy.clearSnooze();
4335 }
4336 }
4337 setNetworkPolicies(policies);
4338
4339 // Turn restrict background data off
4340 setRestrictBackground(false);
4341
Stuart Scotte3e314d2015-04-20 14:07:45 -07004342 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4343 // Remove app's "restrict background data" flag
4344 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4345 setUidPolicy(uid, POLICY_NONE);
4346 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004347 }
4348 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004349
Sudheer Shankab8f23162017-08-04 13:30:10 -07004350 @Override
4351 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4352 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4353 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4354 }
4355
4356 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4357 final int uidRules;
4358 final boolean isBackgroundRestricted;
4359 synchronized (mUidRulesFirstLock) {
4360 uidRules = mUidRules.get(uid, RULE_NONE);
4361 isBackgroundRestricted = mRestrictBackground;
4362 }
4363 if (hasRule(uidRules, RULE_REJECT_ALL)) {
4364 if (LOGV) logUidStatus(uid, "blocked by power restrictions");
4365 return true;
4366 }
4367 if (!isNetworkMetered) {
4368 if (LOGV) logUidStatus(uid, "allowed on unmetered network");
4369 return false;
4370 }
4371 if (hasRule(uidRules, RULE_REJECT_METERED)) {
4372 if (LOGV) logUidStatus(uid, "blacklisted on metered network");
4373 return true;
4374 }
4375 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4376 if (LOGV) logUidStatus(uid, "whitelisted on metered network");
4377 return false;
4378 }
4379 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4380 if (LOGV) logUidStatus(uid, "temporary whitelisted on metered network");
4381 return false;
4382 }
4383 if (isBackgroundRestricted) {
4384 if (LOGV) logUidStatus(uid, "blocked when background is restricted");
4385 return true;
4386 }
4387 if (LOGV) logUidStatus(uid, "allowed by default");
4388 return false;
4389 }
4390
Felipe Lemed17fda42016-04-29 11:12:45 -07004391 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4392
4393 @Override
4394 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004395 synchronized (mUidRulesFirstLock) {
4396 boolean changed = removeUserStateUL(userId, false);
4397 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004398 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004399 synchronized (mNetworkPoliciesSecondLock) {
4400 writePolicyAL();
4401 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004402 }
4403 }
4404 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004405
4406 /**
4407 * @return true if the given uid is restricted from doing networking on metered networks.
4408 */
4409 @Override
4410 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4411 final int uidRules;
4412 final boolean isBackgroundRestricted;
4413 synchronized (mUidRulesFirstLock) {
4414 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4415 isBackgroundRestricted = mRestrictBackground;
4416 }
4417 return isBackgroundRestricted
4418 && !hasRule(uidRules, RULE_ALLOW_METERED)
4419 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4420 }
4421
4422 /**
4423 * @return true if networking is blocked on the given interface for the given uid according
4424 * to current networking policies.
4425 */
4426 @Override
4427 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004428 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004429 synchronized (mNetworkPoliciesSecondLock) {
4430 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004431 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004432 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004433 }
4434 }
4435
4436 private static boolean hasRule(int uidRules, int rule) {
4437 return (uidRules & rule) != 0;
4438 }
4439
4440 private static void logUidStatus(int uid, String descr) {
4441 Slog.d(TAG, String.format("uid %d is %s", uid, descr));
Felipe Lemed17fda42016-04-29 11:12:45 -07004442 }
Sudheer Shankae7361852017-03-07 11:51:46 -08004443
4444 /**
4445 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
4446 * (uid, procStateSeq) pairs.
4447 */
4448 @VisibleForTesting
4449 public static final class ProcStateSeqHistory {
4450 private static final int INVALID_UID = -1;
4451
4452 /**
4453 * Denotes maximum number of items this history can hold.
4454 */
4455 private final int mMaxCapacity;
4456 /**
4457 * Used for storing the uid information.
4458 */
4459 private final int[] mUids;
4460 /**
4461 * Used for storing the sequence numbers associated with {@link #mUids}.
4462 */
4463 private final long[] mProcStateSeqs;
4464 /**
4465 * Points to the next available slot for writing (uid, procStateSeq) pair.
4466 */
4467 private int mHistoryNext;
4468
4469 public ProcStateSeqHistory(int maxCapacity) {
4470 mMaxCapacity = maxCapacity;
4471 mUids = new int[mMaxCapacity];
4472 Arrays.fill(mUids, INVALID_UID);
4473 mProcStateSeqs = new long[mMaxCapacity];
4474 }
4475
4476 @GuardedBy("mUidRulesFirstLock")
4477 public void addProcStateSeqUL(int uid, long procStateSeq) {
4478 mUids[mHistoryNext] = uid;
4479 mProcStateSeqs[mHistoryNext] = procStateSeq;
4480 mHistoryNext = increaseNext(mHistoryNext, 1);
4481 }
4482
4483 @GuardedBy("mUidRulesFirstLock")
4484 public void dumpUL(IndentingPrintWriter fout) {
4485 if (mUids[0] == INVALID_UID) {
4486 fout.println("NONE");
4487 return;
4488 }
4489 int index = mHistoryNext;
4490 do {
4491 index = increaseNext(index, -1);
4492 if (mUids[index] == INVALID_UID) {
4493 break;
4494 }
4495 fout.println(getString(mUids[index], mProcStateSeqs[index]));
4496 } while (index != mHistoryNext);
4497 }
4498
4499 public static String getString(int uid, long procStateSeq) {
Sudheer Shankadb9aaf032017-06-19 19:05:31 -07004500 return "UID=" + uid + " Seq=" + procStateSeq;
Sudheer Shankae7361852017-03-07 11:51:46 -08004501 }
4502
4503 private int increaseNext(int next, int increment) {
4504 next += increment;
4505 if (next >= mMaxCapacity) {
4506 next = 0;
4507 } else if (next < 0) {
4508 next = mMaxCapacity - 1;
4509 }
4510 return next;
4511 }
4512 }
Chris Wren193ae6b2017-03-31 15:17:11 -04004513
4514 private class NotificationId {
4515 private final String mTag;
4516 private final int mId;
4517
4518 NotificationId(NetworkPolicy policy, int type) {
4519 mTag = buildNotificationTag(policy, type);
4520 mId = type;
4521 }
4522
4523 @Override
4524 public boolean equals(Object o) {
4525 if (this == o) return true;
4526 if (!(o instanceof NotificationId)) return false;
4527 NotificationId that = (NotificationId) o;
4528 return Objects.equals(mTag, that.mTag);
4529 }
4530
4531 @Override
4532 public int hashCode() {
4533 return Objects.hash(mTag);
4534 }
4535
4536 /**
4537 * Build unique tag that identifies an active {@link NetworkPolicy}
4538 * notification of a specific type, like {@link #TYPE_LIMIT}.
4539 */
4540 private String buildNotificationTag(NetworkPolicy policy, int type) {
4541 return TAG + ":" + policy.template.hashCode() + ":" + type;
4542 }
4543
4544 public String getTag() {
4545 return mTag;
4546 }
4547
4548 public int getId() {
4549 return mId;
4550 }
4551 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004552}