blob: 93458c8daf9ca49f5a78d30354fe939efd76f8dc [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 Sharkey22c055e2011-06-12 21:13:51 -070036import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070037import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070038import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070039import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070040import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080041import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070042import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
43import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070044import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070045import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060046import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
47import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
Felipe Leme46b451f2016-08-19 08:46:17 -070048import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070049import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070050import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070051import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070053import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070054import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070055import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070056import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080057import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
58import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060059import static android.net.NetworkPolicyManager.resolveNetworkId;
Felipe Lemeb146f762016-08-19 09:52:16 -070060import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070061import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070062import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
63import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070064import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
65import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070066import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080067import static android.net.TrafficStats.MB_IN_BYTES;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070068import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070069import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060070import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070071import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080072
Jeff Sharkey854b2b12012-04-13 16:03:40 -070073import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070074import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070075import static com.android.internal.util.XmlUtils.readBooleanAttribute;
76import static com.android.internal.util.XmlUtils.readIntAttribute;
77import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060078import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070079import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
80import static com.android.internal.util.XmlUtils.writeIntAttribute;
81import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060082import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070083import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070084import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060085
Jeff Sharkey21c9c452011-06-07 12:26:43 -070086import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080087import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070088import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070089
Dianne Hackborn88e98df2015-03-23 13:29:14 -070090import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070091import android.annotation.IntDef;
Felipe Lemebc853dd2016-09-08 13:26:55 -070092import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -070093import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -080094import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070095import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070096import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070097import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070098import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070099import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700100import android.app.Notification;
101import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700102import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700103import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700104import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700105import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700106import android.content.Intent;
107import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700108import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700109import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700110import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700111import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700112import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700113import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700114import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700115import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700116import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700117import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700118import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700119import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700120import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700121import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700122import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600123import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700124import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700125import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700126import android.net.NetworkTemplate;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600127import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700128import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700129import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700130import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700131import android.os.Environment;
132import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700133import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700134import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700135import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700136import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700137import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700138import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700139import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700140import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600141import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800142import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700143import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700144import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600145import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700146import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700147import android.os.ShellCallback;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600148import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700149import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700150import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700151import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700152import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100153import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700154import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600155import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800156import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600157import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700158import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400159import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700160import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700161import android.util.ArrayMap;
162import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700163import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700164import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700165import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700166import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600167import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700168import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600169import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700170import android.util.SparseBooleanArray;
171import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700172import android.util.TrustedTime;
173import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700174
Jeff Sharkey497e4432011-06-14 17:27:29 -0700175import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700176import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800177import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400178import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500179import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700180import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800181import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600182import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700183import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700184import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600185import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700186import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700187import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700188import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800189import com.android.server.SystemConfig;
jackqdyulei455e90a2017-02-09 15:29:16 -0800190import com.android.server.power.BatterySaverPolicy.ServiceType;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600191
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600192import libcore.io.IoUtils;
193
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700194import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700195
196import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700197import org.xmlpull.v1.XmlSerializer;
198
199import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700200import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700201import java.io.FileInputStream;
202import java.io.FileNotFoundException;
203import java.io.FileOutputStream;
204import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700205import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700206import java.lang.annotation.Retention;
207import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100208import java.nio.charset.StandardCharsets;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600209import java.time.ZoneId;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600210import java.time.ZonedDateTime;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700211import java.util.ArrayList;
212import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700213import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600214import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400215import java.util.Objects;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800216import java.util.concurrent.CountDownLatch;
217import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700218
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700219/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700220 * Service that maintains low-level network policy rules, using
221 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700222 * <p>
223 * Derives active rules by combining a given policy with other system status,
224 * and delivers to listeners, such as {@link ConnectivityManager}, for
225 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700226 *
227 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000228 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700229 * <ul>
230 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
231 * rules).
232 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
233 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000234 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
235 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700236 * </ul>
237 *
238 * <p>
239 * As such, methods that require synchronization have the following prefixes:
240 * <ul>
241 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
242 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000243 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
244 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700245 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700246 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700247public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800248 static final String TAG = "NetworkPolicy";
Hugo Benichi5d2f2b52017-04-07 08:53:25 +0900249 private static final boolean LOGD = false;
250 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700251
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700252 private static final int VERSION_INIT = 1;
253 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700254 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800255 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800256 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800257 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700258 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700259 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700260 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700261 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600262 private static final int VERSION_ADDED_CYCLE = 11;
263 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700264
Sudheer Shankae7361852017-03-07 11:51:46 -0800265 /**
266 * Max items written to {@link #ProcStateSeqHistory}.
267 */
268 @VisibleForTesting
269 public static final int MAX_PROC_STATE_SEQ_HISTORY =
270 ActivityManager.isLowRamDeviceStatic() ? 50 : 200;
271
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800272 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400273 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800274 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400275 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800276 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400277 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700278
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700279 private static final String TAG_POLICY_LIST = "policy-list";
280 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600281 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700282 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700283 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800284 private static final String TAG_WHITELIST = "whitelist";
285 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800286 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700287
288 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700289 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700290 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
291 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700292 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600293 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
294 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
295 private static final String ATTR_CYCLE_START = "cycleStart";
296 private static final String ATTR_CYCLE_END = "cycleEnd";
297 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700298 private static final String ATTR_WARNING_BYTES = "warningBytes";
299 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700300 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800301 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
302 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800303 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700304 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700305 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700306 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700307 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600308 private static final String ATTR_SUB_ID = "subId";
309 private static final String ATTR_TITLE = "title";
310 private static final String ATTR_SUMMARY = "summary";
311 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
312 private static final String ATTR_USAGE_BYTES = "usageBytes";
313 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600314 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700315
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800316 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800317 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800318 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800319 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700320
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700321 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
322
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700323 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700324 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800325 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800326 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700327 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700328 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
329 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700330 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700331 private static final int MSG_SET_FIREWALL_RULES = 14;
Felipe Leme03e95e22016-09-09 09:25:31 -0700332 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700333
Makoto Onuki8e777332017-03-28 11:25:47 -0700334 private static final int UID_MSG_STATE_CHANGED = 100;
335 private static final int UID_MSG_GONE = 101;
336
Jeff Sharkey75279902011-05-24 18:39:45 -0700337 private final Context mContext;
338 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700339 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700340 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700341 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700342 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700343 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700344 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700345
346 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700347 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700348 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700349 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800350 @GuardedBy("mUidRulesFirstLock")
351 private PowerSaveState mRestrictBackgroundPowerState;
352
353 // Store the status of restrict background before turning on battery saver.
354 // Used to restore mRestrictBackground when battery saver is turned off.
355 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700356
Sudheer Shanka543339f2017-07-28 15:18:07 -0700357 // Denotes the status of restrict background read from disk.
358 private boolean mLoadedRestrictBackground;
359
Felipe Lemef0823852016-06-08 13:43:08 -0700360 // See main javadoc for instructions on how to use these locks.
361 final Object mUidRulesFirstLock = new Object();
362 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700363
Felipe Lemef0823852016-06-08 13:43:08 -0700364 @GuardedBy("allLocks") volatile boolean mSystemReady;
365
Felipe Lemef0823852016-06-08 13:43:08 -0700366 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
367 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
368 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800369 // Store whether user flipped restrict background in battery saver mode
370 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700371
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700372 private final boolean mSuppressDefaultPolicy;
373
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700374 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800375 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700376 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800377 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = 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 Sharkey17bebd22017-07-19 21:00:38 -0600380 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600381 /** Map from subId to package name that owns subscription plans. */
382 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600383
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700384 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700385 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700386 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700387 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700388
Felipe Lemef0823852016-06-08 13:43:08 -0700389 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700390 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700391 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700392 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700393 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800394 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700395
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700396 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700397 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700398 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
399
Jeff Sharkey32566012014-12-02 18:30:14 -0800400 /**
401 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700402 * in power save mode, except device idle (doze) still applies.
403 * TODO: An int array might be sufficient
404 */
Felipe Lemef0823852016-06-08 13:43:08 -0700405 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700406 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
407
408 /**
409 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800410 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700411 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800412 */
Felipe Lemef0823852016-06-08 13:43:08 -0700413 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700414 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700415
Felipe Lemef0823852016-06-08 13:43:08 -0700416 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700417 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
418
Felipe Lemeb85a6372016-01-14 16:16:16 -0800419 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800420 * UIDs that have been initially white-listed by system to avoid restricted background.
421 */
Felipe Lemef0823852016-06-08 13:43:08 -0700422 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800423 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
424 new SparseBooleanArray();
425
426 /**
427 * UIDs that have been initially white-listed by system to avoid restricted background,
428 * but later revoked by user.
429 */
Felipe Lemef0823852016-06-08 13:43:08 -0700430 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800431 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
432 new SparseBooleanArray();
433
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700434 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700435 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800436 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700437 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700438 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800439 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700440
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700441 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700442 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400443 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700444
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700445 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700446 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800447 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700448
Jeff Sharkey32566012014-12-02 18:30:14 -0800449 private final RemoteCallbackList<INetworkPolicyListener>
450 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700451
Dianne Hackborn497175b2014-07-01 12:56:08 -0700452 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700453 @VisibleForTesting
454 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700455
456 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700457
Felipe Lemef0823852016-06-08 13:43:08 -0700458 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700459 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700460
Svet Ganov16a16892015-04-16 10:32:04 -0700461 private final AppOpsManager mAppOps;
462
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800463 private final IPackageManager mIPm;
464
Sudheer Shankae7361852017-03-07 11:51:46 -0800465 private ActivityManagerInternal mActivityManagerInternal;
466
467 /**
468 * This is used for debugging purposes. Whenever the IUidObserver.onUidStateChanged is called,
469 * the uid and procStateSeq will be written to this and will be printed as part of dump.
470 */
471 @VisibleForTesting
472 public ProcStateSeqHistory mObservedHistory
473 = new ProcStateSeqHistory(MAX_PROC_STATE_SEQ_HISTORY);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800474
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700475 // TODO: keep whitelist of system-critical services that should never have
476 // rules enforced, such as system, phone, and radio UIDs.
477
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700478 // TODO: migrate notifications to SystemUI
479
Jeff Sharkey75279902011-05-24 18:39:45 -0700480 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700481 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
482 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700483 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
484 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700485 }
486
487 private static File getSystemDir() {
488 return new File(Environment.getDataDirectory(), "system");
489 }
490
491 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700492 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700493 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700494 mContext = checkNotNull(context, "missing context");
495 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700496 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700497 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700498 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700499 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700500 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700501 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700502 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700503 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700504
Amith Yamasani450a16b2013-09-18 16:28:50 -0700505 HandlerThread thread = new HandlerThread(TAG);
506 thread.start();
507 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700508
Makoto Onuki8e777332017-03-28 11:25:47 -0700509 // We create another thread for the UID events, which are more time-critical.
510 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
511 /*allowIo=*/ false);
512 mUidEventThread.start();
513 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
514
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700515 mSuppressDefaultPolicy = suppressDefaultPolicy;
516
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700517 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700518
519 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800520
Felipe Lemed17fda42016-04-29 11:12:45 -0700521 // Expose private service for system components to use.
522 LocalServices.addService(NetworkPolicyManagerInternal.class,
523 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700524 }
525
526 public void bindConnectivityManager(IConnectivityManager connManager) {
527 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700528 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700529
Jeff Sharkey497e4432011-06-14 17:27:29 -0700530 public void bindNotificationManager(INotificationManager notifManager) {
531 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
532 }
533
Felipe Lemef0823852016-06-08 13:43:08 -0700534 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700535 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700536 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
537 mPowerSaveWhitelistExceptIdleAppIds.clear();
538 if (whitelist != null) {
539 for (int uid : whitelist) {
540 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
541 }
542 }
543 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700544 mPowerSaveWhitelistAppIds.clear();
545 if (whitelist != null) {
546 for (int uid : whitelist) {
547 mPowerSaveWhitelistAppIds.put(uid, true);
548 }
549 }
550 } catch (RemoteException e) {
551 }
552 }
553
Felipe Lemea9505cc2016-02-26 10:28:41 -0800554 /**
555 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
556 * revoke the whitelist.
557 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700558 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800559 */
Felipe Lemef0823852016-06-08 13:43:08 -0700560 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800561 final List<UserInfo> users = mUserManager.getUsers();
562 final int numberUsers = users.size();
563
Felipe Lemea110eec2016-04-29 09:58:06 -0700564 boolean changed = false;
565 for (int i = 0; i < numberUsers; i++) {
566 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700567 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700568 }
569 return changed;
570 }
571
Felipe Lemef0823852016-06-08 13:43:08 -0700572 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700573 final SystemConfig sysConfig = SystemConfig.getInstance();
574 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800575 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
576 boolean changed = false;
577 for (int i = 0; i < allowDataUsage.size(); i++) {
578 final String pkg = allowDataUsage.valueAt(i);
579 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700580 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
581 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800582 final ApplicationInfo app;
583 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700584 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800585 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700586 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
587 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800588 continue;
589 }
590 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700591 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
592 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800593 continue;
594 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700595 final int uid = UserHandle.getUid(userId, app.uid);
596 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
597 if (LOGD)
598 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
599 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800600 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700601 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700602 if (LOGD)
603 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
604 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700605 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700606 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800607 }
608 }
609 return changed;
610 }
611
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800612 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700613 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800614 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700615 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800616 // Boost thread's priority during system server init
617 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700618 if (!isBandwidthControlEnabled()) {
619 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
620 return;
621 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700622
Felipe Leme873a83a2016-09-07 11:34:10 -0700623 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700624
Felipe Leme873a83a2016-09-07 11:34:10 -0700625 synchronized (mUidRulesFirstLock) {
626 synchronized (mNetworkPoliciesSecondLock) {
627 updatePowerSaveWhitelistUL();
628 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
629 mPowerManagerInternal.registerLowPowerModeObserver(
630 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800631 @Override
632 public int getServiceType() {
633 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700634 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800635
636 @Override
637 public void onLowPowerModeChanged(PowerSaveState result) {
638 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800639 if (LOGD) {
640 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
641 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800642 synchronized (mUidRulesFirstLock) {
643 if (mRestrictPower != enabled) {
644 mRestrictPower = enabled;
645 updateRulesForRestrictPowerUL();
646 }
647 }
648 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800649 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800650 mRestrictPower = mPowerManagerInternal.getLowPowerState(
651 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700652
653 mSystemReady = true;
654
655 // read policy from disk
656 readPolicyAL();
657
jackqdyulei29c82ab2017-03-10 14:09:16 -0800658 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700659 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800660 mRestrictBackgroundPowerState = mPowerManagerInternal
661 .getLowPowerState(ServiceType.DATA_SAVER);
662 final boolean localRestrictBackground =
663 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700664 if (localRestrictBackground && !mLoadedRestrictBackground) {
665 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800666 }
667 mPowerManagerInternal.registerLowPowerModeObserver(
668 new PowerManagerInternal.LowPowerModeListener() {
669 @Override
670 public int getServiceType() {
671 return ServiceType.DATA_SAVER;
672 }
673
674 @Override
675 public void onLowPowerModeChanged(PowerSaveState result) {
676 synchronized (mUidRulesFirstLock) {
677 updateRestrictBackgroundByLowPowerModeUL(result);
678 }
679 }
680 });
681
Felipe Leme873a83a2016-09-07 11:34:10 -0700682 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
683 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700684 }
Felipe Lemef0823852016-06-08 13:43:08 -0700685
Sudheer Shanka543339f2017-07-28 15:18:07 -0700686 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700687 updateRulesForGlobalChangeAL(false);
688 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700689 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800690 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700691
Sudheer Shankae7361852017-03-07 11:51:46 -0800692 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700693 try {
694 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000695 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800696 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700697 mNetworkManager.registerObserver(mAlertObserver);
698 } catch (RemoteException e) {
699 // ignored; both services live in system_server
700 }
701
702 // listen for changes to power save whitelist
703 final IntentFilter whitelistFilter = new IntentFilter(
704 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
705 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
706
Felipe Leme873a83a2016-09-07 11:34:10 -0700707 // watch for network interfaces to be claimed
708 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
709 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
710
711 // listen for package changes to update policy
712 final IntentFilter packageFilter = new IntentFilter();
713 packageFilter.addAction(ACTION_PACKAGE_ADDED);
714 packageFilter.addDataScheme("package");
715 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
716
717 // listen for UID changes to update policy
718 mContext.registerReceiver(
719 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
720
721 // listen for user changes to update policy
722 final IntentFilter userFilter = new IntentFilter();
723 userFilter.addAction(ACTION_USER_ADDED);
724 userFilter.addAction(ACTION_USER_REMOVED);
725 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
726
727 // listen for stats update events
728 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
729 mContext.registerReceiver(
730 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
731
732 // listen for restrict background changes from notifications
733 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
734 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
735
736 // listen for snooze warning from notifications
737 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
738 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
739 MANAGE_NETWORK_POLICY, mHandler);
740
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600741 // listen for configured wifi networks to be loaded
742 final IntentFilter wifiFilter =
743 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
744 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700745
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700746 // listen for carrier config changes to update data cycle information
747 final IntentFilter carrierConfigFilter = new IntentFilter(
748 ACTION_CARRIER_CONFIG_CHANGED);
749 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
750
Felipe Leme873a83a2016-09-07 11:34:10 -0700751 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800752 // tell systemReady() that the service has been initialized
753 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700754 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800755 // Restore the default priority after init is done
756 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700757 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700758 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700759 }
760
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800761 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
762 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
763 mHandler.post(() -> initService(initCompleteSignal));
764 return initCompleteSignal;
765 }
766
767 public void systemReady(CountDownLatch initCompleteSignal) {
768 // wait for initService to complete
769 try {
770 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
771 throw new IllegalStateException("Service " + TAG +" init timeout");
772 }
773 } catch (InterruptedException e) {
774 Thread.currentThread().interrupt();
775 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
776 }
777 }
778
Sudheer Shankac9d94072017-02-22 22:13:55 +0000779 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700780 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700781 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
782 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700783 }
784
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700785 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700786 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700787 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700788
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700789 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700790 }
791
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700792 @Override public void onUidIdle(int uid, boolean disabled) {
793 }
794
795 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700796 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700797 };
798
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700799 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700800 @Override
801 public void onReceive(Context context, Intent intent) {
802 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700803 synchronized (mUidRulesFirstLock) {
804 updatePowerSaveWhitelistUL();
805 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700806 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700807 }
808 }
809 };
810
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700811 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700812 @Override
813 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700814 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700815
816 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700817 final int uid = intent.getIntExtra(EXTRA_UID, -1);
818 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700819
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700820 if (ACTION_PACKAGE_ADDED.equals(action)) {
821 // update rules for UID, since it might be subject to
822 // global background data policy
823 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700824 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700825 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700826 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700827 }
828 }
829 };
830
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700831 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700832 @Override
833 public void onReceive(Context context, Intent intent) {
834 // on background handler thread, and UID_REMOVED is protected
835
836 final int uid = intent.getIntExtra(EXTRA_UID, -1);
837 if (uid == -1) return;
838
839 // remove any policy and update rules to clean up
840 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700841 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700842 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700843 synchronized (mNetworkPoliciesSecondLock) {
844 writePolicyAL();
845 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700846 }
847 }
848 };
849
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700850 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700851 @Override
852 public void onReceive(Context context, Intent intent) {
853 // on background handler thread, and USER_ADDED and USER_REMOVED
854 // broadcasts are protected
855
856 final String action = intent.getAction();
857 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
858 if (userId == -1) return;
859
Amith Yamasani15e472352015-04-24 19:06:07 -0700860 switch (action) {
861 case ACTION_USER_REMOVED:
862 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700863 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800864 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700865 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700866 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700867 if (action == ACTION_USER_ADDED) {
868 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700869 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700870 }
871 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700872 synchronized (mNetworkPoliciesSecondLock) {
873 updateRulesForGlobalChangeAL(true);
874 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700875 }
876 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700877 }
878 }
879 };
880
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700881 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700882 * Receiver that watches for {@link INetworkStatsService} updates, which we
883 * use to check against {@link NetworkPolicy#warningBytes}.
884 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700885 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700886 @Override
887 public void onReceive(Context context, Intent intent) {
888 // on background handler thread, and verified
889 // READ_NETWORK_USAGE_HISTORY permission above.
890
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800891 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700892 synchronized (mNetworkPoliciesSecondLock) {
893 updateNetworkEnabledNL();
894 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700895 }
896 }
897 };
898
899 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700900 * Receiver that watches for {@link Notification} control of
901 * {@link #mRestrictBackground}.
902 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700903 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700904 @Override
905 public void onReceive(Context context, Intent intent) {
906 // on background handler thread, and verified MANAGE_NETWORK_POLICY
907 // permission above.
908
909 setRestrictBackground(false);
910 }
911 };
912
913 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800914 * Receiver that watches for {@link Notification} control of
915 * {@link NetworkPolicy#lastWarningSnooze}.
916 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700917 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800918 @Override
919 public void onReceive(Context context, Intent intent) {
920 // on background handler thread, and verified MANAGE_NETWORK_POLICY
921 // permission above.
922
923 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
924 performSnooze(template, TYPE_WARNING);
925 }
926 };
927
928 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600929 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
930 * we can perform upgrade logic.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700931 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600932 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700933 @Override
934 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900935 synchronized (mUidRulesFirstLock) {
936 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600937 upgradeWifiMeteredOverrideAL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700938 }
939 }
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600940 // Only need to perform upgrade logic once
941 mContext.unregisterReceiver(this);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700942 }
943 };
944
945 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700946 * Observer that watches for {@link INetworkManagementService} alerts.
947 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700948 final private INetworkManagementEventObserver mAlertObserver
949 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700950 @Override
951 public void limitReached(String limitName, String iface) {
952 // only someone like NMS should be calling us
953 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
954
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800955 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
956 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700957 }
958 }
959 };
960
961 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700962 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
963 * to show visible notifications as needed.
964 */
Felipe Lemef0823852016-06-08 13:43:08 -0700965 void updateNotificationsNL() {
966 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700967
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700968 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -0400969 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700970 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700971
972 // TODO: when switching to kernel notifications, compute next future
973 // cycle boundary to recompute notifications.
974
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700975 // examine stats for each active policy
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700976 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
977 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700978 // ignore policies that aren't relevant to user
979 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700980 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700981
Jeff Sharkey53313d72017-07-13 16:47:32 -0600982 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
983 .cycleIterator(policy).next();
984 final long start = cycle.first.toInstant().toEpochMilli();
985 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700986 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700987
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700988 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800989 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700990 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
991 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700992 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -0700993 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700994 }
995
Jeff Sharkey497e4432011-06-14 17:27:29 -0700996 } else {
Felipe Lemef0823852016-06-08 13:43:08 -0700997 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700998
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800999 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001000 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001001 }
1002 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001003 }
1004
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001005 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001006 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001007 final NotificationId notificationId = beforeNotifs.valueAt(i);
1008 if (!mActiveNotifs.contains(notificationId)) {
1009 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001010 }
1011 }
1012 }
1013
1014 /**
1015 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001016 * current device state, such as when
1017 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1018 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001019 */
1020 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001021 if (template.isMatchRuleMobile()) {
1022 final TelephonyManager tele = TelephonyManager.from(mContext);
1023 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001024
Jeff Sharkey32566012014-12-02 18:30:14 -08001025 // Mobile template is relevant when any active subscriber matches
1026 final int[] subIds = sub.getActiveSubscriptionIdList();
1027 for (int subId : subIds) {
1028 final String subscriberId = tele.getSubscriberId(subId);
1029 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001030 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001031 if (template.matches(probeIdent)) {
1032 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001033 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001034 }
1035 return false;
1036 } else {
1037 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001038 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001039 }
1040
1041 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001042 * Notify that given {@link NetworkTemplate} is over
1043 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1044 */
Felipe Lemef0823852016-06-08 13:43:08 -07001045 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001046 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001047 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001048 mOverLimitNotified.add(template);
1049 }
1050 }
1051
Felipe Lemef0823852016-06-08 13:43:08 -07001052 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001053 mOverLimitNotified.remove(template);
1054 }
1055
1056 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001057 * Show notification for combined {@link NetworkPolicy} and specific type,
1058 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1059 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001060 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001061 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001062 final Notification.Builder builder =
1063 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001064 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001065 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001066 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001067 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001068
1069 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001070 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001071 switch (type) {
1072 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001073 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001074 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001075
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001076 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001077 builder.setTicker(title);
1078 builder.setContentTitle(title);
1079 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001080 builder.setDefaults(Notification.DEFAULT_ALL);
Julia Reynoldsbad42972017-04-25 13:52:49 -04001081 builder.setChannelId(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001082
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001083 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1084 builder.setDeleteIntent(PendingIntent.getBroadcast(
1085 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1086
Wei Liu546cb772016-07-21 16:19:01 -07001087 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001088 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001089 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1090
Jeff Sharkey497e4432011-06-14 17:27:29 -07001091 break;
1092 }
1093 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001094 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001095
1096 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001097 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001098 switch (policy.template.getMatchRule()) {
1099 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001100 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001101 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001102 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001103 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001104 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001105 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001106 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001107 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001108 case MATCH_WIFI:
1109 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001110 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001111 break;
1112 default:
1113 title = null;
1114 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001115 }
1116
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001117 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001118 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001119 builder.setTicker(title);
1120 builder.setContentTitle(title);
1121 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001122
Wei Liu546cb772016-07-21 16:19:01 -07001123 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001124 builder.setContentIntent(PendingIntent.getActivity(
1125 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1126 break;
1127 }
1128 case TYPE_LIMIT_SNOOZED: {
1129 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001130 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001131 Formatter.formatFileSize(mContext, overBytes));
1132
1133 final CharSequence title;
1134 switch (policy.template.getMatchRule()) {
1135 case MATCH_MOBILE_3G_LOWER:
1136 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1137 break;
1138 case MATCH_MOBILE_4G:
1139 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1140 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001141 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001142 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1143 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001144 case MATCH_WIFI:
1145 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1146 break;
1147 default:
1148 title = null;
1149 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001150 }
1151
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001152 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001153 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001154 builder.setTicker(title);
1155 builder.setContentTitle(title);
1156 builder.setContentText(body);
1157
Wei Liu546cb772016-07-21 16:19:01 -07001158 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001159 builder.setContentIntent(PendingIntent.getActivity(
1160 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001161 break;
1162 }
1163 }
1164
1165 // TODO: move to NotificationManager once we can mock it
1166 try {
1167 final String packageName = mContext.getPackageName();
Chris Wren193ae6b2017-03-31 15:17:11 -04001168 if (!TextUtils.isEmpty(body)) {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001169 builder.setStyle(new Notification.BigTextStyle()
1170 .bigText(body));
1171 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001172 mNotifManager.enqueueNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001173 packageName, packageName, notificationId.getTag(), notificationId.getId(),
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001174 builder.build(), UserHandle.USER_ALL);
Chris Wren193ae6b2017-03-31 15:17:11 -04001175 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001176 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001177 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001178 }
1179 }
1180
Chris Wren193ae6b2017-03-31 15:17:11 -04001181 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001182 // TODO: move to NotificationManager once we can mock it
1183 try {
1184 final String packageName = mContext.getPackageName();
1185 mNotifManager.cancelNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001186 packageName, notificationId.getTag(), notificationId.getId(),
1187 UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001188 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001189 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001190 }
1191 }
1192
1193 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001194 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001195 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001196 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001197 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001198 @Override
1199 public void onReceive(Context context, Intent intent) {
1200 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1201 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001202
1203 maybeRefreshTrustedTime();
Hugo Benichi446c9c92017-04-10 09:41:10 +09001204 synchronized (mUidRulesFirstLock) {
1205 synchronized (mNetworkPoliciesSecondLock) {
1206 ensureActiveMobilePolicyAL();
1207 normalizePoliciesNL();
1208 updateNetworkEnabledNL();
1209 updateNetworkRulesNL();
1210 updateNotificationsNL();
1211 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001212 }
1213 }
1214 };
1215
1216 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001217 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1218 * if necessary.
1219 *
1220 * @param subId that has its associated NetworkPolicy updated if necessary
1221 * @return if any policies were updated
1222 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001223 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1224 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001225
1226 boolean policyUpdated = false;
1227 final String subscriberId = TelephonyManager.from(mContext).getSubscriberId(subId);
1228
1229 // find and update the mobile NetworkPolicy for this subscriber id
1230 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1231 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1232 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1233 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1234 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001235 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1236 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001237 }
1238 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001239 return policyUpdated;
1240 }
1241
1242 /**
1243 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1244 *
1245 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1246 * to do so, it returns the fallback value.
1247 *
1248 * @param config The CarrierConfig to read the value from.
1249 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1250 * @return cycleDay to use in the mobile NetworkPolicy.
1251 */
1252 @VisibleForTesting
1253 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1254 int fallbackCycleDay) {
1255 if (config == null) {
1256 return fallbackCycleDay;
1257 }
1258 int cycleDay =
1259 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1260 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1261 return fallbackCycleDay;
1262 }
1263 // validate cycleDay value
1264 final Calendar cal = Calendar.getInstance();
1265 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1266 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1267 Slog.e(TAG, "Invalid date in "
1268 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1269 return fallbackCycleDay;
1270 }
1271 return cycleDay;
1272 }
1273
1274 /**
1275 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1276 *
1277 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1278 * to do so, it returns the fallback value.
1279 *
1280 * @param config The CarrierConfig to read the value from.
1281 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1282 * @return warningBytes to use in the mobile NetworkPolicy.
1283 */
1284 @VisibleForTesting
1285 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1286 long fallbackWarningBytes) {
1287 if (config == null) {
1288 return fallbackWarningBytes;
1289 }
1290 long warningBytes =
1291 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1292
1293 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1294 return WARNING_DISABLED;
1295 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1296 return getPlatformDefaultWarningBytes();
1297 } else if (warningBytes < 0) {
1298 Slog.e(TAG, "Invalid value in "
1299 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1300 + "non-negative value but got: " + warningBytes);
1301 return fallbackWarningBytes;
1302 }
1303
1304 return warningBytes;
1305 }
1306
1307 /**
1308 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1309 *
1310 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1311 * to do so, it returns the fallback value.
1312 *
1313 * @param config The CarrierConfig to read the value from.
1314 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1315 * @return limitBytes to use in the mobile NetworkPolicy.
1316 */
1317 @VisibleForTesting
1318 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1319 long fallbackLimitBytes) {
1320 if (config == null) {
1321 return fallbackLimitBytes;
1322 }
1323 long limitBytes =
1324 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1325
1326 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1327 return LIMIT_DISABLED;
1328 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1329 return getPlatformDefaultLimitBytes();
1330 } else if (limitBytes < 0) {
1331 Slog.e(TAG, "Invalid value in "
1332 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1333 + "non-negative value but got: " + limitBytes);
1334 return fallbackLimitBytes;
1335 }
1336 return limitBytes;
1337 }
1338
1339 /**
1340 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1341 */
1342 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1343 @Override
1344 public void onReceive(Context context, Intent intent) {
1345 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1346 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1347
1348 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1349 return;
1350 }
1351 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
1352 final TelephonyManager tele = TelephonyManager.from(mContext);
1353 final String subscriberId = tele.getSubscriberId(subId);
1354
1355 maybeRefreshTrustedTime();
1356 synchronized (mUidRulesFirstLock) {
1357 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001358 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001359 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001360 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001361 if (!updated) return;
1362 // update network and notification rules, as the data cycle changed and it's
1363 // possible that we should be triggering warnings/limits now
1364 handleNetworkPoliciesUpdateAL(true);
1365 }
1366 }
1367 }
1368 };
1369
1370 /**
1371 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1372 * one has been updated.
1373 *
1374 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1375 * update.
1376 */
1377 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1378 if (shouldNormalizePolicies) {
1379 normalizePoliciesNL();
1380 }
1381 updateNetworkEnabledNL();
1382 updateNetworkRulesNL();
1383 updateNotificationsNL();
1384 writePolicyAL();
1385 }
1386
1387 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001388 * Proactively control network data connections when they exceed
1389 * {@link NetworkPolicy#limitBytes}.
1390 */
Felipe Lemef0823852016-06-08 13:43:08 -07001391 void updateNetworkEnabledNL() {
1392 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001393
1394 // TODO: reset any policy-disabled networks when any policy is removed
1395 // completely, which is currently rare case.
1396
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001397 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1398 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001399 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001400 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001401 setNetworkTemplateEnabled(policy.template, true);
1402 continue;
1403 }
1404
Jeff Sharkey53313d72017-07-13 16:47:32 -06001405 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1406 .cycleIterator(policy).next();
1407 final long start = cycle.first.toInstant().toEpochMilli();
1408 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001409 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001410
1411 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001412 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1413 && policy.lastLimitSnooze < start;
1414 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001415
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001416 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001417 }
1418 }
1419
1420 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001421 * Proactively disable networks that match the given
1422 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001423 */
1424 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001425 // TODO: reach into ConnectivityManager to proactively disable bringing
1426 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001427
1428 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1429 // If mobile data usage hits the limit or if the user resumes the data, we need to
1430 // notify telephony.
1431 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1432 final TelephonyManager tm = TelephonyManager.from(mContext);
1433
1434 final int[] subIds = sm.getActiveSubscriptionIdList();
1435 for (int subId : subIds) {
1436 final String subscriberId = tm.getSubscriberId(subId);
1437 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1438 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1439 // Template is matched when subscriber id matches.
1440 if (template.matches(probeIdent)) {
1441 tm.setPolicyDataEnabled(enabled, subId);
1442 }
1443 }
1444 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001445 }
1446
1447 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001448 * Examine all connected {@link NetworkState}, looking for
1449 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1450 * remaining quota based on usage cycle and historical stats.
1451 */
Felipe Lemef0823852016-06-08 13:43:08 -07001452 void updateNetworkRulesNL() {
1453 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001454
1455 final NetworkState[] states;
1456 try {
1457 states = mConnManager.getAllNetworkState();
1458 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001459 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001460 return;
1461 }
1462
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001463 // First, generate identities of all connected networks so we can
1464 // quickly compare them against all defined policies below.
1465 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001466 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001467 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001468 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001469 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001470
1471 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001472 if (baseIface != null) {
1473 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001474 }
1475
1476 // Stacked interfaces are considered to have same identity as
1477 // their parent network.
1478 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1479 for (LinkProperties stackedLink : stackedLinks) {
1480 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001481 if (stackedIface != null) {
1482 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001483 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001484 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001485 }
1486 }
1487
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001488 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001489 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001490 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001491 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001492 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001493
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001494 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001495 for (int j = connIdents.size() - 1; j >= 0; j--) {
1496 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1497 if (policy.template.matches(ident.second)) {
1498 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001499 }
1500 }
1501
1502 if (ifaceList.size() > 0) {
1503 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001504 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001505 }
1506 }
1507
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001508 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001509 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001510
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001511 // apply each policy that we found ifaces for; compute remaining data
1512 // based on current cycle and historical stats, and push to kernel.
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001513 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1514 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1515 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001516
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001517 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001518 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001519 }
1520
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001521 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001522 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001523 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001524 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001525 if (hasLimit && policy.hasCycle()) {
1526 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1527 .cycleIterator(policy).next();
1528 final long start = cycle.first.toInstant().toEpochMilli();
1529 final long end = cycle.second.toInstant().toEpochMilli();
1530 final long totalBytes = getTotalBytes(policy.template, start, end);
1531
1532 if (policy.lastLimitSnooze >= start) {
1533 // snoozing past quota, but we still need to restrict apps,
1534 // so push really high quota.
1535 quotaBytes = Long.MAX_VALUE;
1536 } else {
1537 // remaining "quota" bytes are based on total usage in
1538 // current cycle. kernel doesn't like 0-byte rules, so we
1539 // set 1-byte quota and disable the radio later.
1540 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1541 }
1542 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001543 // metered network, but no policy limit; we still need to
1544 // restrict apps, so push really high quota.
1545 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001546 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001547
1548 if (ifaces.length > 1) {
1549 // TODO: switch to shared quota once NMS supports
1550 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001551 }
1552
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001553 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001554 // long quotaBytes split up into two ints to fit in message
1555 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1556 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1557 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001558 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001559 }
1560 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001561
1562 // keep track of lowest warning or limit of active policies
1563 if (hasWarning && policy.warningBytes < lowestRule) {
1564 lowestRule = policy.warningBytes;
1565 }
1566 if (hasLimit && policy.limitBytes < lowestRule) {
1567 lowestRule = policy.limitBytes;
1568 }
1569 }
1570
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001571 for (int i = connIfaces.size()-1; i >= 0; i--) {
1572 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001573 // long quotaBytes split up into two ints to fit in message
1574 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1575 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1576 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001577 newMeteredIfaces.add(iface);
1578 }
1579
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001580 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001581
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001582 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001583 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1584 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001585 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001586 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1587 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001588 }
1589 }
1590 mMeteredIfaces = newMeteredIfaces;
1591
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001592 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001593 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001594 }
1595
1596 /**
1597 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1598 * have at least a default mobile policy defined.
1599 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001600 private void ensureActiveMobilePolicyAL() {
1601 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001602 if (mSuppressDefaultPolicy) return;
1603
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001604 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001605 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001606
Jeff Sharkey32566012014-12-02 18:30:14 -08001607 final int[] subIds = sub.getActiveSubscriptionIdList();
1608 for (int subId : subIds) {
1609 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001610 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001611 }
1612 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001613
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001614 /**
1615 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1616 * have at least a default mobile policy defined.
1617 *
1618 * @param subId to build a default policy for
1619 * @param subscriberId that we check for an existing policy
1620 * @return true if a mobile network policy was added, or false one already existed.
1621 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001622 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001623 // Poke around to see if we already have a policy
1624 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001625 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001626 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1627 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1628 if (template.matches(probeIdent)) {
1629 if (LOGD) {
1630 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1631 + NetworkIdentity.scrubSubscriberId(subscriberId));
1632 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001633 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001634 }
1635 }
1636
Jeff Sharkey32566012014-12-02 18:30:14 -08001637 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1638 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001639 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001640 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001641 return true;
1642 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001643
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001644 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001645 final int dataWarningConfig = mContext.getResources().getInteger(
1646 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001647 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001648 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001649 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001650 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001651 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001652 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001653
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001654 private long getPlatformDefaultLimitBytes() {
1655 return LIMIT_DISABLED;
1656 }
1657
1658 @VisibleForTesting
1659 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001660 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001661 final RecurrenceRule cycleRule = NetworkPolicy
1662 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001663 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001664 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1665 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1666 synchronized (mUidRulesFirstLock) {
1667 synchronized (mNetworkPoliciesSecondLock) {
1668 updateDefaultMobilePolicyAL(subId, policy);
1669 }
1670 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001671 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001672 }
1673
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001674 /**
1675 * Update the given {@link NetworkPolicy} based on any carrier-provided
1676 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1677 * Leaves policy untouched if the user has modified it.
1678 *
1679 * @return if the policy was modified
1680 */
1681 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1682 if (!policy.inferred) {
1683 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1684 return false;
1685 }
1686
1687 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1688 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1689 policy.lastLimitSnooze, policy.metered, policy.inferred);
1690
1691 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1692 if (!ArrayUtils.isEmpty(plans)) {
1693 final SubscriptionPlan plan = plans[0];
1694 policy.cycleRule = plan.getCycleRule();
1695 final long planLimitBytes = plan.getDataLimitBytes();
1696 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1697 policy.warningBytes = getPlatformDefaultWarningBytes();
1698 policy.limitBytes = getPlatformDefaultLimitBytes();
1699 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1700 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1701 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1702 } else {
1703 policy.warningBytes = (planLimitBytes * 9) / 10;
1704 switch (plan.getDataLimitBehavior()) {
1705 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1706 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1707 policy.limitBytes = planLimitBytes;
1708 break;
1709 default:
1710 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1711 break;
1712 }
1713 }
1714 } else {
1715 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1716 final int currentCycleDay;
1717 if (policy.cycleRule.isMonthly()) {
1718 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1719 } else {
1720 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1721 }
1722 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1723 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1724 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1725 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1726 }
1727
1728 if (policy.equals(original)) {
1729 return false;
1730 } else {
1731 Slog.d(TAG, "Updated " + original + " to " + policy);
1732 return true;
1733 }
1734 }
1735
Felipe Lemef0823852016-06-08 13:43:08 -07001736 private void readPolicyAL() {
1737 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001738
1739 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001740 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001741 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001742 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001743 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001744
1745 FileInputStream fis = null;
1746 try {
1747 fis = mPolicyFile.openRead();
1748 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001749 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001750
Felipe Leme46b451f2016-08-19 08:46:17 -07001751 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1752 // to skip UIDs that were explicitly blacklisted.
1753 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1754
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001755 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001756 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001757 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001758 while ((type = in.next()) != END_DOCUMENT) {
1759 final String tag = in.getName();
1760 if (type == START_TAG) {
1761 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001762 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001763 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07001764 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
1765 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001766 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1767 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1768 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001769 final String networkId;
1770 if (version >= VERSION_ADDED_NETWORK_ID) {
1771 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1772 } else {
1773 networkId = null;
1774 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001775 final RecurrenceRule cycleRule;
1776 if (version >= VERSION_ADDED_CYCLE) {
1777 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1778 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1779 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1780 cycleRule = new RecurrenceRule(
1781 RecurrenceRule.convertZonedDateTime(start),
1782 RecurrenceRule.convertZonedDateTime(end),
1783 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001784 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001785 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1786 final String cycleTimezone;
1787 if (version >= VERSION_ADDED_TIMEZONE) {
1788 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1789 } else {
1790 cycleTimezone = "UTC";
1791 }
1792 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001793 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001794 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1795 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001796 final long lastLimitSnooze;
1797 if (version >= VERSION_SPLIT_SNOOZE) {
1798 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1799 } else if (version >= VERSION_ADDED_SNOOZE) {
1800 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001801 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001802 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001803 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001804 final boolean metered;
1805 if (version >= VERSION_ADDED_METERED) {
1806 metered = readBooleanAttribute(in, ATTR_METERED);
1807 } else {
1808 switch (networkTemplate) {
1809 case MATCH_MOBILE_3G_LOWER:
1810 case MATCH_MOBILE_4G:
1811 case MATCH_MOBILE_ALL:
1812 metered = true;
1813 break;
1814 default:
1815 metered = false;
1816 }
1817 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001818 final long lastWarningSnooze;
1819 if (version >= VERSION_SPLIT_SNOOZE) {
1820 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1821 } else {
1822 lastWarningSnooze = SNOOZE_NEVER;
1823 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001824 final boolean inferred;
1825 if (version >= VERSION_ADDED_INFERRED) {
1826 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1827 } else {
1828 inferred = false;
1829 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001830
Jeff Sharkey32566012014-12-02 18:30:14 -08001831 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1832 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001833 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001834 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
1835 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001836 lastLimitSnooze, metered, inferred));
1837 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001838
1839 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
1840 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1841 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1842 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1843 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
1844 RecurrenceRule.convertZonedDateTime(start),
1845 RecurrenceRule.convertZonedDateTime(end),
1846 RecurrenceRule.convertPeriod(period));
1847 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
1848 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
1849
1850 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
1851 SubscriptionPlan.BYTES_UNKNOWN);
1852 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
1853 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
1854 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
1855 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
1856 builder.setDataLimit(limitBytes, limitBehavior);
1857 }
1858
1859 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
1860 SubscriptionPlan.BYTES_UNKNOWN);
1861 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
1862 SubscriptionPlan.TIME_UNKNOWN);
1863 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
1864 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
1865 builder.setDataUsage(usageBytes, usageTime);
1866 }
1867
1868 final int subId = readIntAttribute(in, ATTR_SUB_ID);
1869 final SubscriptionPlan plan = builder.build();
1870 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
1871 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
1872
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001873 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
1874 mSubscriptionPlansOwner.put(subId, ownerPackage);
1875
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001876 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001877 final int uid = readIntAttribute(in, ATTR_UID);
1878 final int policy = readIntAttribute(in, ATTR_POLICY);
1879
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001880 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001881 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001882 } else {
1883 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1884 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001885 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001886 final int appId = readIntAttribute(in, ATTR_APP_ID);
1887 final int policy = readIntAttribute(in, ATTR_POLICY);
1888
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001889 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001890 // app policy is deprecated so this is only used in pre system user split.
1891 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001892 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001893 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001894 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001895 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001896 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001897 } else if (TAG_WHITELIST.equals(tag)) {
1898 insideWhitelist = true;
1899 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1900 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001901 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001902 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1903 final int uid = readIntAttribute(in, ATTR_UID);
1904 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001905 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001906 } else if (type == END_TAG) {
1907 if (TAG_WHITELIST.equals(tag)) {
1908 insideWhitelist = false;
1909 }
1910
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001911 }
1912 }
1913
Felipe Leme46b451f2016-08-19 08:46:17 -07001914 final int size = whitelistedRestrictBackground.size();
1915 for (int i = 0; i < size; i++) {
1916 final int uid = whitelistedRestrictBackground.keyAt(i);
1917 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1918 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1919 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1920 + " because its policy is " + uidPoliciesToString(policy));
1921 continue;
1922 }
1923 if (UserHandle.isApp(uid)) {
1924 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1925 if (LOGV)
1926 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1927 setUidPolicyUncheckedUL(uid, newPolicy, false);
1928 } else {
1929 Slog.w(TAG, "unable to update policy on UID " + uid);
1930 }
1931 }
1932
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001933 } catch (FileNotFoundException e) {
1934 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001935 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001936 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001937 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001938 } finally {
1939 IoUtils.closeQuietly(fis);
1940 }
1941 }
1942
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001943 /**
1944 * Upgrade legacy background data flags, notifying listeners of one last
1945 * change to always-true.
1946 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001947 private void upgradeDefaultBackgroundDataUL() {
1948 // This method is only called when we're unable to find the network policy flag, which
1949 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001950
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001951 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07001952 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001953 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
1954
1955 // NOTE: We used to read the legacy setting here :
1956 //
1957 // final int legacyFlagValue = Settings.Secure.getInt(
1958 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
1959 //
1960 // This is no longer necessary because we will never upgrade directly from Gingerbread
1961 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
1962 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001963 }
1964
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001965 /**
1966 * Perform upgrade step of moving any user-defined meterness overrides over
1967 * into {@link WifiConfiguration}.
1968 */
1969 private void upgradeWifiMeteredOverrideAL() {
1970 boolean modified = false;
1971 final WifiManager wm = mContext.getSystemService(WifiManager.class);
1972 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
1973 for (int i = 0; i < mNetworkPolicy.size(); ) {
1974 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1975 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
1976 && !policy.inferred) {
1977 mNetworkPolicy.removeAt(i);
1978 modified = true;
1979
1980 final String networkId = resolveNetworkId(policy.template.getNetworkId());
1981 for (WifiConfiguration config : configs) {
1982 if (Objects.equals(resolveNetworkId(config), networkId)) {
1983 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
1984 config.meteredOverride = policy.metered
1985 ? WifiConfiguration.METERED_OVERRIDE_METERED
1986 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
1987 wm.updateNetwork(config);
1988 }
1989 }
1990 } else {
1991 i++;
1992 }
1993 }
1994 if (modified) {
1995 writePolicyAL();
1996 }
1997 }
1998
Felipe Lemef0823852016-06-08 13:43:08 -07001999 void writePolicyAL() {
2000 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002001
2002 FileOutputStream fos = null;
2003 try {
2004 fos = mPolicyFile.startWrite();
2005
2006 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002007 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002008 out.startDocument(null, true);
2009
2010 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002011 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002012 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002013
2014 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002015 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2016 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002017 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002018 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002019
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002020 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002021 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2022 final String subscriberId = template.getSubscriberId();
2023 if (subscriberId != null) {
2024 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002025 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002026 final String networkId = template.getNetworkId();
2027 if (networkId != null) {
2028 out.attribute(null, ATTR_NETWORK_ID, networkId);
2029 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002030 writeStringAttribute(out, ATTR_CYCLE_START,
2031 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2032 writeStringAttribute(out, ATTR_CYCLE_END,
2033 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2034 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2035 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002036 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2037 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002038 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2039 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002040 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002041 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002042 out.endTag(null, TAG_NETWORK_POLICY);
2043 }
2044
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002045 // write all known subscription plans
2046 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2047 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002048 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002049 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2050 if (ArrayUtils.isEmpty(plans)) continue;
2051
2052 for (SubscriptionPlan plan : plans) {
2053 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2054 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002055 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002056 final RecurrenceRule cycleRule = plan.getCycleRule();
2057 writeStringAttribute(out, ATTR_CYCLE_START,
2058 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2059 writeStringAttribute(out, ATTR_CYCLE_END,
2060 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2061 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2062 RecurrenceRule.convertPeriod(cycleRule.period));
2063 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2064 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2065 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2066 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2067 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2068 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2069 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2070 }
2071 }
2072
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002073 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002074 for (int i = 0; i < mUidPolicy.size(); i++) {
2075 final int uid = mUidPolicy.keyAt(i);
2076 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002077
Jeff Sharkey497e4432011-06-14 17:27:29 -07002078 // skip writing empty policies
2079 if (policy == POLICY_NONE) continue;
2080
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002081 out.startTag(null, TAG_UID_POLICY);
2082 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002083 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002084 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002085 }
2086
2087 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002088
2089 // write all whitelists
2090 out.startTag(null, TAG_WHITELIST);
2091
Felipe Lemea9505cc2016-02-26 10:28:41 -08002092 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002093 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002094 for (int i = 0; i < size; i++) {
2095 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2096 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2097 writeIntAttribute(out, ATTR_UID, uid);
2098 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2099 }
2100
Felipe Lemeb85a6372016-01-14 16:16:16 -08002101 out.endTag(null, TAG_WHITELIST);
2102
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002103 out.endDocument();
2104
2105 mPolicyFile.finishWrite(fos);
2106 } catch (IOException e) {
2107 if (fos != null) {
2108 mPolicyFile.failWrite(fos);
2109 }
2110 }
2111 }
2112
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002113 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002114 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002115 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002116
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002117 if (!UserHandle.isApp(uid)) {
2118 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002119 }
Felipe Lemef0823852016-06-08 13:43:08 -07002120 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002121 final long token = Binder.clearCallingIdentity();
2122 try {
2123 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2124 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002125 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002126 }
2127 } finally {
2128 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002129 }
2130 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002131 }
2132
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002133 @Override
2134 public void addUidPolicy(int uid, int policy) {
2135 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002136
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002137 if (!UserHandle.isApp(uid)) {
2138 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2139 }
2140
Felipe Lemef0823852016-06-08 13:43:08 -07002141 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002142 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2143 policy |= oldPolicy;
2144 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002145 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002146 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002147 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002148 }
2149
2150 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002151 public void removeUidPolicy(int uid, int policy) {
2152 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2153
2154 if (!UserHandle.isApp(uid)) {
2155 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2156 }
2157
Felipe Lemef0823852016-06-08 13:43:08 -07002158 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002159 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2160 policy = oldPolicy & ~policy;
2161 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002162 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002163 }
2164 }
2165 }
2166
Felipe Lemef0823852016-06-08 13:43:08 -07002167 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2168 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002169
Felipe Leme57e3d312016-08-23 14:42:52 -07002170 final boolean notifyApp;
2171 if (!isUidValidForWhitelistRules(uid)) {
2172 notifyApp = false;
2173 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002174 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2175 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2176 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2177 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002178 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2179 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002180 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2181 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2182 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2183 if (LOGD)
2184 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2185 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2186 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002187 notifyApp = wasBlocked != isBlocked;
2188 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002189 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2190 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002191 }
2192
Felipe Lemef0823852016-06-08 13:43:08 -07002193 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002194 if (policy == POLICY_NONE) {
2195 mUidPolicy.delete(uid);
2196 } else {
2197 mUidPolicy.put(uid, policy);
2198 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002199
2200 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002201 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002202 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002203 synchronized (mNetworkPoliciesSecondLock) {
2204 writePolicyAL();
2205 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002206 }
2207 }
2208
2209 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002210 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002211 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2212
Felipe Lemef0823852016-06-08 13:43:08 -07002213 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002214 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002215 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002216 }
2217
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002218 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002219 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002220 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2221
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002222 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002223 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002224 for (int i = 0; i < mUidPolicy.size(); i++) {
2225 final int uid = mUidPolicy.keyAt(i);
2226 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002227 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2228 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002229 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002230 }
2231 }
2232 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002233 return uids;
2234 }
2235
2236 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002237 * Removes any persistable state associated with given {@link UserHandle}, persisting
2238 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002239 */
Felipe Lemef0823852016-06-08 13:43:08 -07002240 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002241
Felipe Lemef0823852016-06-08 13:43:08 -07002242 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07002243 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002244
Felipe Lemea110eec2016-04-29 09:58:06 -07002245 // Remove entries from revoked default restricted background UID whitelist
2246 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2247 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2248 if (UserHandle.getUserId(uid) == userId) {
2249 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002250 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002251 }
2252 }
2253
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002254 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002255 int[] uids = new int[0];
2256 for (int i = 0; i < mUidPolicy.size(); i++) {
2257 final int uid = mUidPolicy.keyAt(i);
2258 if (UserHandle.getUserId(uid) == userId) {
2259 uids = appendInt(uids, uid);
2260 }
2261 }
2262
2263 if (uids.length > 0) {
2264 for (int uid : uids) {
2265 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002266 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002267 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002268 }
Felipe Lemef0823852016-06-08 13:43:08 -07002269 synchronized (mNetworkPoliciesSecondLock) {
2270 updateRulesForGlobalChangeAL(true);
2271 if (writePolicy && changed) {
2272 writePolicyAL();
2273 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002274 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002275 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002276 }
2277
2278 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002279 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002280 // TODO: create permission for observing network policy
2281 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002282 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002283 }
2284
2285 @Override
2286 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002287 // TODO: create permission for observing network policy
2288 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002289 mListeners.unregister(listener);
2290 }
2291
Jeff Sharkey1b861272011-05-22 00:34:52 -07002292 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002293 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002294 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2295
Felipe Leme6a05eee2016-02-19 14:43:51 -08002296 final long token = Binder.clearCallingIdentity();
2297 try {
2298 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002299 synchronized (mUidRulesFirstLock) {
2300 synchronized (mNetworkPoliciesSecondLock) {
2301 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002302 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002303 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002304 }
2305 } finally {
2306 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002307 }
2308 }
2309
Hugo Benichi446c9c92017-04-10 09:41:10 +09002310 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002311 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002312 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2313 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002314 }
2315
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002316 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002317 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002318 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002319 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002320 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2321 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2322 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002323 } catch (SecurityException e) {
2324 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002325
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002326 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2327 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2328 return new NetworkPolicy[0];
2329 }
Svet Ganov16a16892015-04-16 10:32:04 -07002330 }
2331
Felipe Lemef0823852016-06-08 13:43:08 -07002332 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002333 final int size = mNetworkPolicy.size();
2334 final NetworkPolicy[] policies = new NetworkPolicy[size];
2335 for (int i = 0; i < size; i++) {
2336 policies[i] = mNetworkPolicy.valueAt(i);
2337 }
2338 return policies;
2339 }
2340 }
2341
Felipe Lemef0823852016-06-08 13:43:08 -07002342 private void normalizePoliciesNL() {
2343 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002344 }
2345
Felipe Lemef0823852016-06-08 13:43:08 -07002346 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002347 final TelephonyManager tele = TelephonyManager.from(mContext);
2348 final String[] merged = tele.getMergedSubscriberIds();
2349
2350 mNetworkPolicy.clear();
2351 for (NetworkPolicy policy : policies) {
2352 // When two normalized templates conflict, prefer the most
2353 // restrictive policy
2354 policy.template = NetworkTemplate.normalize(policy.template, merged);
2355 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2356 if (existing == null || existing.compareTo(policy) > 0) {
2357 if (existing != null) {
2358 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2359 }
2360 mNetworkPolicy.put(policy.template, policy);
2361 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002362 }
2363 }
2364
2365 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002366 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002367 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002368
2369 final long token = Binder.clearCallingIdentity();
2370 try {
2371 performSnooze(template, TYPE_LIMIT);
2372 } finally {
2373 Binder.restoreCallingIdentity(token);
2374 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002375 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002376
Dianne Hackborn497175b2014-07-01 12:56:08 -07002377 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002378 maybeRefreshTrustedTime();
2379 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002380 synchronized (mUidRulesFirstLock) {
2381 synchronized (mNetworkPoliciesSecondLock) {
2382 // find and snooze local policy that matches
2383 final NetworkPolicy policy = mNetworkPolicy.get(template);
2384 if (policy == null) {
2385 throw new IllegalArgumentException("unable to find policy for " + template);
2386 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002387
Felipe Lemef0823852016-06-08 13:43:08 -07002388 switch (type) {
2389 case TYPE_WARNING:
2390 policy.lastWarningSnooze = currentTime;
2391 break;
2392 case TYPE_LIMIT:
2393 policy.lastLimitSnooze = currentTime;
2394 break;
2395 default:
2396 throw new IllegalArgumentException("unexpected type");
2397 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002398
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002399 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002400 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002401 }
2402 }
2403
2404 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002405 public void onTetheringChanged(String iface, boolean tethering) {
2406 // No need to enforce permission because setRestrictBackground() will do it.
2407 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002408 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002409 if (mRestrictBackground && tethering) {
2410 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2411 setRestrictBackground(false);
2412 }
2413 }
2414 }
2415
2416 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002417 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002418 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002419 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002420 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2421 final long token = Binder.clearCallingIdentity();
2422 try {
2423 maybeRefreshTrustedTime();
2424 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002425 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002426 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002427 } finally {
2428 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002429 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002430 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002431 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002432 }
2433 }
2434
Felipe Lemef0823852016-06-08 13:43:08 -07002435 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002436 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002437 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002438 if (restrictBackground == mRestrictBackground) {
2439 // Ideally, UI should never allow this scenario...
2440 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002441 return;
2442 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002443 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2444 final boolean oldRestrictBackground = mRestrictBackground;
2445 mRestrictBackground = restrictBackground;
2446 // Must whitelist foreground apps before turning data saver mode on.
2447 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2448 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2449 updateRulesForRestrictBackgroundUL();
2450 try {
2451 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2452 Slog.e(TAG,
2453 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2454 mRestrictBackground = oldRestrictBackground;
2455 // TODO: if it knew the foreground apps (see TODO above), it could call
2456 // updateRulesForRestrictBackgroundUL() again to restore state.
2457 return;
2458 }
2459 } catch (RemoteException e) {
2460 // ignored; service lives in system_server
2461 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002462
Sudheer Shanka543339f2017-07-28 15:18:07 -07002463 sendRestrictBackgroundChangedMsg();
2464
2465 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2466 mRestrictBackgroundChangedInBsm = true;
2467 }
2468 synchronized (mNetworkPoliciesSecondLock) {
2469 updateNotificationsNL();
2470 writePolicyAL();
2471 }
2472 } finally {
2473 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002474 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002475 }
2476
2477 private void sendRestrictBackgroundChangedMsg() {
2478 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2479 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2480 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002481 }
2482
Felipe Lemeb85a6372016-01-14 16:16:16 -08002483 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002484 public int getRestrictBackgroundByCaller() {
2485 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2486 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002487
Felipe Lemef0823852016-06-08 13:43:08 -07002488 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002489 // Must clear identity because getUidPolicy() is restricted to system.
2490 final long token = Binder.clearCallingIdentity();
2491 final int policy;
2492 try {
2493 policy = getUidPolicy(uid);
2494 } finally {
2495 Binder.restoreCallingIdentity(token);
2496 }
2497 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2498 // App is blacklisted.
2499 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2500 }
Felipe Leme1b103232016-01-22 09:44:57 -08002501 if (!mRestrictBackground) {
2502 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2503 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002504 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002505 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2506 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2507 }
2508 }
2509
2510 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002511 public boolean getRestrictBackground() {
2512 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2513
Felipe Lemef0823852016-06-08 13:43:08 -07002514 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002515 return mRestrictBackground;
2516 }
2517 }
2518
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002519 @Override
2520 public void setDeviceIdleMode(boolean enabled) {
2521 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002522 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2523 try {
2524 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002525 if (mDeviceIdleMode == enabled) {
2526 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002527 }
Felipe Lemeea014392016-09-06 13:59:54 -07002528 mDeviceIdleMode = enabled;
2529 if (mSystemReady) {
2530 // Device idle change means we need to rebuild rules for all
2531 // known apps, so do a global refresh.
2532 updateRulesForRestrictPowerUL();
2533 }
2534 }
2535 if (enabled) {
2536 EventLogTags.writeDeviceIdleOnPhase("net");
2537 } else {
2538 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002539 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002540 } finally {
2541 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002542 }
2543 }
2544
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002545 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002546 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2547 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002548 final long token = Binder.clearCallingIdentity();
2549 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002550 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2551 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2552 for (WifiConfiguration config : configs) {
2553 if (Objects.equals(resolveNetworkId(config), networkId)) {
2554 config.meteredOverride = meteredOverride;
2555 wm.updateNetwork(config);
2556 }
2557 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002558 } finally {
2559 Binder.restoreCallingIdentity(token);
2560 }
2561 }
2562
Jeff Sharkey46645002011-07-27 21:11:21 -07002563 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002564 @Deprecated
2565 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2566 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2567 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2568 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002569 }
2570
Jeff Sharkey53313d72017-07-13 16:47:32 -06002571 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2572 // Verify they're not lying about package name
2573 mAppOps.checkPackage(callingUid, callingPackage);
2574
Jeff Sharkey53313d72017-07-13 16:47:32 -06002575 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002576 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002577 final long token = Binder.clearCallingIdentity();
2578 try {
2579 si = mContext.getSystemService(SubscriptionManager.class)
2580 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002581 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002582 } finally {
2583 Binder.restoreCallingIdentity(token);
2584 }
2585
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002586 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002587 if (si != null) {
2588 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2589 return;
2590 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002591 }
2592
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002593 // Second check: has the CarrierService delegated access?
2594 if (config != null) {
2595 final String overridePackage = config
2596 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2597 if (!TextUtils.isEmpty(overridePackage)
2598 && Objects.equals(overridePackage, callingPackage)) {
2599 return;
2600 }
2601 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002602
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002603 // Third check: is caller the fallback/default CarrierService?
2604 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2605 if (!TextUtils.isEmpty(defaultPackage)
2606 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002607 return;
2608 }
2609
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002610 // Final check: does the caller hold a permission?
2611 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002612 }
2613
2614 @Override
2615 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2616 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2617
Jeff Sharkey53313d72017-07-13 16:47:32 -06002618 final String fake = SystemProperties.get("fw.fake_plan");
2619 if (!TextUtils.isEmpty(fake)) {
2620 final List<SubscriptionPlan> plans = new ArrayList<>();
2621 if ("month_hard".equals(fake)) {
2622 plans.add(SubscriptionPlan.Builder
2623 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2624 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002625 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2626 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2627 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2628 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2629 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002630 plans.add(SubscriptionPlan.Builder
2631 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2632 .setTitle("G-Mobile Happy")
2633 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2634 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2635 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2636 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2637 .build());
2638 plans.add(SubscriptionPlan.Builder
2639 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2640 .setTitle("G-Mobile, Charged after limit")
2641 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2642 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2643 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2644 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2645 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002646 } else if ("month_soft".equals(fake)) {
2647 plans.add(SubscriptionPlan.Builder
2648 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2649 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2650 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2651 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002652 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2653 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2654 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2655 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2656 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002657 plans.add(SubscriptionPlan.Builder
2658 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2659 .setTitle("G-Mobile, Throttled after limit")
2660 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2661 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2662 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2663 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2664 .build());
2665 plans.add(SubscriptionPlan.Builder
2666 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2667 .setTitle("G-Mobile, No data connection after limit")
2668 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2669 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2670 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2671 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2672 .build());
2673
Jeff Sharkey53313d72017-07-13 16:47:32 -06002674 } else if ("month_none".equals(fake)) {
2675 plans.add(SubscriptionPlan.Builder
2676 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2677 .setTitle("G-Mobile")
2678 .build());
2679 } else if ("prepaid".equals(fake)) {
2680 plans.add(SubscriptionPlan.Builder
2681 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2682 ZonedDateTime.now().plusDays(10))
2683 .setTitle("G-Mobile")
2684 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2685 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2686 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2687 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2688 .build());
2689 } else if ("prepaid_crazy".equals(fake)) {
2690 plans.add(SubscriptionPlan.Builder
2691 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2692 ZonedDateTime.now().plusDays(10))
2693 .setTitle("G-Mobile Anytime")
2694 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2695 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2696 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2697 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2698 .build());
2699 plans.add(SubscriptionPlan.Builder
2700 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2701 ZonedDateTime.now().plusDays(20))
2702 .setTitle("G-Mobile Nickel Nights")
2703 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002704 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2705 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002706 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2707 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2708 .build());
2709 plans.add(SubscriptionPlan.Builder
2710 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2711 ZonedDateTime.now().plusDays(20))
2712 .setTitle("G-Mobile Bonus 3G")
2713 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002714 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002715 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2716 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2717 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2718 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002719 } else if ("unlimited".equals(fake)) {
2720 plans.add(SubscriptionPlan.Builder
2721 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2722 ZonedDateTime.now().plusDays(10))
2723 .setTitle("G-Mobile Awesome")
2724 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2725 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2726 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2727 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2728 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002729 }
2730 return plans.toArray(new SubscriptionPlan[plans.size()]);
2731 }
2732
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002733 synchronized (mUidRulesFirstLock) {
2734 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002735 // Only give out plan details to the package that defined them,
2736 // so that we don't risk leaking plans between apps. We always
2737 // let in core system components (like the Settings app).
2738 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2739 if (Objects.equals(ownerPackage, callingPackage)
2740 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2741 return mSubscriptionPlans.get(subId);
2742 } else {
2743 Log.w(TAG, "Not returning plans because caller " + callingPackage
2744 + " doesn't match owner " + ownerPackage);
2745 return null;
2746 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002747 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002748 }
2749 }
2750
2751 @Override
2752 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2753 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2754
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002755 for (SubscriptionPlan plan : plans) {
2756 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002757 }
2758
2759 final long token = Binder.clearCallingIdentity();
2760 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002761 maybeRefreshTrustedTime();
2762 synchronized (mUidRulesFirstLock) {
2763 synchronized (mNetworkPoliciesSecondLock) {
2764 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002765 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002766
2767 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
2768 .getSubscriberId(subId);
2769 ensureActiveMobilePolicyAL(subId, subscriberId);
2770 maybeUpdateMobilePolicyCycleAL(subId);
2771 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002772 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002773 }
2774 } finally {
2775 Binder.restoreCallingIdentity(token);
2776 }
2777 }
2778
2779 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002780 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002781 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002782
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002783 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2784
Dianne Hackborn497175b2014-07-01 12:56:08 -07002785 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002786 for (String arg : args) {
2787 argSet.add(arg);
2788 }
2789
Felipe Lemef0823852016-06-08 13:43:08 -07002790 synchronized (mUidRulesFirstLock) {
2791 synchronized (mNetworkPoliciesSecondLock) {
2792 if (argSet.contains("--unsnooze")) {
2793 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2794 mNetworkPolicy.valueAt(i).clearSnooze();
2795 }
2796
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002797 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002798
2799 fout.println("Cleared snooze timestamps");
2800 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002801 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002802
Felipe Lemef0823852016-06-08 13:43:08 -07002803 fout.print("System ready: "); fout.println(mSystemReady);
2804 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2805 fout.print("Restrict power: "); fout.println(mRestrictPower);
2806 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002807 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2808
2809 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07002810 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002811 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002812 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2813 fout.println(mNetworkPolicy.valueAt(i).toString());
2814 }
2815 fout.decreaseIndent();
2816
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002817 fout.println();
2818 fout.println("Subscription plans:");
2819 fout.increaseIndent();
2820 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2821 final int subId = mSubscriptionPlans.keyAt(i);
2822 fout.println("Subscriber ID " + subId + ":");
2823 fout.increaseIndent();
2824 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2825 if (!ArrayUtils.isEmpty(plans)) {
2826 for (SubscriptionPlan plan : plans) {
2827 fout.println(plan);
2828 }
2829 }
2830 fout.decreaseIndent();
2831 }
2832 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002833
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002834 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07002835 fout.println("Policy for UIDs:");
2836 fout.increaseIndent();
2837 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002838 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002839 final int uid = mUidPolicy.keyAt(i);
2840 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002841 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002842 fout.print(uid);
2843 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002844 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002845 fout.println();
2846 }
2847 fout.decreaseIndent();
2848
2849 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2850 if (size > 0) {
2851 fout.println("Power save whitelist (except idle) app ids:");
2852 fout.increaseIndent();
2853 for (int i = 0; i < size; i++) {
2854 fout.print("UID=");
2855 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2856 fout.print(": ");
2857 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2858 fout.println();
2859 }
2860 fout.decreaseIndent();
2861 }
2862
2863 size = mPowerSaveWhitelistAppIds.size();
2864 if (size > 0) {
2865 fout.println("Power save whitelist app ids:");
2866 fout.increaseIndent();
2867 for (int i = 0; i < size; i++) {
2868 fout.print("UID=");
2869 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2870 fout.print(": ");
2871 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2872 fout.println();
2873 }
2874 fout.decreaseIndent();
2875 }
2876
Felipe Lemef0823852016-06-08 13:43:08 -07002877 size = mDefaultRestrictBackgroundWhitelistUids.size();
2878 if (size > 0) {
2879 fout.println("Default restrict background whitelist uids:");
2880 fout.increaseIndent();
2881 for (int i = 0; i < size; i++) {
2882 fout.print("UID=");
2883 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2884 fout.println();
2885 }
2886 fout.decreaseIndent();
2887 }
2888
2889 size = mRestrictBackgroundWhitelistRevokedUids.size();
2890 if (size > 0) {
2891 fout.println("Default restrict background whitelist uids revoked by users:");
2892 fout.increaseIndent();
2893 for (int i = 0; i < size; i++) {
2894 fout.print("UID=");
2895 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2896 fout.println();
2897 }
2898 fout.decreaseIndent();
2899 }
2900
2901 final SparseBooleanArray knownUids = new SparseBooleanArray();
2902 collectKeys(mUidState, knownUids);
2903 collectKeys(mUidRules, knownUids);
2904
2905 fout.println("Status for all known UIDs:");
2906 fout.increaseIndent();
2907 size = knownUids.size();
2908 for (int i = 0; i < size; i++) {
2909 final int uid = knownUids.keyAt(i);
2910 fout.print("UID=");
2911 fout.print(uid);
2912
2913 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2914 fout.print(" state=");
2915 fout.print(state);
2916 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2917 fout.print(" (fg)");
2918 } else {
2919 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2920 ? " (fg svc)" : " (bg)");
2921 }
2922
2923 final int uidRules = mUidRules.get(uid, RULE_NONE);
2924 fout.print(" rules=");
2925 fout.print(uidRulesToString(uidRules));
2926 fout.println();
2927 }
2928 fout.decreaseIndent();
2929
2930 fout.println("Status for just UIDs with rules:");
2931 fout.increaseIndent();
2932 size = mUidRules.size();
2933 for (int i = 0; i < size; i++) {
2934 final int uid = mUidRules.keyAt(i);
2935 fout.print("UID=");
2936 fout.print(uid);
2937 final int uidRules = mUidRules.get(uid, RULE_NONE);
2938 fout.print(" rules=");
2939 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002940 fout.println();
2941 }
2942 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08002943
2944 fout.println("Observed uid state changes:");
2945 fout.increaseIndent();
2946 mObservedHistory.dumpUL(fout);
2947 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002948 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002949 }
2950 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002951
2952 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002953 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002954 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002955 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002956 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002957 }
2958
2959 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002960 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002961 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2962
Felipe Lemef0823852016-06-08 13:43:08 -07002963 synchronized (mUidRulesFirstLock) {
2964 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002965 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002966 }
2967
Felipe Lemef0823852016-06-08 13:43:08 -07002968 private boolean isUidForegroundUL(int uid) {
2969 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002970 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2971 }
2972
Felipe Lemef0823852016-06-08 13:43:08 -07002973 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002974 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002975 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002976 }
2977
Felipe Lemef0823852016-06-08 13:43:08 -07002978 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002979 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2980 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2981 }
2982
Felipe Lemef0823852016-06-08 13:43:08 -07002983 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002984 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002985 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002986 }
2987
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002988 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002989 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002990 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2991 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002992 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002993 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002994 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2995 try {
2996 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2997 if (oldUidState != uidState) {
2998 // state changed, push updated rules
2999 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003000 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3001 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3002 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003003 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003004 if (mDeviceIdleMode) {
3005 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003006 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003007 if (mRestrictPower) {
3008 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003009 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003010 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003011 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003012 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003013 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003014 } finally {
3015 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003016 }
3017 }
3018
Felipe Lemef0823852016-06-08 13:43:08 -07003019 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003020 final int index = mUidState.indexOfKey(uid);
3021 if (index >= 0) {
3022 final int oldUidState = mUidState.valueAt(index);
3023 mUidState.removeAt(index);
3024 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003025 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003026 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003027 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003028 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003029 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003030 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003031 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003032 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003033 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003034 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003035 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003036 }
3037 }
3038
Felipe Lemef28983d2016-03-25 12:18:23 -07003039 // adjust stats accounting based on foreground status
3040 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003041 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3042 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3043 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3044 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003045 try {
3046 mNetworkStats.setUidForeground(uid, uidForeground);
3047 } catch (RemoteException e) {
3048 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003049 } finally {
3050 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003051 }
3052 }
3053
Sudheer Shankac9d94072017-02-22 22:13:55 +00003054 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3055 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003056 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003057 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003058 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003059 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003060 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003061 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003062 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003063 }
3064
Felipe Lemef0823852016-06-08 13:43:08 -07003065 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003066 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3067 try {
3068 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3069 mUidFirewallPowerSaveRules);
3070 } finally {
3071 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3072 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003073 }
3074
Felipe Lemef0823852016-06-08 13:43:08 -07003075 void updateRuleForRestrictPowerUL(int uid) {
3076 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003077 }
3078
Felipe Lemef0823852016-06-08 13:43:08 -07003079 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003080 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3081 try {
3082 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3083 mUidFirewallDozableRules);
3084 } finally {
3085 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3086 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003087 }
3088
Felipe Lemef0823852016-06-08 13:43:08 -07003089 void updateRuleForDeviceIdleUL(int uid) {
3090 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003091 }
3092
Felipe Lemef28983d2016-03-25 12:18:23 -07003093 // NOTE: since both fw_dozable and fw_powersave uses the same map
3094 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003095 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003096 SparseIntArray rules) {
3097 if (enabled) {
3098 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003099 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003100 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003101 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003102 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003103 for (int ui = users.size() - 1; ui >= 0; ui--) {
3104 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003105 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3106 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3107 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3108 updateRulesForWhitelistedAppIds(uidRules,
3109 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003110 }
3111 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003112 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003113 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003114 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3115 }
3116 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003117 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
3118 } else {
3119 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003120 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003121 }
3122
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003123 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3124 final SparseBooleanArray whitelistedAppIds, int userId) {
3125 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3126 if (whitelistedAppIds.valueAt(i)) {
3127 final int appId = whitelistedAppIds.keyAt(i);
3128 final int uid = UserHandle.getUid(userId, appId);
3129 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3130 }
3131 }
3132 }
3133
3134 /**
3135 * @param deviceIdleMode if true then we don't consider
3136 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3137 * whitelisted.
3138 */
3139 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003140 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003141 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3142 || mPowerSaveWhitelistAppIds.get(appId);
3143 if (!deviceIdleMode) {
3144 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3145 }
3146 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003147 }
3148
Felipe Lemef28983d2016-03-25 12:18:23 -07003149 // NOTE: since both fw_dozable and fw_powersave uses the same map
3150 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003151 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003152 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003153 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3154 chain == FIREWALL_CHAIN_DOZABLE);
3155 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003156 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003157 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003158 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003159 }
3160 }
3161 }
3162
Felipe Lemef0823852016-06-08 13:43:08 -07003163 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003164 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3165 try {
3166 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3167 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003168
Felipe Leme873a83a2016-09-07 11:34:10 -07003169 // Fully update the app idle firewall chain.
3170 final List<UserInfo> users = mUserManager.getUsers();
3171 for (int ui = users.size() - 1; ui >= 0; ui--) {
3172 UserInfo user = users.get(ui);
3173 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3174 for (int uid : idleUids) {
3175 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3176 // quick check: if this uid doesn't have INTERNET permission, it
3177 // doesn't have network access anyway, so it is a waste to mess
3178 // with it here.
3179 if (hasInternetPermissions(uid)) {
3180 uidRules.put(uid, FIREWALL_RULE_DENY);
3181 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003182 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003183 }
3184 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003185
Felipe Lemebc853dd2016-09-08 13:26:55 -07003186 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003187 } finally {
3188 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3189 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003190 }
3191
Felipe Lemef0823852016-06-08 13:43:08 -07003192 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003193 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003194
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003195 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3196 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3197 }
3198 try {
3199 int appId = UserHandle.getAppId(uid);
3200 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3201 && !isUidForegroundOnRestrictPowerUL(uid)) {
3202 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3203 } else {
3204 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3205 }
3206 } finally {
3207 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003208 }
3209 }
3210
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003211 /**
3212 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3213 * changed.
3214 */
Felipe Lemef0823852016-06-08 13:43:08 -07003215 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003216 boolean paroled = mUsageStats.isAppIdleParoleOn();
3217 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003218 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003219
3220 int ruleCount = mUidFirewallStandbyRules.size();
3221 for (int i = 0; i < ruleCount; i++) {
3222 int uid = mUidFirewallStandbyRules.keyAt(i);
3223 int oldRules = mUidRules.get(uid);
3224 if (enableChain) {
3225 // Chain wasn't enabled before and the other power-related
3226 // chains are whitelists, so we can clear the
3227 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3228 // the effective rules result in blocking network access.
3229 oldRules &= MASK_METERED_NETWORKS;
3230 } else {
3231 // Skip if it had no restrictions to begin with
3232 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3233 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003234 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3235 if (newUidRules == RULE_NONE) {
3236 mUidRules.delete(uid);
3237 } else {
3238 mUidRules.put(uid, newUidRules);
3239 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003240 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003241 }
3242
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003243 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003244 * Update rules that might be changed by {@link #mRestrictBackground},
3245 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003246 */
Felipe Lemef0823852016-06-08 13:43:08 -07003247 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003248 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3249 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3250 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3251 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003252 try {
Felipe Leme09700462016-09-08 09:33:48 -07003253 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003254 updateRulesForRestrictPowerUL();
3255 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003256
Felipe Leme873a83a2016-09-07 11:34:10 -07003257 // If the set of restricted networks may have changed, re-evaluate those.
3258 if (restrictedNetworksChanged) {
3259 normalizePoliciesNL();
3260 updateNetworkRulesNL();
3261 }
3262 } finally {
3263 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003264 }
3265 }
3266
Felipe Leme09700462016-09-08 09:33:48 -07003267 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003268 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003269 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3270 try {
3271 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003272 updateRulesForPowerSaveUL();
3273 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3274 } finally {
3275 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3276 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003277 }
3278
Felipe Lemef0823852016-06-08 13:43:08 -07003279 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003280 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3281 try {
3282 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3283 } finally {
3284 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3285 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003286 }
3287
3288 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3289 private static final int TYPE_RESTRICT_POWER = 2;
3290 @Retention(RetentionPolicy.SOURCE)
3291 @IntDef(flag = false, value = {
3292 TYPE_RESTRICT_BACKGROUND,
3293 TYPE_RESTRICT_POWER,
3294 })
3295 public @interface RestrictType {
3296 }
3297
3298 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003299 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003300 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3301 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3302 }
3303 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003304 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003305
3306 final PackageManager pm = mContext.getPackageManager();
3307 final List<UserInfo> users;
3308 final List<ApplicationInfo> apps;
3309
3310 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3311 try {
3312 users = mUserManager.getUsers();
3313 } finally {
3314 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3315 }
3316 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3317 try {
3318 apps = pm.getInstalledApplications(
3319 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3320 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3321 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3322 } finally {
3323 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3324 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003325
Felipe Leme873a83a2016-09-07 11:34:10 -07003326 final int usersSize = users.size();
3327 final int appsSize = apps.size();
3328 for (int i = 0; i < usersSize; i++) {
3329 final UserInfo user = users.get(i);
3330 for (int j = 0; j < appsSize; j++) {
3331 final ApplicationInfo app = apps.get(j);
3332 final int uid = UserHandle.getUid(user.id, app.uid);
3333 switch (type) {
3334 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003335 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003336 break;
3337 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003338 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003339 break;
3340 default:
3341 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3342 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003343 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003344 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003345 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003346 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003347 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003348 }
3349
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003350 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003351 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003352 final int numUsers = users.size();
3353 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003354 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003355 int uid = UserHandle.getUid(user.id, appId);
3356 // Update external firewall rules.
3357 updateRuleForAppIdleUL(uid);
3358 updateRuleForDeviceIdleUL(uid);
3359 updateRuleForRestrictPowerUL(uid);
3360 // Update internal rules.
3361 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003362 }
3363 }
3364
Felipe Leme70c57c22016-03-29 10:45:13 -07003365 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3366 // methods below could be merged into a isUidValidForRules() method.
3367 private boolean isUidValidForBlacklistRules(int uid) {
3368 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003369 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003370 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003371 return true;
3372 }
3373
3374 return false;
3375 }
3376
Felipe Leme70c57c22016-03-29 10:45:13 -07003377 private boolean isUidValidForWhitelistRules(int uid) {
3378 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3379 }
3380
Amith Yamasani15e472352015-04-24 19:06:07 -07003381 private boolean isUidIdle(int uid) {
3382 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3383 final int userId = UserHandle.getUserId(uid);
3384
songjinshi0655edd2016-05-18 19:55:32 +08003385 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003386 for (String packageName : packages) {
3387 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3388 return false;
3389 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003390 }
3391 }
3392 return true;
3393 }
3394
3395 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003396 * Checks if an uid has INTERNET permissions.
3397 * <p>
3398 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003399 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003400 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003401 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003402 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003403 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003404 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003405 }
3406 } catch (RemoteException e) {
3407 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003408 return true;
3409 }
3410
3411 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003412 * Clears all state - internal and external - associated with an UID.
3413 */
3414 private void onUidDeletedUL(int uid) {
3415 // First cleanup in-memory state synchronously...
3416 mUidRules.delete(uid);
3417 mUidPolicy.delete(uid);
3418 mUidFirewallStandbyRules.delete(uid);
3419 mUidFirewallDozableRules.delete(uid);
3420 mUidFirewallPowerSaveRules.delete(uid);
3421 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3422 mPowerSaveWhitelistAppIds.delete(uid);
3423 mPowerSaveTempWhitelistAppIds.delete(uid);
3424
3425 // ...then update iptables asynchronously.
3426 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3427 }
3428
3429 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003430 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003431 *
Felipe Leme781ba142016-05-09 16:24:48 -07003432 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003433 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003434 * <li>Doze mode
3435 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003436 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003437 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003438 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003439 *
3440 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003441 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003442 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003443 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003444 updateRuleForDeviceIdleUL(uid);
3445 updateRuleForAppIdleUL(uid);
3446 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003447
3448 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003449 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003450
3451 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003452 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003453 }
3454
Felipe Leme70c57c22016-03-29 10:45:13 -07003455 /**
3456 * Applies network rules to bandwidth controllers based on process state and user-defined
3457 * restrictions (blacklist / whitelist).
3458 *
3459 * <p>
3460 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3461 * networks:
3462 * <ul>
3463 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3464 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3465 * also blacklisted.
3466 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3467 * no UIDs other those whitelisted will have access.
3468 * <ul>
3469 *
3470 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3471 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3472 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3473 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003474 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003475 * {@link INetworkManagementService}, but this method should also be called in events (like
3476 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3477 * following rules should also be applied:
3478 *
3479 * <ul>
3480 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3481 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3482 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3483 * {@code bw_penalty_box}.
3484 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3485 * </ul>
3486 *
3487 * <p>For optimization, the rules are only applied on user apps that have internet access
3488 * permission, since there is no need to change the {@code iptables} rule if the app does not
3489 * have permission to use the internet.
3490 *
3491 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003492 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003493 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003494 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003495 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3496 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3497 "updateRulesForDataUsageRestrictionsUL: " + uid);
3498 }
3499 try {
3500 updateRulesForDataUsageRestrictionsULInner(uid);
3501 } finally {
3502 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3503 }
3504 }
3505
3506 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003507 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003508 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003509 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003510 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003511
Dianne Hackborn497175b2014-07-01 12:56:08 -07003512 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003513 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003514 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003515
Felipe Leme781ba142016-05-09 16:24:48 -07003516 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003517 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003518 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3519 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003520
Felipe Leme70c57c22016-03-29 10:45:13 -07003521 // First step: define the new rule based on user restrictions and foreground state.
3522 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003523 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3524 newRule = RULE_TEMPORARY_ALLOW_METERED;
3525 } else if (isWhitelisted) {
3526 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003527 }
3528 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003529 if (isBlacklisted) {
3530 newRule = RULE_REJECT_METERED;
3531 } else if (mRestrictBackground && isWhitelisted) {
3532 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003533 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003534 }
Felipe Leme781ba142016-05-09 16:24:48 -07003535 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003536
Felipe Lemef28983d2016-03-25 12:18:23 -07003537 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003538 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003539 + ": isForeground=" +isForeground
3540 + ", isBlacklisted=" + isBlacklisted
3541 + ", isWhitelisted=" + isWhitelisted
3542 + ", oldRule=" + uidRulesToString(oldRule)
3543 + ", newRule=" + uidRulesToString(newRule)
3544 + ", newUidRules=" + uidRulesToString(newUidRules)
3545 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003546 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003547
Felipe Leme46c4fc32016-05-04 09:21:43 -07003548 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003549 mUidRules.delete(uid);
3550 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003551 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003552 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003553
Felipe Leme70c57c22016-03-29 10:45:13 -07003554 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003555 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003556 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003557 // Temporarily whitelist foreground app, removing from blacklist if necessary
3558 // (since bw_penalty_box prevails over bw_happy_box).
3559
3560 setMeteredNetworkWhitelist(uid, true);
3561 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3562 // but ideally it should be just:
3563 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003564 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003565 setMeteredNetworkBlacklist(uid, false);
3566 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003567 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003568 // Remove temporary whitelist from app that is not on foreground anymore.
3569
3570 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3571 // but ideally they should be just:
3572 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3573 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003574 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003575 setMeteredNetworkWhitelist(uid, false);
3576 }
Felipe Leme781ba142016-05-09 16:24:48 -07003577 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003578 setMeteredNetworkBlacklist(uid, true);
3579 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003580 } else if (hasRule(newRule, RULE_REJECT_METERED)
3581 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003582 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003583 setMeteredNetworkBlacklist(uid, isBlacklisted);
Hugo Benichi2966c182017-03-28 17:17:13 +09003584 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003585 // Since blacklist prevails over whitelist, we need to handle the special case
3586 // where app is whitelisted and blacklisted at the same time (although such
3587 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003588 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003589 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003590 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3591 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003592 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003593 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003594 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003595 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003596 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3597 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003598 + ", whitelisted=" + isWhitelisted
3599 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003600 + ", newRule=" + uidRulesToString(newUidRules)
3601 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003602 }
Felipe Leme781ba142016-05-09 16:24:48 -07003603
Sudheer Shankac9d94072017-02-22 22:13:55 +00003604 // Dispatch changed rule to existing listeners.
3605 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003606 }
3607 }
3608
3609 /**
3610 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3611 * listeners in case of change.
3612 * <p>
3613 * There are 3 power-related rules that affects whether an app has background access on
3614 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3615 * restriction, it's added to the equivalent firewall chain:
3616 * <ul>
3617 * <li>App is idle: {@code fw_standby} firewall chain.
3618 * <li>Device is idle: {@code fw_dozable} firewall chain.
3619 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3620 * </ul>
3621 * <p>
3622 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3623 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3624 * <p>
3625 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3626 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003627 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003628 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3629
Sudheer Shankac9d94072017-02-22 22:13:55 +00003630 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003631
Sudheer Shankac9d94072017-02-22 22:13:55 +00003632 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003633 mUidRules.delete(uid);
3634 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003635 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003636 }
3637 }
3638
3639 /**
3640 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3641 *
3642 * @param uid the uid of the app to update rules for
3643 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3644 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3645 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003646 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003647 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003648 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003649 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3650 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3651 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3652 + (paroled ? "P" : "-"));
3653 }
3654 try {
3655 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3656 } finally {
3657 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3658 }
3659 }
3660
3661 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003662 if (!isUidValidForBlacklistRules(uid)) {
3663 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003664 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003665 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003666
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003667 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003668 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003669 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003670
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003671 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003672 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3673 int newRule = RULE_NONE;
3674
3675 // First step: define the new rule based on user restrictions and foreground state.
3676
3677 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3678 // by considering the foreground and non-foreground states.
3679 if (isForeground) {
3680 if (restrictMode) {
3681 newRule = RULE_ALLOW_ALL;
3682 }
3683 } else if (restrictMode) {
3684 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3685 }
3686
3687 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3688
3689 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003690 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003691 + ", isIdle: " + isIdle
3692 + ", mRestrictPower: " + mRestrictPower
3693 + ", mDeviceIdleMode: " + mDeviceIdleMode
3694 + ", isForeground=" + isForeground
3695 + ", isWhitelisted=" + isWhitelisted
3696 + ", oldRule=" + uidRulesToString(oldRule)
3697 + ", newRule=" + uidRulesToString(newRule)
3698 + ", newUidRules=" + uidRulesToString(newUidRules)
3699 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3700 }
3701
Felipe Leme781ba142016-05-09 16:24:48 -07003702 // Second step: notify listeners if state changed.
3703 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003704 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003705 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003706 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003707 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3708 } else {
3709 // All scenarios should have been covered above
3710 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3711 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003712 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003713 + ", newRule=" + uidRulesToString(newUidRules)
3714 + ", oldRule=" + uidRulesToString(oldUidRules));
3715 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003716 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003717 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003718
Sudheer Shankac9d94072017-02-22 22:13:55 +00003719 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003720 }
3721
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003722 private class AppIdleStateChangeListener
3723 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3724
3725 @Override
3726 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3727 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003728 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3729 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003730 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003731 synchronized (mUidRulesFirstLock) {
3732 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003733 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003734 }
3735 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003736 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003737 }
3738
3739 @Override
3740 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003741 synchronized (mUidRulesFirstLock) {
3742 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003743 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003744 }
3745 }
3746
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003747 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3748 if (listener != null) {
3749 try {
3750 listener.onUidRulesChanged(uid, uidRules);
3751 } catch (RemoteException ignored) {
3752 }
3753 }
3754 }
3755
3756 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3757 String[] meteredIfaces) {
3758 if (listener != null) {
3759 try {
3760 listener.onMeteredIfacesChanged(meteredIfaces);
3761 } catch (RemoteException ignored) {
3762 }
3763 }
3764 }
3765
3766 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3767 boolean restrictBackground) {
3768 if (listener != null) {
3769 try {
3770 listener.onRestrictBackgroundChanged(restrictBackground);
3771 } catch (RemoteException ignored) {
3772 }
3773 }
3774 }
3775
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003776 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3777 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003778 if (listener != null) {
3779 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003780 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003781 } catch (RemoteException ignored) {
3782 }
3783 }
3784 }
3785
Makoto Onuki8e777332017-03-28 11:25:47 -07003786 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003787 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003788 public boolean handleMessage(Message msg) {
3789 switch (msg.what) {
3790 case MSG_RULES_CHANGED: {
3791 final int uid = msg.arg1;
3792 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003793 final int length = mListeners.beginBroadcast();
3794 for (int i = 0; i < length; i++) {
3795 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3796 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003797 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003798 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003799 return true;
3800 }
3801 case MSG_METERED_IFACES_CHANGED: {
3802 final String[] meteredIfaces = (String[]) msg.obj;
3803 final int length = mListeners.beginBroadcast();
3804 for (int i = 0; i < length; i++) {
3805 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003806 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003807 }
3808 mListeners.finishBroadcast();
3809 return true;
3810 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003811 case MSG_LIMIT_REACHED: {
3812 final String iface = (String) msg.obj;
3813
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003814 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003815 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003816 if (mMeteredIfaces.contains(iface)) {
3817 try {
3818 // force stats update to make sure we have
3819 // numbers that caused alert to trigger.
3820 mNetworkStats.forceUpdate();
3821 } catch (RemoteException e) {
3822 // ignored; service lives in system_server
3823 }
3824
Felipe Lemef0823852016-06-08 13:43:08 -07003825 updateNetworkEnabledNL();
3826 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003827 }
3828 }
3829 return true;
3830 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003831 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3832 final boolean restrictBackground = msg.arg1 != 0;
3833 final int length = mListeners.beginBroadcast();
3834 for (int i = 0; i < length; i++) {
3835 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003836 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003837 }
3838 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003839 final Intent intent =
3840 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3841 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3842 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3843 return true;
3844 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003845 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003846 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003847 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003848 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003849 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07003850 final int length = mListeners.beginBroadcast();
3851 for (int i = 0; i < length; i++) {
3852 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003853 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003854 }
3855 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003856 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3857 if (notifyApp.booleanValue()) {
3858 broadcastRestrictBackgroundChanged(uid, notifyApp);
3859 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003860 return true;
3861 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003862 case MSG_ADVISE_PERSIST_THRESHOLD: {
3863 final long lowestRule = (Long) msg.obj;
3864 try {
3865 // make sure stats are recorded frequently enough; we aim
3866 // for 2MB threshold for 2GB/month rules.
3867 final long persistThreshold = lowestRule / 1000;
3868 mNetworkStats.advisePersistThreshold(persistThreshold);
3869 } catch (RemoteException e) {
3870 // ignored; service lives in system_server
3871 }
3872 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003873 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003874 case MSG_UPDATE_INTERFACE_QUOTA: {
3875 removeInterfaceQuota((String) msg.obj);
3876 // int params need to be stitched back into a long
3877 setInterfaceQuota((String) msg.obj,
3878 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3879 return true;
3880 }
3881 case MSG_REMOVE_INTERFACE_QUOTA: {
3882 removeInterfaceQuota((String) msg.obj);
3883 return true;
3884 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003885 case MSG_SET_FIREWALL_RULES: {
3886 final int chain = msg.arg1;
3887 final int toggle = msg.arg2;
3888 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3889 if (uidRules != null) {
3890 setUidFirewallRules(chain, uidRules);
3891 }
3892 if (toggle != CHAIN_TOGGLE_NONE) {
3893 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3894 }
3895 return true;
3896 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003897 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3898 resetUidFirewallRules(msg.arg1);
3899 return true;
3900 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003901 default: {
3902 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003903 }
3904 }
3905 }
Makoto Onuki8e777332017-03-28 11:25:47 -07003906 };
3907
3908 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
3909 @Override
3910 public boolean handleMessage(Message msg) {
3911 switch (msg.what) {
3912 case UID_MSG_STATE_CHANGED: {
3913 final int uid = msg.arg1;
3914 final int procState = msg.arg2;
3915 final long procStateSeq = (Long) msg.obj;
3916
3917 handleUidChanged(uid, procState, procStateSeq);
3918 return true;
3919 }
3920 case UID_MSG_GONE: {
3921 final int uid = msg.arg1;
3922 handleUidGone(uid);
3923 return true;
3924 }
3925 default: {
3926 return false;
3927 }
3928 }
3929 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003930
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003931 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003932
Makoto Onuki8e777332017-03-28 11:25:47 -07003933 void handleUidChanged(int uid, int procState, long procStateSeq) {
3934 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
3935 try {
3936 synchronized (mUidRulesFirstLock) {
3937 // We received a uid state change callback, add it to the history so that it
3938 // will be useful for debugging.
3939 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
3940 // Now update the network policy rules as per the updated uid state.
3941 updateUidStateUL(uid, procState);
3942 // Updating the network rules is done, so notify AMS about this.
3943 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
3944 }
3945 } finally {
3946 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3947 }
3948 }
3949
3950 void handleUidGone(int uid) {
3951 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
3952 try {
3953 synchronized (mUidRulesFirstLock) {
3954 removeUidStateUL(uid);
3955 }
3956 } finally {
3957 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3958 }
3959 }
3960
Felipe Leme57e3d312016-08-23 14:42:52 -07003961 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3962 final PackageManager pm = mContext.getPackageManager();
3963 final String[] packages = pm.getPackagesForUid(uid);
3964 if (packages != null) {
3965 final int userId = UserHandle.getUserId(uid);
3966 for (String packageName : packages) {
3967 final Intent intent =
3968 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3969 intent.setPackage(packageName);
3970 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3971 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3972 }
3973 }
3974 }
3975
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003976 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003977 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003978 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003979 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003980 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003981 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003982 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003983 }
3984 }
3985
3986 private void removeInterfaceQuota(String iface) {
3987 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003988 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003989 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003990 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003991 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003992 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003993 }
3994 }
3995
Felipe Leme70c57c22016-03-29 10:45:13 -07003996 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3997 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003998 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003999 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004000 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004001 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4002 } catch (RemoteException e) {
4003 // ignored; service lives in system_server
4004 }
4005 }
4006
4007 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4008 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4009 try {
4010 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4011 } catch (IllegalStateException e) {
4012 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004013 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004014 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004015 }
4016 }
4017
Felipe Lemebc853dd2016-09-08 13:26:55 -07004018 private static final int CHAIN_TOGGLE_NONE = 0;
4019 private static final int CHAIN_TOGGLE_ENABLE = 1;
4020 private static final int CHAIN_TOGGLE_DISABLE = 2;
4021 @Retention(RetentionPolicy.SOURCE)
4022 @IntDef(flag = false, value = {
4023 CHAIN_TOGGLE_NONE,
4024 CHAIN_TOGGLE_ENABLE,
4025 CHAIN_TOGGLE_DISABLE
4026 })
4027 public @interface ChainToggleType {
4028 }
4029
4030 /**
4031 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
4032 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
4033 *
4034 * @param chain firewall chain.
4035 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4036 * @param toggle whether the chain should be enabled, disabled, or not changed.
4037 */
4038 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
4039 @ChainToggleType int toggle) {
4040 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
4041 }
4042
Amith Yamasani15e472352015-04-24 19:06:07 -07004043 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004044 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4045 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4046 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004047 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004048 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004049 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004050 int size = uidRules.size();
4051 int[] uids = new int[size];
4052 int[] rules = new int[size];
4053 for(int index = size - 1; index >= 0; --index) {
4054 uids[index] = uidRules.keyAt(index);
4055 rules[index] = uidRules.valueAt(index);
4056 }
4057 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004058 } catch (IllegalStateException e) {
4059 Log.wtf(TAG, "problem setting firewall uid rules", e);
4060 } catch (RemoteException e) {
4061 // ignored; service lives in system_server
4062 }
4063 }
4064
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004065 /**
4066 * Add or remove a uid to the firewall blacklist for all network ifaces.
4067 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004068 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004069 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4070 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4071 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004072 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004073 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004074 if (chain == FIREWALL_CHAIN_DOZABLE) {
4075 mUidFirewallDozableRules.put(uid, rule);
4076 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4077 mUidFirewallStandbyRules.put(uid, rule);
4078 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4079 mUidFirewallPowerSaveRules.put(uid, rule);
4080 }
4081
4082 try {
4083 mNetworkManager.setFirewallUidRule(chain, uid, rule);
4084 } catch (IllegalStateException e) {
4085 Log.wtf(TAG, "problem setting firewall uid rules", e);
4086 } catch (RemoteException e) {
4087 // ignored; service lives in system_server
4088 }
4089 } finally {
4090 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004091 }
4092 }
4093
4094 /**
4095 * Add or remove a uid to the firewall blacklist for all network ifaces.
4096 */
Felipe Lemef0823852016-06-08 13:43:08 -07004097 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004098 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4099 mFirewallChainStates.get(chain) == enable) {
4100 // All is the same, nothing to do.
4101 return;
4102 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004103 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004104 try {
4105 mNetworkManager.setFirewallChainEnabled(chain, enable);
4106 } catch (IllegalStateException e) {
4107 Log.wtf(TAG, "problem enable firewall chain", e);
4108 } catch (RemoteException e) {
4109 // ignored; service lives in system_server
4110 }
4111 }
4112
Felipe Leme03e95e22016-09-09 09:25:31 -07004113 /**
4114 * Resets all firewall rules associated with an UID.
4115 */
4116 private void resetUidFirewallRules(int uid) {
4117 try {
4118 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4119 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4120 mNetworkManager
4121 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4122 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4123 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4124 } catch (IllegalStateException e) {
4125 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4126 } catch (RemoteException e) {
4127 // ignored; service lives in system_server
4128 }
4129 }
4130
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004131 private long getTotalBytes(NetworkTemplate template, long start, long end) {
4132 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004133 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004134 } catch (RuntimeException e) {
4135 Slog.w(TAG, "problem reading network stats: " + e);
4136 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004137 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004138 // ignored; service lives in system_server
4139 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004140 }
4141 }
4142
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004143 private boolean isBandwidthControlEnabled() {
4144 final long token = Binder.clearCallingIdentity();
4145 try {
4146 return mNetworkManager.isBandwidthControlEnabled();
4147 } catch (RemoteException e) {
4148 // ignored; service lives in system_server
4149 return false;
4150 } finally {
4151 Binder.restoreCallingIdentity(token);
4152 }
4153 }
4154
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004155 /**
4156 * Try refreshing {@link #mTime} when stale.
4157 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07004158 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004159 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004160 mTime.forceRefresh();
4161 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004162 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004163
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004164 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004165 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
4166 }
4167
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004168 private static Intent buildAllowBackgroundDataIntent() {
4169 return new Intent(ACTION_ALLOW_BACKGROUND);
4170 }
4171
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004172 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4173 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
4174 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4175 return intent;
4176 }
4177
Wei Liu546cb772016-07-21 16:19:01 -07004178 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004179 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004180 intent.setComponent(ComponentName.unflattenFromString(
4181 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004182 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4183 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4184 return intent;
4185 }
4186
Wei Liu546cb772016-07-21 16:19:01 -07004187 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004188 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004189 intent.setComponent(ComponentName.unflattenFromString(
4190 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004191 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4192 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4193 return intent;
4194 }
4195
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004196 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004197 public void addIdleHandler(IdleHandler handler) {
4198 mHandler.getLooper().getQueue().addIdleHandler(handler);
4199 }
4200
jackqdyulei29c82ab2017-03-10 14:09:16 -08004201 @VisibleForTesting
4202 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4203 mRestrictBackgroundPowerState = result;
4204
4205 boolean restrictBackground = result.batterySaverEnabled;
4206 boolean shouldInvokeRestrictBackground;
4207 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4208 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4209
4210 if (result.globalBatterySaverEnabled) {
4211 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4212 // turn it on.
4213 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4214 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4215 localRestrictBgChangedInBsm = false;
4216 } else {
4217 // Try to restore the restrictBackground if it doesn't change in bsm
4218 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4219 restrictBackground = mRestrictBackgroundBeforeBsm;
4220 }
4221
4222 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004223 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004224 }
4225
4226 // Change it at last so setRestrictBackground() won't affect this variable
4227 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4228 }
4229
Jeff Sharkey1b861272011-05-22 00:34:52 -07004230 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4231 final int size = source.size();
4232 for (int i = 0; i < size; i++) {
4233 target.put(source.keyAt(i), true);
4234 }
4235 }
4236
Stuart Scottf1fb3972015-04-02 18:00:02 -07004237 @Override
4238 public void factoryReset(String subscriber) {
4239 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4240
Stuart Scotte3e314d2015-04-20 14:07:45 -07004241 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4242 return;
4243 }
4244
Stuart Scottf1fb3972015-04-02 18:00:02 -07004245 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004246 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004247 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4248 for (NetworkPolicy policy : policies) {
4249 if (policy.template.equals(template)) {
4250 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4251 policy.inferred = false;
4252 policy.clearSnooze();
4253 }
4254 }
4255 setNetworkPolicies(policies);
4256
4257 // Turn restrict background data off
4258 setRestrictBackground(false);
4259
Stuart Scotte3e314d2015-04-20 14:07:45 -07004260 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4261 // Remove app's "restrict background data" flag
4262 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4263 setUidPolicy(uid, POLICY_NONE);
4264 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004265 }
4266 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004267
Sudheer Shankab8f23162017-08-04 13:30:10 -07004268 @Override
4269 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4270 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4271 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4272 }
4273
4274 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4275 final int uidRules;
4276 final boolean isBackgroundRestricted;
4277 synchronized (mUidRulesFirstLock) {
4278 uidRules = mUidRules.get(uid, RULE_NONE);
4279 isBackgroundRestricted = mRestrictBackground;
4280 }
4281 if (hasRule(uidRules, RULE_REJECT_ALL)) {
4282 if (LOGV) logUidStatus(uid, "blocked by power restrictions");
4283 return true;
4284 }
4285 if (!isNetworkMetered) {
4286 if (LOGV) logUidStatus(uid, "allowed on unmetered network");
4287 return false;
4288 }
4289 if (hasRule(uidRules, RULE_REJECT_METERED)) {
4290 if (LOGV) logUidStatus(uid, "blacklisted on metered network");
4291 return true;
4292 }
4293 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4294 if (LOGV) logUidStatus(uid, "whitelisted on metered network");
4295 return false;
4296 }
4297 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4298 if (LOGV) logUidStatus(uid, "temporary whitelisted on metered network");
4299 return false;
4300 }
4301 if (isBackgroundRestricted) {
4302 if (LOGV) logUidStatus(uid, "blocked when background is restricted");
4303 return true;
4304 }
4305 if (LOGV) logUidStatus(uid, "allowed by default");
4306 return false;
4307 }
4308
Felipe Lemed17fda42016-04-29 11:12:45 -07004309 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4310
4311 @Override
4312 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004313 synchronized (mUidRulesFirstLock) {
4314 boolean changed = removeUserStateUL(userId, false);
4315 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004316 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004317 synchronized (mNetworkPoliciesSecondLock) {
4318 writePolicyAL();
4319 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004320 }
4321 }
4322 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004323
4324 /**
4325 * @return true if the given uid is restricted from doing networking on metered networks.
4326 */
4327 @Override
4328 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4329 final int uidRules;
4330 final boolean isBackgroundRestricted;
4331 synchronized (mUidRulesFirstLock) {
4332 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4333 isBackgroundRestricted = mRestrictBackground;
4334 }
4335 return isBackgroundRestricted
4336 && !hasRule(uidRules, RULE_ALLOW_METERED)
4337 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4338 }
4339
4340 /**
4341 * @return true if networking is blocked on the given interface for the given uid according
4342 * to current networking policies.
4343 */
4344 @Override
4345 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004346 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004347 synchronized (mNetworkPoliciesSecondLock) {
4348 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004349 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004350 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004351 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004352
4353 @Override
4354 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4355 synchronized (mUidRulesFirstLock) {
4356 if (added) {
4357 mPowerSaveTempWhitelistAppIds.put(appId, true);
4358 } else {
4359 mPowerSaveTempWhitelistAppIds.delete(appId);
4360 }
4361 updateRulesForTempWhitelistChangeUL(appId);
4362 }
4363 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004364 }
4365
4366 private static boolean hasRule(int uidRules, int rule) {
4367 return (uidRules & rule) != 0;
4368 }
4369
4370 private static void logUidStatus(int uid, String descr) {
4371 Slog.d(TAG, String.format("uid %d is %s", uid, descr));
Felipe Lemed17fda42016-04-29 11:12:45 -07004372 }
Sudheer Shankae7361852017-03-07 11:51:46 -08004373
4374 /**
4375 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
4376 * (uid, procStateSeq) pairs.
4377 */
4378 @VisibleForTesting
4379 public static final class ProcStateSeqHistory {
4380 private static final int INVALID_UID = -1;
4381
4382 /**
4383 * Denotes maximum number of items this history can hold.
4384 */
4385 private final int mMaxCapacity;
4386 /**
4387 * Used for storing the uid information.
4388 */
4389 private final int[] mUids;
4390 /**
4391 * Used for storing the sequence numbers associated with {@link #mUids}.
4392 */
4393 private final long[] mProcStateSeqs;
4394 /**
4395 * Points to the next available slot for writing (uid, procStateSeq) pair.
4396 */
4397 private int mHistoryNext;
4398
4399 public ProcStateSeqHistory(int maxCapacity) {
4400 mMaxCapacity = maxCapacity;
4401 mUids = new int[mMaxCapacity];
4402 Arrays.fill(mUids, INVALID_UID);
4403 mProcStateSeqs = new long[mMaxCapacity];
4404 }
4405
4406 @GuardedBy("mUidRulesFirstLock")
4407 public void addProcStateSeqUL(int uid, long procStateSeq) {
4408 mUids[mHistoryNext] = uid;
4409 mProcStateSeqs[mHistoryNext] = procStateSeq;
4410 mHistoryNext = increaseNext(mHistoryNext, 1);
4411 }
4412
4413 @GuardedBy("mUidRulesFirstLock")
4414 public void dumpUL(IndentingPrintWriter fout) {
4415 if (mUids[0] == INVALID_UID) {
4416 fout.println("NONE");
4417 return;
4418 }
4419 int index = mHistoryNext;
4420 do {
4421 index = increaseNext(index, -1);
4422 if (mUids[index] == INVALID_UID) {
4423 break;
4424 }
4425 fout.println(getString(mUids[index], mProcStateSeqs[index]));
4426 } while (index != mHistoryNext);
4427 }
4428
4429 public static String getString(int uid, long procStateSeq) {
Sudheer Shankadb9aaf032017-06-19 19:05:31 -07004430 return "UID=" + uid + " Seq=" + procStateSeq;
Sudheer Shankae7361852017-03-07 11:51:46 -08004431 }
4432
4433 private int increaseNext(int next, int increment) {
4434 next += increment;
4435 if (next >= mMaxCapacity) {
4436 next = 0;
4437 } else if (next < 0) {
4438 next = mMaxCapacity - 1;
4439 }
4440 return next;
4441 }
4442 }
Chris Wren193ae6b2017-03-31 15:17:11 -04004443
4444 private class NotificationId {
4445 private final String mTag;
4446 private final int mId;
4447
4448 NotificationId(NetworkPolicy policy, int type) {
4449 mTag = buildNotificationTag(policy, type);
4450 mId = type;
4451 }
4452
4453 @Override
4454 public boolean equals(Object o) {
4455 if (this == o) return true;
4456 if (!(o instanceof NotificationId)) return false;
4457 NotificationId that = (NotificationId) o;
4458 return Objects.equals(mTag, that.mTag);
4459 }
4460
4461 @Override
4462 public int hashCode() {
4463 return Objects.hash(mTag);
4464 }
4465
4466 /**
4467 * Build unique tag that identifies an active {@link NetworkPolicy}
4468 * notification of a specific type, like {@link #TYPE_LIMIT}.
4469 */
4470 private String buildNotificationTag(NetworkPolicy policy, int type) {
4471 return TAG + ":" + policy.template.hashCode() + ":" + type;
4472 }
4473
4474 public String getTag() {
4475 return mTag;
4476 }
4477
4478 public int getId() {
4479 return mId;
4480 }
4481 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004482}