blob: 32513dbc32a435f6b24618f9e75221e57375aece [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 Sharkey497e4432011-06-14 17:27:29 -070022import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070023import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070024import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070025import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070026import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070027import static android.content.Intent.ACTION_USER_ADDED;
28import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070029import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090030import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080031import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
32import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060034import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070035import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070036import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070037import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070038import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070039import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080040import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070041import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
42import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070043import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070044import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060045import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
46import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
Felipe Leme46b451f2016-08-19 08:46:17 -070047import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070048import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070049import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070050import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070051import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070052import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070053import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070054import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070055import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080056import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
57import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060058import static android.net.NetworkPolicyManager.resolveNetworkId;
Felipe Lemeb146f762016-08-19 09:52:16 -070059import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070060import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070061import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
62import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070063import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
64import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070065import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080066import static android.net.TrafficStats.MB_IN_BYTES;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070067import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070068import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060069import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070070import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080071
Jeff Sharkey854b2b12012-04-13 16:03:40 -070072import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070073import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070074import static com.android.internal.util.XmlUtils.readBooleanAttribute;
75import static com.android.internal.util.XmlUtils.readIntAttribute;
76import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060077import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070078import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
79import static com.android.internal.util.XmlUtils.writeIntAttribute;
80import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060081import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070082import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070083import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060084
Jeff Sharkey21c9c452011-06-07 12:26:43 -070085import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080086import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070087import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070088
Dianne Hackborn88e98df2015-03-23 13:29:14 -070089import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070090import android.annotation.IntDef;
Felipe Lemebc853dd2016-09-08 13:26:55 -070091import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -070092import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -080093import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070094import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070095import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070096import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070097import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070098import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070099import android.app.Notification;
100import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700101import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700102import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700103import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700104import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700105import android.content.Intent;
106import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700107import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700108import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700109import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700110import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700111import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700112import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700113import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700114import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700115import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700116import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700117import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700118import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700119import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700120import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700121import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600122import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700123import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700124import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700125import android.net.NetworkTemplate;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600126import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700127import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700128import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700129import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700130import android.os.Environment;
131import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700132import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700133import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700134import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700135import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700136import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700137import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700138import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700139import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600140import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800141import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700142import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700143import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600144import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700145import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700146import android.os.ShellCallback;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600147import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700148import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700149import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700150import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700151import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100152import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700153import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600154import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800155import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600156import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700157import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400158import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700159import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700160import android.util.ArrayMap;
161import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700162import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700163import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700164import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700165import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600166import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700167import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600168import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700169import android.util.SparseBooleanArray;
170import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700171import android.util.TrustedTime;
172import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700173
Jeff Sharkey497e4432011-06-14 17:27:29 -0700174import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700175import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800176import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400177import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500178import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700179import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800180import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600181import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700182import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700183import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600184import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700185import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700186import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700187import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800188import com.android.server.SystemConfig;
jackqdyulei455e90a2017-02-09 15:29:16 -0800189import com.android.server.power.BatterySaverPolicy.ServiceType;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600190
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600191import libcore.io.IoUtils;
192
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700193import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700194
195import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700196import org.xmlpull.v1.XmlSerializer;
197
198import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700199import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700200import java.io.FileInputStream;
201import java.io.FileNotFoundException;
202import java.io.FileOutputStream;
203import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700204import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700205import java.lang.annotation.Retention;
206import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100207import java.nio.charset.StandardCharsets;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600208import java.time.ZoneId;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600209import java.time.ZonedDateTime;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700210import java.util.ArrayList;
211import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700212import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600213import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400214import java.util.Objects;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800215import java.util.concurrent.CountDownLatch;
216import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700217
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700218/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700219 * Service that maintains low-level network policy rules, using
220 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700221 * <p>
222 * Derives active rules by combining a given policy with other system status,
223 * and delivers to listeners, such as {@link ConnectivityManager}, for
224 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700225 *
226 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000227 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700228 * <ul>
229 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
230 * rules).
231 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
232 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000233 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
234 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700235 * </ul>
236 *
237 * <p>
238 * As such, methods that require synchronization have the following prefixes:
239 * <ul>
240 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
241 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000242 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
243 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700244 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700245 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700246public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800247 static final String TAG = "NetworkPolicy";
Hugo Benichi5d2f2b52017-04-07 08:53:25 +0900248 private static final boolean LOGD = false;
249 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700250
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700251 private static final int VERSION_INIT = 1;
252 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700253 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800254 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800255 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800256 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700257 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700258 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700259 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700260 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600261 private static final int VERSION_ADDED_CYCLE = 11;
262 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700263
Sudheer Shankae7361852017-03-07 11:51:46 -0800264 /**
265 * Max items written to {@link #ProcStateSeqHistory}.
266 */
267 @VisibleForTesting
268 public static final int MAX_PROC_STATE_SEQ_HISTORY =
269 ActivityManager.isLowRamDeviceStatic() ? 50 : 200;
270
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800271 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400272 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800273 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400274 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800275 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400276 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700277
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700278 private static final String TAG_POLICY_LIST = "policy-list";
279 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600280 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700281 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700282 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800283 private static final String TAG_WHITELIST = "whitelist";
284 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800285 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700286
287 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700288 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700289 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
290 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700291 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600292 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
293 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
294 private static final String ATTR_CYCLE_START = "cycleStart";
295 private static final String ATTR_CYCLE_END = "cycleEnd";
296 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700297 private static final String ATTR_WARNING_BYTES = "warningBytes";
298 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700299 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800300 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
301 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800302 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700303 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700304 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700305 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700306 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600307 private static final String ATTR_SUB_ID = "subId";
308 private static final String ATTR_TITLE = "title";
309 private static final String ATTR_SUMMARY = "summary";
310 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
311 private static final String ATTR_USAGE_BYTES = "usageBytes";
312 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700313
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800314 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800315 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800316 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800317 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700318
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700319 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
320
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700321 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700322 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800323 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800324 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700325 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700326 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
327 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700328 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700329 private static final int MSG_SET_FIREWALL_RULES = 14;
Felipe Leme03e95e22016-09-09 09:25:31 -0700330 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700331
Makoto Onuki8e777332017-03-28 11:25:47 -0700332 private static final int UID_MSG_STATE_CHANGED = 100;
333 private static final int UID_MSG_GONE = 101;
334
Jeff Sharkey75279902011-05-24 18:39:45 -0700335 private final Context mContext;
336 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700337 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700338 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700339 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700340 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700341 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700342 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700343
344 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700345 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700346 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700347 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800348 @GuardedBy("mUidRulesFirstLock")
349 private PowerSaveState mRestrictBackgroundPowerState;
350
351 // Store the status of restrict background before turning on battery saver.
352 // Used to restore mRestrictBackground when battery saver is turned off.
353 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700354
Felipe Lemef0823852016-06-08 13:43:08 -0700355 // See main javadoc for instructions on how to use these locks.
356 final Object mUidRulesFirstLock = new Object();
357 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700358
Felipe Lemef0823852016-06-08 13:43:08 -0700359 @GuardedBy("allLocks") volatile boolean mSystemReady;
360
Felipe Lemef0823852016-06-08 13:43:08 -0700361 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
362 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
363 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800364 // Store whether user flipped restrict background in battery saver mode
365 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700366
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700367 private final boolean mSuppressDefaultPolicy;
368
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700369 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800370 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700371 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800372 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700373
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600374 /** Defined subscription plans. */
375 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
376
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700377 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700378 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700379 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700380 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700381
Felipe Lemef0823852016-06-08 13:43:08 -0700382 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700383 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700384 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700385 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700386 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800387 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700388
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700389 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700390 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700391 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
392
Jeff Sharkey32566012014-12-02 18:30:14 -0800393 /**
394 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700395 * in power save mode, except device idle (doze) still applies.
396 * TODO: An int array might be sufficient
397 */
Felipe Lemef0823852016-06-08 13:43:08 -0700398 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700399 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
400
401 /**
402 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800403 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700404 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800405 */
Felipe Lemef0823852016-06-08 13:43:08 -0700406 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700407 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700408
Felipe Lemef0823852016-06-08 13:43:08 -0700409 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700410 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
411
Felipe Lemeb85a6372016-01-14 16:16:16 -0800412 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800413 * UIDs that have been initially white-listed by system to avoid restricted background.
414 */
Felipe Lemef0823852016-06-08 13:43:08 -0700415 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800416 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
417 new SparseBooleanArray();
418
419 /**
420 * UIDs that have been initially white-listed by system to avoid restricted background,
421 * but later revoked by user.
422 */
Felipe Lemef0823852016-06-08 13:43:08 -0700423 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800424 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
425 new SparseBooleanArray();
426
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700427 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700428 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800429 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700430 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700431 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800432 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700433
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700434 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700435 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400436 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700437
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700438 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700439 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800440 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700441
Jeff Sharkey32566012014-12-02 18:30:14 -0800442 private final RemoteCallbackList<INetworkPolicyListener>
443 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700444
Dianne Hackborn497175b2014-07-01 12:56:08 -0700445 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700446 @VisibleForTesting
447 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700448
449 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700450
Felipe Lemef0823852016-06-08 13:43:08 -0700451 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700452 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700453
Svet Ganov16a16892015-04-16 10:32:04 -0700454 private final AppOpsManager mAppOps;
455
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800456 private final IPackageManager mIPm;
457
Sudheer Shankae7361852017-03-07 11:51:46 -0800458 private ActivityManagerInternal mActivityManagerInternal;
459
460 /**
461 * This is used for debugging purposes. Whenever the IUidObserver.onUidStateChanged is called,
462 * the uid and procStateSeq will be written to this and will be printed as part of dump.
463 */
464 @VisibleForTesting
465 public ProcStateSeqHistory mObservedHistory
466 = new ProcStateSeqHistory(MAX_PROC_STATE_SEQ_HISTORY);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800467
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700468 // TODO: keep whitelist of system-critical services that should never have
469 // rules enforced, such as system, phone, and radio UIDs.
470
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700471 // TODO: migrate notifications to SystemUI
472
Jeff Sharkey75279902011-05-24 18:39:45 -0700473 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700474 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
475 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700476 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
477 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700478 }
479
480 private static File getSystemDir() {
481 return new File(Environment.getDataDirectory(), "system");
482 }
483
484 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700485 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700486 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700487 mContext = checkNotNull(context, "missing context");
488 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700489 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700490 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700491 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700492 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700493 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700494 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700495 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700496 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700497
Amith Yamasani450a16b2013-09-18 16:28:50 -0700498 HandlerThread thread = new HandlerThread(TAG);
499 thread.start();
500 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700501
Makoto Onuki8e777332017-03-28 11:25:47 -0700502 // We create another thread for the UID events, which are more time-critical.
503 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
504 /*allowIo=*/ false);
505 mUidEventThread.start();
506 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
507
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700508 mSuppressDefaultPolicy = suppressDefaultPolicy;
509
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700510 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700511
512 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800513
Felipe Lemed17fda42016-04-29 11:12:45 -0700514 // Expose private service for system components to use.
515 LocalServices.addService(NetworkPolicyManagerInternal.class,
516 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700517 }
518
519 public void bindConnectivityManager(IConnectivityManager connManager) {
520 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700521 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700522
Jeff Sharkey497e4432011-06-14 17:27:29 -0700523 public void bindNotificationManager(INotificationManager notifManager) {
524 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
525 }
526
Felipe Lemef0823852016-06-08 13:43:08 -0700527 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700528 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700529 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
530 mPowerSaveWhitelistExceptIdleAppIds.clear();
531 if (whitelist != null) {
532 for (int uid : whitelist) {
533 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
534 }
535 }
536 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700537 mPowerSaveWhitelistAppIds.clear();
538 if (whitelist != null) {
539 for (int uid : whitelist) {
540 mPowerSaveWhitelistAppIds.put(uid, true);
541 }
542 }
543 } catch (RemoteException e) {
544 }
545 }
546
Felipe Lemea9505cc2016-02-26 10:28:41 -0800547 /**
548 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
549 * revoke the whitelist.
550 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700551 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800552 */
Felipe Lemef0823852016-06-08 13:43:08 -0700553 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800554 final List<UserInfo> users = mUserManager.getUsers();
555 final int numberUsers = users.size();
556
Felipe Lemea110eec2016-04-29 09:58:06 -0700557 boolean changed = false;
558 for (int i = 0; i < numberUsers; i++) {
559 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700560 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700561 }
562 return changed;
563 }
564
Felipe Lemef0823852016-06-08 13:43:08 -0700565 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700566 final SystemConfig sysConfig = SystemConfig.getInstance();
567 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800568 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
569 boolean changed = false;
570 for (int i = 0; i < allowDataUsage.size(); i++) {
571 final String pkg = allowDataUsage.valueAt(i);
572 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700573 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
574 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800575 final ApplicationInfo app;
576 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700577 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800578 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700579 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
580 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800581 continue;
582 }
583 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700584 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
585 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800586 continue;
587 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700588 final int uid = UserHandle.getUid(userId, app.uid);
589 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
590 if (LOGD)
591 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
592 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800593 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700594 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700595 if (LOGD)
596 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
597 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700598 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700599 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800600 }
601 }
602 return changed;
603 }
604
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800605 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700606 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800607 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700608 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800609 // Boost thread's priority during system server init
610 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700611 if (!isBandwidthControlEnabled()) {
612 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
613 return;
614 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700615
Felipe Leme873a83a2016-09-07 11:34:10 -0700616 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700617
Felipe Leme873a83a2016-09-07 11:34:10 -0700618 synchronized (mUidRulesFirstLock) {
619 synchronized (mNetworkPoliciesSecondLock) {
620 updatePowerSaveWhitelistUL();
621 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
622 mPowerManagerInternal.registerLowPowerModeObserver(
623 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800624 @Override
625 public int getServiceType() {
626 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700627 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800628
629 @Override
630 public void onLowPowerModeChanged(PowerSaveState result) {
631 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800632 if (LOGD) {
633 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
634 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800635 synchronized (mUidRulesFirstLock) {
636 if (mRestrictPower != enabled) {
637 mRestrictPower = enabled;
638 updateRulesForRestrictPowerUL();
639 }
640 }
641 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800642 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800643 mRestrictPower = mPowerManagerInternal.getLowPowerState(
644 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700645
646 mSystemReady = true;
647
648 // read policy from disk
649 readPolicyAL();
650
jackqdyulei29c82ab2017-03-10 14:09:16 -0800651 // Update the restrictBackground if battery saver is turned on
652 mRestrictBackgroundBeforeBsm = mRestrictBackground;
653 mRestrictBackgroundPowerState = mPowerManagerInternal
654 .getLowPowerState(ServiceType.DATA_SAVER);
655 final boolean localRestrictBackground =
656 mRestrictBackgroundPowerState.batterySaverEnabled;
657 if (localRestrictBackground && localRestrictBackground != mRestrictBackground) {
658 mRestrictBackground = localRestrictBackground;
659 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
660 mRestrictBackground ? 1 : 0, 0).sendToTarget();
661 }
662 mPowerManagerInternal.registerLowPowerModeObserver(
663 new PowerManagerInternal.LowPowerModeListener() {
664 @Override
665 public int getServiceType() {
666 return ServiceType.DATA_SAVER;
667 }
668
669 @Override
670 public void onLowPowerModeChanged(PowerSaveState result) {
671 synchronized (mUidRulesFirstLock) {
672 updateRestrictBackgroundByLowPowerModeUL(result);
673 }
674 }
675 });
676
Felipe Leme873a83a2016-09-07 11:34:10 -0700677 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
678 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700679 }
Felipe Lemef0823852016-06-08 13:43:08 -0700680
Felipe Leme873a83a2016-09-07 11:34:10 -0700681 setRestrictBackgroundUL(mRestrictBackground);
682 updateRulesForGlobalChangeAL(false);
683 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700684 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800685 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700686
Sudheer Shankae7361852017-03-07 11:51:46 -0800687 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700688 try {
689 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000690 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800691 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700692 mNetworkManager.registerObserver(mAlertObserver);
693 } catch (RemoteException e) {
694 // ignored; both services live in system_server
695 }
696
697 // listen for changes to power save whitelist
698 final IntentFilter whitelistFilter = new IntentFilter(
699 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
700 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
701
Felipe Leme873a83a2016-09-07 11:34:10 -0700702 // watch for network interfaces to be claimed
703 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
704 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
705
706 // listen for package changes to update policy
707 final IntentFilter packageFilter = new IntentFilter();
708 packageFilter.addAction(ACTION_PACKAGE_ADDED);
709 packageFilter.addDataScheme("package");
710 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
711
712 // listen for UID changes to update policy
713 mContext.registerReceiver(
714 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
715
716 // listen for user changes to update policy
717 final IntentFilter userFilter = new IntentFilter();
718 userFilter.addAction(ACTION_USER_ADDED);
719 userFilter.addAction(ACTION_USER_REMOVED);
720 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
721
722 // listen for stats update events
723 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
724 mContext.registerReceiver(
725 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
726
727 // listen for restrict background changes from notifications
728 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
729 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
730
731 // listen for snooze warning from notifications
732 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
733 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
734 MANAGE_NETWORK_POLICY, mHandler);
735
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600736 // listen for configured wifi networks to be loaded
737 final IntentFilter wifiFilter =
738 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
739 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700740
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700741 // listen for carrier config changes to update data cycle information
742 final IntentFilter carrierConfigFilter = new IntentFilter(
743 ACTION_CARRIER_CONFIG_CHANGED);
744 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
745
Felipe Leme873a83a2016-09-07 11:34:10 -0700746 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800747 // tell systemReady() that the service has been initialized
748 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700749 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800750 // Restore the default priority after init is done
751 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700752 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700753 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700754 }
755
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800756 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
757 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
758 mHandler.post(() -> initService(initCompleteSignal));
759 return initCompleteSignal;
760 }
761
762 public void systemReady(CountDownLatch initCompleteSignal) {
763 // wait for initService to complete
764 try {
765 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
766 throw new IllegalStateException("Service " + TAG +" init timeout");
767 }
768 } catch (InterruptedException e) {
769 Thread.currentThread().interrupt();
770 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
771 }
772 }
773
Sudheer Shankac9d94072017-02-22 22:13:55 +0000774 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700775 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700776 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
777 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700778 }
779
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700780 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700781 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700782 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700783
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700784 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700785 }
786
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700787 @Override public void onUidIdle(int uid, boolean disabled) {
788 }
789
790 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700791 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700792 };
793
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700794 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700795 @Override
796 public void onReceive(Context context, Intent intent) {
797 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700798 synchronized (mUidRulesFirstLock) {
799 updatePowerSaveWhitelistUL();
800 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700801 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700802 }
803 }
804 };
805
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700806 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700807 @Override
808 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700809 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700810
811 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700812 final int uid = intent.getIntExtra(EXTRA_UID, -1);
813 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700814
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700815 if (ACTION_PACKAGE_ADDED.equals(action)) {
816 // update rules for UID, since it might be subject to
817 // global background data policy
818 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700819 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700820 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700821 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700822 }
823 }
824 };
825
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700826 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700827 @Override
828 public void onReceive(Context context, Intent intent) {
829 // on background handler thread, and UID_REMOVED is protected
830
831 final int uid = intent.getIntExtra(EXTRA_UID, -1);
832 if (uid == -1) return;
833
834 // remove any policy and update rules to clean up
835 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700836 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700837 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700838 synchronized (mNetworkPoliciesSecondLock) {
839 writePolicyAL();
840 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700841 }
842 }
843 };
844
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700845 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700846 @Override
847 public void onReceive(Context context, Intent intent) {
848 // on background handler thread, and USER_ADDED and USER_REMOVED
849 // broadcasts are protected
850
851 final String action = intent.getAction();
852 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
853 if (userId == -1) return;
854
Amith Yamasani15e472352015-04-24 19:06:07 -0700855 switch (action) {
856 case ACTION_USER_REMOVED:
857 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700858 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800859 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700860 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700861 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700862 if (action == ACTION_USER_ADDED) {
863 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700864 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700865 }
866 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700867 synchronized (mNetworkPoliciesSecondLock) {
868 updateRulesForGlobalChangeAL(true);
869 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700870 }
871 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700872 }
873 }
874 };
875
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700876 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700877 * Receiver that watches for {@link INetworkStatsService} updates, which we
878 * use to check against {@link NetworkPolicy#warningBytes}.
879 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700880 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700881 @Override
882 public void onReceive(Context context, Intent intent) {
883 // on background handler thread, and verified
884 // READ_NETWORK_USAGE_HISTORY permission above.
885
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800886 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700887 synchronized (mNetworkPoliciesSecondLock) {
888 updateNetworkEnabledNL();
889 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700890 }
891 }
892 };
893
894 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700895 * Receiver that watches for {@link Notification} control of
896 * {@link #mRestrictBackground}.
897 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700898 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700899 @Override
900 public void onReceive(Context context, Intent intent) {
901 // on background handler thread, and verified MANAGE_NETWORK_POLICY
902 // permission above.
903
904 setRestrictBackground(false);
905 }
906 };
907
908 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800909 * Receiver that watches for {@link Notification} control of
910 * {@link NetworkPolicy#lastWarningSnooze}.
911 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700912 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800913 @Override
914 public void onReceive(Context context, Intent intent) {
915 // on background handler thread, and verified MANAGE_NETWORK_POLICY
916 // permission above.
917
918 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
919 performSnooze(template, TYPE_WARNING);
920 }
921 };
922
923 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600924 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
925 * we can perform upgrade logic.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700926 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600927 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700928 @Override
929 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900930 synchronized (mUidRulesFirstLock) {
931 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600932 upgradeWifiMeteredOverrideAL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700933 }
934 }
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600935 // Only need to perform upgrade logic once
936 mContext.unregisterReceiver(this);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700937 }
938 };
939
940 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700941 * Observer that watches for {@link INetworkManagementService} alerts.
942 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700943 final private INetworkManagementEventObserver mAlertObserver
944 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700945 @Override
946 public void limitReached(String limitName, String iface) {
947 // only someone like NMS should be calling us
948 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
949
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800950 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
951 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700952 }
953 }
954 };
955
956 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700957 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
958 * to show visible notifications as needed.
959 */
Felipe Lemef0823852016-06-08 13:43:08 -0700960 void updateNotificationsNL() {
961 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700962
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700963 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -0400964 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700965 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700966
967 // TODO: when switching to kernel notifications, compute next future
968 // cycle boundary to recompute notifications.
969
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700970 // examine stats for each active policy
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700971 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
972 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700973 // ignore policies that aren't relevant to user
974 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700975 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700976
Jeff Sharkey53313d72017-07-13 16:47:32 -0600977 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
978 .cycleIterator(policy).next();
979 final long start = cycle.first.toInstant().toEpochMilli();
980 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700981 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700982
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700983 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800984 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700985 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
986 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700987 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -0700988 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700989 }
990
Jeff Sharkey497e4432011-06-14 17:27:29 -0700991 } else {
Felipe Lemef0823852016-06-08 13:43:08 -0700992 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700993
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800994 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700995 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700996 }
997 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700998 }
999
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001000 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001001 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001002 final NotificationId notificationId = beforeNotifs.valueAt(i);
1003 if (!mActiveNotifs.contains(notificationId)) {
1004 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001005 }
1006 }
1007 }
1008
1009 /**
1010 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001011 * current device state, such as when
1012 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1013 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001014 */
1015 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001016 if (template.isMatchRuleMobile()) {
1017 final TelephonyManager tele = TelephonyManager.from(mContext);
1018 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001019
Jeff Sharkey32566012014-12-02 18:30:14 -08001020 // Mobile template is relevant when any active subscriber matches
1021 final int[] subIds = sub.getActiveSubscriptionIdList();
1022 for (int subId : subIds) {
1023 final String subscriberId = tele.getSubscriberId(subId);
1024 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001025 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001026 if (template.matches(probeIdent)) {
1027 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001028 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001029 }
1030 return false;
1031 } else {
1032 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001033 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001034 }
1035
1036 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001037 * Notify that given {@link NetworkTemplate} is over
1038 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1039 */
Felipe Lemef0823852016-06-08 13:43:08 -07001040 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001041 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001042 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001043 mOverLimitNotified.add(template);
1044 }
1045 }
1046
Felipe Lemef0823852016-06-08 13:43:08 -07001047 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001048 mOverLimitNotified.remove(template);
1049 }
1050
1051 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001052 * Show notification for combined {@link NetworkPolicy} and specific type,
1053 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1054 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001055 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001056 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001057 final Notification.Builder builder =
1058 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001059 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001060 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001061 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001062 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001063
1064 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001065 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001066 switch (type) {
1067 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001068 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001069 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001070
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001071 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001072 builder.setTicker(title);
1073 builder.setContentTitle(title);
1074 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001075 builder.setDefaults(Notification.DEFAULT_ALL);
Julia Reynoldsbad42972017-04-25 13:52:49 -04001076 builder.setChannelId(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001077
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001078 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1079 builder.setDeleteIntent(PendingIntent.getBroadcast(
1080 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1081
Wei Liu546cb772016-07-21 16:19:01 -07001082 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001083 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001084 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1085
Jeff Sharkey497e4432011-06-14 17:27:29 -07001086 break;
1087 }
1088 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001089 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001090
1091 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001092 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001093 switch (policy.template.getMatchRule()) {
1094 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001095 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001096 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001097 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001098 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001099 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001100 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001101 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001102 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001103 case MATCH_WIFI:
1104 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001105 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001106 break;
1107 default:
1108 title = null;
1109 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001110 }
1111
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001112 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001113 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001114 builder.setTicker(title);
1115 builder.setContentTitle(title);
1116 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001117
Wei Liu546cb772016-07-21 16:19:01 -07001118 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001119 builder.setContentIntent(PendingIntent.getActivity(
1120 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1121 break;
1122 }
1123 case TYPE_LIMIT_SNOOZED: {
1124 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001125 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001126 Formatter.formatFileSize(mContext, overBytes));
1127
1128 final CharSequence title;
1129 switch (policy.template.getMatchRule()) {
1130 case MATCH_MOBILE_3G_LOWER:
1131 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1132 break;
1133 case MATCH_MOBILE_4G:
1134 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1135 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001136 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001137 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1138 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001139 case MATCH_WIFI:
1140 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1141 break;
1142 default:
1143 title = null;
1144 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001145 }
1146
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001147 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001148 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001149 builder.setTicker(title);
1150 builder.setContentTitle(title);
1151 builder.setContentText(body);
1152
Wei Liu546cb772016-07-21 16:19:01 -07001153 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001154 builder.setContentIntent(PendingIntent.getActivity(
1155 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001156 break;
1157 }
1158 }
1159
1160 // TODO: move to NotificationManager once we can mock it
1161 try {
1162 final String packageName = mContext.getPackageName();
Chris Wren193ae6b2017-03-31 15:17:11 -04001163 if (!TextUtils.isEmpty(body)) {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001164 builder.setStyle(new Notification.BigTextStyle()
1165 .bigText(body));
1166 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001167 mNotifManager.enqueueNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001168 packageName, packageName, notificationId.getTag(), notificationId.getId(),
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001169 builder.build(), UserHandle.USER_ALL);
Chris Wren193ae6b2017-03-31 15:17:11 -04001170 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001171 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001172 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001173 }
1174 }
1175
Chris Wren193ae6b2017-03-31 15:17:11 -04001176 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001177 // TODO: move to NotificationManager once we can mock it
1178 try {
1179 final String packageName = mContext.getPackageName();
1180 mNotifManager.cancelNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001181 packageName, notificationId.getTag(), notificationId.getId(),
1182 UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001183 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001184 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001185 }
1186 }
1187
1188 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001189 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001190 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001191 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001192 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001193 @Override
1194 public void onReceive(Context context, Intent intent) {
1195 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1196 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001197
1198 maybeRefreshTrustedTime();
Hugo Benichi446c9c92017-04-10 09:41:10 +09001199 synchronized (mUidRulesFirstLock) {
1200 synchronized (mNetworkPoliciesSecondLock) {
1201 ensureActiveMobilePolicyAL();
1202 normalizePoliciesNL();
1203 updateNetworkEnabledNL();
1204 updateNetworkRulesNL();
1205 updateNotificationsNL();
1206 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001207 }
1208 }
1209 };
1210
1211 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001212 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1213 * if necessary.
1214 *
1215 * @param subId that has its associated NetworkPolicy updated if necessary
1216 * @return if any policies were updated
1217 */
1218 private boolean maybeUpdateMobilePolicyCycleNL(int subId) {
1219 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleNL()");
1220 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1221
1222 if (config == null) {
1223 return false;
1224 }
1225
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)) {
1235 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1236
1237 // only update the policy if the user didn't change any of the defaults.
1238 if (!policy.inferred) {
1239 // TODO: inferred could be split, so that if a user changes their data limit or
1240 // warning, it doesn't prevent their cycle date from being updated.
1241 if (LOGD) Slog.v(TAG, "Didn't update NetworkPolicy because policy.inferred");
1242 continue;
1243 }
1244
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001245 final int currentCycleDay;
1246 if (policy.cycleRule.isMonthly()) {
1247 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1248 } else {
1249 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1250 }
1251
1252 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001253 final long warningBytes = getWarningBytesFromCarrierConfig(config,
1254 policy.warningBytes);
1255 final long limitBytes = getLimitBytesFromCarrierConfig(config,
1256 policy.limitBytes);
1257
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001258 if (currentCycleDay == cycleDay &&
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001259 policy.warningBytes == warningBytes &&
1260 policy.limitBytes == limitBytes) {
1261 continue;
1262 }
1263
1264 policyUpdated = true;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001265 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001266 policy.warningBytes = warningBytes;
1267 policy.limitBytes = limitBytes;
1268
1269 if (LOGD) {
1270 Slog.d(TAG, "Updated NetworkPolicy " + policy + " which matches subscriber "
1271 + NetworkIdentity.scrubSubscriberId(subscriberId)
1272 + " from CarrierConfigManager");
1273 }
1274 }
1275 }
1276
1277 return policyUpdated;
1278 }
1279
1280 /**
1281 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1282 *
1283 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1284 * to do so, it returns the fallback value.
1285 *
1286 * @param config The CarrierConfig to read the value from.
1287 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1288 * @return cycleDay to use in the mobile NetworkPolicy.
1289 */
1290 @VisibleForTesting
1291 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1292 int fallbackCycleDay) {
1293 if (config == null) {
1294 return fallbackCycleDay;
1295 }
1296 int cycleDay =
1297 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1298 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1299 return fallbackCycleDay;
1300 }
1301 // validate cycleDay value
1302 final Calendar cal = Calendar.getInstance();
1303 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1304 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1305 Slog.e(TAG, "Invalid date in "
1306 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1307 return fallbackCycleDay;
1308 }
1309 return cycleDay;
1310 }
1311
1312 /**
1313 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1314 *
1315 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1316 * to do so, it returns the fallback value.
1317 *
1318 * @param config The CarrierConfig to read the value from.
1319 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1320 * @return warningBytes to use in the mobile NetworkPolicy.
1321 */
1322 @VisibleForTesting
1323 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1324 long fallbackWarningBytes) {
1325 if (config == null) {
1326 return fallbackWarningBytes;
1327 }
1328 long warningBytes =
1329 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1330
1331 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1332 return WARNING_DISABLED;
1333 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1334 return getPlatformDefaultWarningBytes();
1335 } else if (warningBytes < 0) {
1336 Slog.e(TAG, "Invalid value in "
1337 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1338 + "non-negative value but got: " + warningBytes);
1339 return fallbackWarningBytes;
1340 }
1341
1342 return warningBytes;
1343 }
1344
1345 /**
1346 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1347 *
1348 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1349 * to do so, it returns the fallback value.
1350 *
1351 * @param config The CarrierConfig to read the value from.
1352 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1353 * @return limitBytes to use in the mobile NetworkPolicy.
1354 */
1355 @VisibleForTesting
1356 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1357 long fallbackLimitBytes) {
1358 if (config == null) {
1359 return fallbackLimitBytes;
1360 }
1361 long limitBytes =
1362 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1363
1364 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1365 return LIMIT_DISABLED;
1366 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1367 return getPlatformDefaultLimitBytes();
1368 } else if (limitBytes < 0) {
1369 Slog.e(TAG, "Invalid value in "
1370 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1371 + "non-negative value but got: " + limitBytes);
1372 return fallbackLimitBytes;
1373 }
1374 return limitBytes;
1375 }
1376
1377 /**
1378 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1379 */
1380 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1381 @Override
1382 public void onReceive(Context context, Intent intent) {
1383 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1384 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1385
1386 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1387 return;
1388 }
1389 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
1390 final TelephonyManager tele = TelephonyManager.from(mContext);
1391 final String subscriberId = tele.getSubscriberId(subId);
1392
1393 maybeRefreshTrustedTime();
1394 synchronized (mUidRulesFirstLock) {
1395 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001396 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001397 if (added) return;
1398 final boolean updated = maybeUpdateMobilePolicyCycleNL(subId);
1399 if (!updated) return;
1400 // update network and notification rules, as the data cycle changed and it's
1401 // possible that we should be triggering warnings/limits now
1402 handleNetworkPoliciesUpdateAL(true);
1403 }
1404 }
1405 }
1406 };
1407
1408 /**
1409 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1410 * one has been updated.
1411 *
1412 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1413 * update.
1414 */
1415 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1416 if (shouldNormalizePolicies) {
1417 normalizePoliciesNL();
1418 }
1419 updateNetworkEnabledNL();
1420 updateNetworkRulesNL();
1421 updateNotificationsNL();
1422 writePolicyAL();
1423 }
1424
1425 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001426 * Proactively control network data connections when they exceed
1427 * {@link NetworkPolicy#limitBytes}.
1428 */
Felipe Lemef0823852016-06-08 13:43:08 -07001429 void updateNetworkEnabledNL() {
1430 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001431
1432 // TODO: reset any policy-disabled networks when any policy is removed
1433 // completely, which is currently rare case.
1434
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001435 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1436 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001437 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001438 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001439 setNetworkTemplateEnabled(policy.template, true);
1440 continue;
1441 }
1442
Jeff Sharkey53313d72017-07-13 16:47:32 -06001443 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1444 .cycleIterator(policy).next();
1445 final long start = cycle.first.toInstant().toEpochMilli();
1446 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001447 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001448
1449 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001450 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1451 && policy.lastLimitSnooze < start;
1452 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001453
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001454 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001455 }
1456 }
1457
1458 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001459 * Proactively disable networks that match the given
1460 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001461 */
1462 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001463 // TODO: reach into ConnectivityManager to proactively disable bringing
1464 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001465
1466 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1467 // If mobile data usage hits the limit or if the user resumes the data, we need to
1468 // notify telephony.
1469 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1470 final TelephonyManager tm = TelephonyManager.from(mContext);
1471
1472 final int[] subIds = sm.getActiveSubscriptionIdList();
1473 for (int subId : subIds) {
1474 final String subscriberId = tm.getSubscriberId(subId);
1475 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1476 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1477 // Template is matched when subscriber id matches.
1478 if (template.matches(probeIdent)) {
1479 tm.setPolicyDataEnabled(enabled, subId);
1480 }
1481 }
1482 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001483 }
1484
1485 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001486 * Examine all connected {@link NetworkState}, looking for
1487 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1488 * remaining quota based on usage cycle and historical stats.
1489 */
Felipe Lemef0823852016-06-08 13:43:08 -07001490 void updateNetworkRulesNL() {
1491 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001492
1493 final NetworkState[] states;
1494 try {
1495 states = mConnManager.getAllNetworkState();
1496 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001497 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001498 return;
1499 }
1500
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001501 // First, generate identities of all connected networks so we can
1502 // quickly compare them against all defined policies below.
1503 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001504 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001505 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001506 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001507 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001508
1509 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001510 if (baseIface != null) {
1511 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001512 }
1513
1514 // Stacked interfaces are considered to have same identity as
1515 // their parent network.
1516 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1517 for (LinkProperties stackedLink : stackedLinks) {
1518 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001519 if (stackedIface != null) {
1520 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001521 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001522 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001523 }
1524 }
1525
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001526 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001527 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001528 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001529 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001530 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001531
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001532 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001533 for (int j = connIdents.size() - 1; j >= 0; j--) {
1534 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1535 if (policy.template.matches(ident.second)) {
1536 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001537 }
1538 }
1539
1540 if (ifaceList.size() > 0) {
1541 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001542 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001543 }
1544 }
1545
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001546 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001547 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001548
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001549 // apply each policy that we found ifaces for; compute remaining data
1550 // based on current cycle and historical stats, and push to kernel.
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001551 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1552 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1553 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001554
Jeff Sharkey53313d72017-07-13 16:47:32 -06001555 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1556 .cycleIterator(policy).next();
1557 final long start = cycle.first.toInstant().toEpochMilli();
1558 final long end = cycle.second.toInstant().toEpochMilli();
1559 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001560
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001561 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001562 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001563 }
1564
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001565 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001566 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001567 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001568 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001569 if (!hasLimit) {
1570 // metered network, but no policy limit; we still need to
1571 // restrict apps, so push really high quota.
1572 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001573 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001574 // snoozing past quota, but we still need to restrict apps,
1575 // so push really high quota.
1576 quotaBytes = Long.MAX_VALUE;
1577 } else {
1578 // remaining "quota" bytes are based on total usage in
1579 // current cycle. kernel doesn't like 0-byte rules, so we
1580 // set 1-byte quota and disable the radio later.
1581 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1582 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001583
1584 if (ifaces.length > 1) {
1585 // TODO: switch to shared quota once NMS supports
1586 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001587 }
1588
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001589 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001590 // long quotaBytes split up into two ints to fit in message
1591 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1592 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1593 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001594 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001595 }
1596 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001597
1598 // keep track of lowest warning or limit of active policies
1599 if (hasWarning && policy.warningBytes < lowestRule) {
1600 lowestRule = policy.warningBytes;
1601 }
1602 if (hasLimit && policy.limitBytes < lowestRule) {
1603 lowestRule = policy.limitBytes;
1604 }
1605 }
1606
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001607 for (int i = connIfaces.size()-1; i >= 0; i--) {
1608 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001609 // long quotaBytes split up into two ints to fit in message
1610 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1611 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1612 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001613 newMeteredIfaces.add(iface);
1614 }
1615
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001616 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001617
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001618 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001619 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1620 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001621 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001622 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1623 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001624 }
1625 }
1626 mMeteredIfaces = newMeteredIfaces;
1627
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001628 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001629 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001630 }
1631
1632 /**
1633 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1634 * have at least a default mobile policy defined.
1635 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001636 private void ensureActiveMobilePolicyAL() {
1637 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001638 if (mSuppressDefaultPolicy) return;
1639
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001640 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001641 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001642
Jeff Sharkey32566012014-12-02 18:30:14 -08001643 final int[] subIds = sub.getActiveSubscriptionIdList();
1644 for (int subId : subIds) {
1645 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001646 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001647 }
1648 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001649
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001650 /**
1651 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1652 * have at least a default mobile policy defined.
1653 *
1654 * @param subId to build a default policy for
1655 * @param subscriberId that we check for an existing policy
1656 * @return true if a mobile network policy was added, or false one already existed.
1657 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001658 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001659 // Poke around to see if we already have a policy
1660 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001661 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001662 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1663 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1664 if (template.matches(probeIdent)) {
1665 if (LOGD) {
1666 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1667 + NetworkIdentity.scrubSubscriberId(subscriberId));
1668 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001669 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001670 }
1671 }
1672
Jeff Sharkey32566012014-12-02 18:30:14 -08001673 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1674 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001675 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001676 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001677 return true;
1678 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001679
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001680 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001681 final int dataWarningConfig = mContext.getResources().getInteger(
1682 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001683 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001684 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001685 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001686 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001687 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001688 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001689
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001690 private long getPlatformDefaultLimitBytes() {
1691 return LIMIT_DISABLED;
1692 }
1693
1694 @VisibleForTesting
1695 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
1696 PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1697
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001698 final int cycleDay = getCycleDayFromCarrierConfig(config,
1699 ZonedDateTime.now().getDayOfMonth());
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001700 final long warningBytes = getWarningBytesFromCarrierConfig(config,
1701 getPlatformDefaultWarningBytes());
1702 final long limitBytes = getLimitBytesFromCarrierConfig(config,
1703 getPlatformDefaultLimitBytes());
1704
Jeff Sharkey32566012014-12-02 18:30:14 -08001705 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001706 final RecurrenceRule cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1707 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001708 warningBytes, limitBytes, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1709 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001710 }
1711
Felipe Lemef0823852016-06-08 13:43:08 -07001712 private void readPolicyAL() {
1713 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001714
1715 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001716 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001717 mSubscriptionPlans.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001718 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001719
1720 FileInputStream fis = null;
1721 try {
1722 fis = mPolicyFile.openRead();
1723 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001724 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001725
Felipe Leme46b451f2016-08-19 08:46:17 -07001726 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1727 // to skip UIDs that were explicitly blacklisted.
1728 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1729
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001730 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001731 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001732 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001733 while ((type = in.next()) != END_DOCUMENT) {
1734 final String tag = in.getName();
1735 if (type == START_TAG) {
1736 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001737 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001738 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001739 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1740 mRestrictBackground = readBooleanAttribute(
1741 in, ATTR_RESTRICT_BACKGROUND);
1742 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001743 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001744 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001745 if (mRestrictBackground != oldValue) {
1746 // Some early services may have read the default value,
1747 // so notify them that it's changed
1748 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1749 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1750 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001751
1752 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1753 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1754 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001755 final String networkId;
1756 if (version >= VERSION_ADDED_NETWORK_ID) {
1757 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1758 } else {
1759 networkId = null;
1760 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001761 final RecurrenceRule cycleRule;
1762 if (version >= VERSION_ADDED_CYCLE) {
1763 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1764 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1765 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1766 cycleRule = new RecurrenceRule(
1767 RecurrenceRule.convertZonedDateTime(start),
1768 RecurrenceRule.convertZonedDateTime(end),
1769 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001770 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001771 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1772 final String cycleTimezone;
1773 if (version >= VERSION_ADDED_TIMEZONE) {
1774 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1775 } else {
1776 cycleTimezone = "UTC";
1777 }
1778 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001779 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001780 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1781 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001782 final long lastLimitSnooze;
1783 if (version >= VERSION_SPLIT_SNOOZE) {
1784 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1785 } else if (version >= VERSION_ADDED_SNOOZE) {
1786 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001787 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001788 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001789 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001790 final boolean metered;
1791 if (version >= VERSION_ADDED_METERED) {
1792 metered = readBooleanAttribute(in, ATTR_METERED);
1793 } else {
1794 switch (networkTemplate) {
1795 case MATCH_MOBILE_3G_LOWER:
1796 case MATCH_MOBILE_4G:
1797 case MATCH_MOBILE_ALL:
1798 metered = true;
1799 break;
1800 default:
1801 metered = false;
1802 }
1803 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001804 final long lastWarningSnooze;
1805 if (version >= VERSION_SPLIT_SNOOZE) {
1806 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1807 } else {
1808 lastWarningSnooze = SNOOZE_NEVER;
1809 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001810 final boolean inferred;
1811 if (version >= VERSION_ADDED_INFERRED) {
1812 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1813 } else {
1814 inferred = false;
1815 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001816
Jeff Sharkey32566012014-12-02 18:30:14 -08001817 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1818 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001819 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001820 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
1821 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001822 lastLimitSnooze, metered, inferred));
1823 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001824
1825 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
1826 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1827 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1828 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1829 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
1830 RecurrenceRule.convertZonedDateTime(start),
1831 RecurrenceRule.convertZonedDateTime(end),
1832 RecurrenceRule.convertPeriod(period));
1833 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
1834 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
1835
1836 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
1837 SubscriptionPlan.BYTES_UNKNOWN);
1838 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
1839 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
1840 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
1841 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
1842 builder.setDataLimit(limitBytes, limitBehavior);
1843 }
1844
1845 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
1846 SubscriptionPlan.BYTES_UNKNOWN);
1847 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
1848 SubscriptionPlan.TIME_UNKNOWN);
1849 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
1850 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
1851 builder.setDataUsage(usageBytes, usageTime);
1852 }
1853
1854 final int subId = readIntAttribute(in, ATTR_SUB_ID);
1855 final SubscriptionPlan plan = builder.build();
1856 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
1857 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
1858
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001859 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001860 final int uid = readIntAttribute(in, ATTR_UID);
1861 final int policy = readIntAttribute(in, ATTR_POLICY);
1862
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001863 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001864 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001865 } else {
1866 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1867 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001868 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001869 final int appId = readIntAttribute(in, ATTR_APP_ID);
1870 final int policy = readIntAttribute(in, ATTR_POLICY);
1871
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001872 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001873 // app policy is deprecated so this is only used in pre system user split.
1874 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001875 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001876 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001877 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001878 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001879 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001880 } else if (TAG_WHITELIST.equals(tag)) {
1881 insideWhitelist = true;
1882 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1883 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001884 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001885 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1886 final int uid = readIntAttribute(in, ATTR_UID);
1887 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001888 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001889 } else if (type == END_TAG) {
1890 if (TAG_WHITELIST.equals(tag)) {
1891 insideWhitelist = false;
1892 }
1893
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001894 }
1895 }
1896
Felipe Leme46b451f2016-08-19 08:46:17 -07001897 final int size = whitelistedRestrictBackground.size();
1898 for (int i = 0; i < size; i++) {
1899 final int uid = whitelistedRestrictBackground.keyAt(i);
1900 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1901 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1902 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1903 + " because its policy is " + uidPoliciesToString(policy));
1904 continue;
1905 }
1906 if (UserHandle.isApp(uid)) {
1907 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1908 if (LOGV)
1909 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1910 setUidPolicyUncheckedUL(uid, newPolicy, false);
1911 } else {
1912 Slog.w(TAG, "unable to update policy on UID " + uid);
1913 }
1914 }
1915
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001916 } catch (FileNotFoundException e) {
1917 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001918 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001919 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001920 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001921 } finally {
1922 IoUtils.closeQuietly(fis);
1923 }
1924 }
1925
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001926 /**
1927 * Upgrade legacy background data flags, notifying listeners of one last
1928 * change to always-true.
1929 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001930 private void upgradeDefaultBackgroundDataUL() {
1931 // This method is only called when we're unable to find the network policy flag, which
1932 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001933
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001934 // Seed from the default value configured for this device.
1935 mRestrictBackground = Settings.Global.getInt(
1936 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
1937
1938 // NOTE: We used to read the legacy setting here :
1939 //
1940 // final int legacyFlagValue = Settings.Secure.getInt(
1941 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
1942 //
1943 // This is no longer necessary because we will never upgrade directly from Gingerbread
1944 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
1945 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001946 }
1947
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001948 /**
1949 * Perform upgrade step of moving any user-defined meterness overrides over
1950 * into {@link WifiConfiguration}.
1951 */
1952 private void upgradeWifiMeteredOverrideAL() {
1953 boolean modified = false;
1954 final WifiManager wm = mContext.getSystemService(WifiManager.class);
1955 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
1956 for (int i = 0; i < mNetworkPolicy.size(); ) {
1957 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1958 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
1959 && !policy.inferred) {
1960 mNetworkPolicy.removeAt(i);
1961 modified = true;
1962
1963 final String networkId = resolveNetworkId(policy.template.getNetworkId());
1964 for (WifiConfiguration config : configs) {
1965 if (Objects.equals(resolveNetworkId(config), networkId)) {
1966 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
1967 config.meteredOverride = policy.metered
1968 ? WifiConfiguration.METERED_OVERRIDE_METERED
1969 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
1970 wm.updateNetwork(config);
1971 }
1972 }
1973 } else {
1974 i++;
1975 }
1976 }
1977 if (modified) {
1978 writePolicyAL();
1979 }
1980 }
1981
Felipe Lemef0823852016-06-08 13:43:08 -07001982 void writePolicyAL() {
1983 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001984
1985 FileOutputStream fos = null;
1986 try {
1987 fos = mPolicyFile.startWrite();
1988
1989 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001990 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001991 out.startDocument(null, true);
1992
1993 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001994 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001995 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001996
1997 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001998 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1999 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002000 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002001 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002002
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002003 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002004 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2005 final String subscriberId = template.getSubscriberId();
2006 if (subscriberId != null) {
2007 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002008 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002009 final String networkId = template.getNetworkId();
2010 if (networkId != null) {
2011 out.attribute(null, ATTR_NETWORK_ID, networkId);
2012 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002013 writeStringAttribute(out, ATTR_CYCLE_START,
2014 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2015 writeStringAttribute(out, ATTR_CYCLE_END,
2016 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2017 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2018 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002019 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2020 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002021 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2022 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002023 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002024 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002025 out.endTag(null, TAG_NETWORK_POLICY);
2026 }
2027
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002028 // write all known subscription plans
2029 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2030 final int subId = mSubscriptionPlans.keyAt(i);
2031 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2032 if (ArrayUtils.isEmpty(plans)) continue;
2033
2034 for (SubscriptionPlan plan : plans) {
2035 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2036 writeIntAttribute(out, ATTR_SUB_ID, subId);
2037 final RecurrenceRule cycleRule = plan.getCycleRule();
2038 writeStringAttribute(out, ATTR_CYCLE_START,
2039 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2040 writeStringAttribute(out, ATTR_CYCLE_END,
2041 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2042 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2043 RecurrenceRule.convertPeriod(cycleRule.period));
2044 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2045 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2046 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2047 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2048 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2049 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2050 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2051 }
2052 }
2053
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002054 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002055 for (int i = 0; i < mUidPolicy.size(); i++) {
2056 final int uid = mUidPolicy.keyAt(i);
2057 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002058
Jeff Sharkey497e4432011-06-14 17:27:29 -07002059 // skip writing empty policies
2060 if (policy == POLICY_NONE) continue;
2061
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002062 out.startTag(null, TAG_UID_POLICY);
2063 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002064 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002065 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002066 }
2067
2068 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002069
2070 // write all whitelists
2071 out.startTag(null, TAG_WHITELIST);
2072
Felipe Lemea9505cc2016-02-26 10:28:41 -08002073 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002074 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002075 for (int i = 0; i < size; i++) {
2076 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2077 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2078 writeIntAttribute(out, ATTR_UID, uid);
2079 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2080 }
2081
Felipe Lemeb85a6372016-01-14 16:16:16 -08002082 out.endTag(null, TAG_WHITELIST);
2083
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002084 out.endDocument();
2085
2086 mPolicyFile.finishWrite(fos);
2087 } catch (IOException e) {
2088 if (fos != null) {
2089 mPolicyFile.failWrite(fos);
2090 }
2091 }
2092 }
2093
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002094 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002095 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002096 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002097
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002098 if (!UserHandle.isApp(uid)) {
2099 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002100 }
Felipe Lemef0823852016-06-08 13:43:08 -07002101 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002102 final long token = Binder.clearCallingIdentity();
2103 try {
2104 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2105 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002106 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002107 }
2108 } finally {
2109 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002110 }
2111 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002112 }
2113
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002114 @Override
2115 public void addUidPolicy(int uid, int policy) {
2116 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002117
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002118 if (!UserHandle.isApp(uid)) {
2119 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2120 }
2121
Felipe Lemef0823852016-06-08 13:43:08 -07002122 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002123 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2124 policy |= oldPolicy;
2125 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002126 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002127 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002128 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002129 }
2130
2131 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002132 public void removeUidPolicy(int uid, int policy) {
2133 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2134
2135 if (!UserHandle.isApp(uid)) {
2136 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2137 }
2138
Felipe Lemef0823852016-06-08 13:43:08 -07002139 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002140 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2141 policy = oldPolicy & ~policy;
2142 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002143 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002144 }
2145 }
2146 }
2147
Felipe Lemef0823852016-06-08 13:43:08 -07002148 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2149 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002150
Felipe Leme57e3d312016-08-23 14:42:52 -07002151 final boolean notifyApp;
2152 if (!isUidValidForWhitelistRules(uid)) {
2153 notifyApp = false;
2154 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002155 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2156 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2157 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2158 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002159 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2160 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002161 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2162 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2163 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2164 if (LOGD)
2165 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2166 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2167 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002168 notifyApp = wasBlocked != isBlocked;
2169 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002170 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2171 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002172 }
2173
Felipe Lemef0823852016-06-08 13:43:08 -07002174 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002175 if (policy == POLICY_NONE) {
2176 mUidPolicy.delete(uid);
2177 } else {
2178 mUidPolicy.put(uid, policy);
2179 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002180
2181 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002182 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002183 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002184 synchronized (mNetworkPoliciesSecondLock) {
2185 writePolicyAL();
2186 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002187 }
2188 }
2189
2190 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002191 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002192 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2193
Felipe Lemef0823852016-06-08 13:43:08 -07002194 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002195 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002196 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002197 }
2198
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002199 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002200 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002201 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2202
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002203 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002204 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002205 for (int i = 0; i < mUidPolicy.size(); i++) {
2206 final int uid = mUidPolicy.keyAt(i);
2207 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002208 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2209 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002210 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002211 }
2212 }
2213 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002214 return uids;
2215 }
2216
2217 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002218 * Removes any persistable state associated with given {@link UserHandle}, persisting
2219 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002220 */
Felipe Lemef0823852016-06-08 13:43:08 -07002221 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002222
Felipe Lemef0823852016-06-08 13:43:08 -07002223 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07002224 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002225
Felipe Lemea110eec2016-04-29 09:58:06 -07002226 // Remove entries from revoked default restricted background UID whitelist
2227 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2228 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2229 if (UserHandle.getUserId(uid) == userId) {
2230 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002231 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002232 }
2233 }
2234
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002235 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002236 int[] uids = new int[0];
2237 for (int i = 0; i < mUidPolicy.size(); i++) {
2238 final int uid = mUidPolicy.keyAt(i);
2239 if (UserHandle.getUserId(uid) == userId) {
2240 uids = appendInt(uids, uid);
2241 }
2242 }
2243
2244 if (uids.length > 0) {
2245 for (int uid : uids) {
2246 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002247 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002248 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002249 }
Felipe Lemef0823852016-06-08 13:43:08 -07002250 synchronized (mNetworkPoliciesSecondLock) {
2251 updateRulesForGlobalChangeAL(true);
2252 if (writePolicy && changed) {
2253 writePolicyAL();
2254 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002255 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002256 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002257 }
2258
2259 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002260 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002261 // TODO: create permission for observing network policy
2262 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002263 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002264 }
2265
2266 @Override
2267 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002268 // TODO: create permission for observing network policy
2269 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002270 mListeners.unregister(listener);
2271 }
2272
Jeff Sharkey1b861272011-05-22 00:34:52 -07002273 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002274 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002275 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2276
Felipe Leme6a05eee2016-02-19 14:43:51 -08002277 final long token = Binder.clearCallingIdentity();
2278 try {
2279 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002280 synchronized (mUidRulesFirstLock) {
2281 synchronized (mNetworkPoliciesSecondLock) {
2282 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002283 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002284 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002285 }
2286 } finally {
2287 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002288 }
2289 }
2290
Hugo Benichi446c9c92017-04-10 09:41:10 +09002291 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002292 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002293 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2294 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002295 }
2296
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002297 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002298 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002299 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002300 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002301 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2302 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2303 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002304 } catch (SecurityException e) {
2305 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002306
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002307 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2308 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2309 return new NetworkPolicy[0];
2310 }
Svet Ganov16a16892015-04-16 10:32:04 -07002311 }
2312
Felipe Lemef0823852016-06-08 13:43:08 -07002313 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002314 final int size = mNetworkPolicy.size();
2315 final NetworkPolicy[] policies = new NetworkPolicy[size];
2316 for (int i = 0; i < size; i++) {
2317 policies[i] = mNetworkPolicy.valueAt(i);
2318 }
2319 return policies;
2320 }
2321 }
2322
Felipe Lemef0823852016-06-08 13:43:08 -07002323 private void normalizePoliciesNL() {
2324 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002325 }
2326
Felipe Lemef0823852016-06-08 13:43:08 -07002327 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002328 final TelephonyManager tele = TelephonyManager.from(mContext);
2329 final String[] merged = tele.getMergedSubscriberIds();
2330
2331 mNetworkPolicy.clear();
2332 for (NetworkPolicy policy : policies) {
2333 // When two normalized templates conflict, prefer the most
2334 // restrictive policy
2335 policy.template = NetworkTemplate.normalize(policy.template, merged);
2336 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2337 if (existing == null || existing.compareTo(policy) > 0) {
2338 if (existing != null) {
2339 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2340 }
2341 mNetworkPolicy.put(policy.template, policy);
2342 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002343 }
2344 }
2345
2346 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002347 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002348 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002349
2350 final long token = Binder.clearCallingIdentity();
2351 try {
2352 performSnooze(template, TYPE_LIMIT);
2353 } finally {
2354 Binder.restoreCallingIdentity(token);
2355 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002356 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002357
Dianne Hackborn497175b2014-07-01 12:56:08 -07002358 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002359 maybeRefreshTrustedTime();
2360 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002361 synchronized (mUidRulesFirstLock) {
2362 synchronized (mNetworkPoliciesSecondLock) {
2363 // find and snooze local policy that matches
2364 final NetworkPolicy policy = mNetworkPolicy.get(template);
2365 if (policy == null) {
2366 throw new IllegalArgumentException("unable to find policy for " + template);
2367 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002368
Felipe Lemef0823852016-06-08 13:43:08 -07002369 switch (type) {
2370 case TYPE_WARNING:
2371 policy.lastWarningSnooze = currentTime;
2372 break;
2373 case TYPE_LIMIT:
2374 policy.lastLimitSnooze = currentTime;
2375 break;
2376 default:
2377 throw new IllegalArgumentException("unexpected type");
2378 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002379
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002380 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002381 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002382 }
2383 }
2384
2385 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002386 public void onTetheringChanged(String iface, boolean tethering) {
2387 // No need to enforce permission because setRestrictBackground() will do it.
2388 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002389 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002390 if (mRestrictBackground && tethering) {
2391 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2392 setRestrictBackground(false);
2393 }
2394 }
2395 }
2396
2397 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002398 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002399 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002400 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002401 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2402 final long token = Binder.clearCallingIdentity();
2403 try {
2404 maybeRefreshTrustedTime();
2405 synchronized (mUidRulesFirstLock) {
2406 if (restrictBackground == mRestrictBackground) {
2407 // Ideally, UI should never allow this scenario...
2408 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2409 return;
2410 }
2411 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002412 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002413
2414 } finally {
2415 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002416 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002417
Felipe Leme29e72ea2016-09-08 13:26:55 -07002418 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2419 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002420 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002421 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002422 }
2423 }
2424
Felipe Lemef0823852016-06-08 13:43:08 -07002425 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002426 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002427 final boolean oldRestrictBackground = mRestrictBackground;
2428 mRestrictBackground = restrictBackground;
2429 // Must whitelist foreground apps before turning data saver mode on.
2430 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2431 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002432 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002433 try {
2434 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2435 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2436 mRestrictBackground = oldRestrictBackground;
2437 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002438 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002439 return;
2440 }
2441 } catch (RemoteException e) {
2442 // ignored; service lives in system_server
2443 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002444
2445 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2446 mRestrictBackgroundChangedInBsm = true;
2447 }
Felipe Lemef0823852016-06-08 13:43:08 -07002448 synchronized (mNetworkPoliciesSecondLock) {
2449 updateNotificationsNL();
2450 writePolicyAL();
2451 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002452 }
2453
Felipe Lemeb85a6372016-01-14 16:16:16 -08002454 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002455 public int getRestrictBackgroundByCaller() {
2456 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2457 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002458
Felipe Lemef0823852016-06-08 13:43:08 -07002459 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002460 // Must clear identity because getUidPolicy() is restricted to system.
2461 final long token = Binder.clearCallingIdentity();
2462 final int policy;
2463 try {
2464 policy = getUidPolicy(uid);
2465 } finally {
2466 Binder.restoreCallingIdentity(token);
2467 }
2468 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2469 // App is blacklisted.
2470 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2471 }
Felipe Leme1b103232016-01-22 09:44:57 -08002472 if (!mRestrictBackground) {
2473 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2474 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002475 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002476 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2477 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2478 }
2479 }
2480
2481 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002482 public boolean getRestrictBackground() {
2483 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2484
Felipe Lemef0823852016-06-08 13:43:08 -07002485 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002486 return mRestrictBackground;
2487 }
2488 }
2489
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002490 @Override
2491 public void setDeviceIdleMode(boolean enabled) {
2492 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002493 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2494 try {
2495 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002496 if (mDeviceIdleMode == enabled) {
2497 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002498 }
Felipe Lemeea014392016-09-06 13:59:54 -07002499 mDeviceIdleMode = enabled;
2500 if (mSystemReady) {
2501 // Device idle change means we need to rebuild rules for all
2502 // known apps, so do a global refresh.
2503 updateRulesForRestrictPowerUL();
2504 }
2505 }
2506 if (enabled) {
2507 EventLogTags.writeDeviceIdleOnPhase("net");
2508 } else {
2509 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002510 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002511 } finally {
2512 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002513 }
2514 }
2515
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002516 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002517 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2518 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002519 final long token = Binder.clearCallingIdentity();
2520 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002521 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2522 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2523 for (WifiConfiguration config : configs) {
2524 if (Objects.equals(resolveNetworkId(config), networkId)) {
2525 config.meteredOverride = meteredOverride;
2526 wm.updateNetwork(config);
2527 }
2528 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002529 } finally {
2530 Binder.restoreCallingIdentity(token);
2531 }
2532 }
2533
Jeff Sharkey46645002011-07-27 21:11:21 -07002534 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002535 @Deprecated
2536 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2537 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2538 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2539 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002540 }
2541
Jeff Sharkey53313d72017-07-13 16:47:32 -06002542 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2543 // Verify they're not lying about package name
2544 mAppOps.checkPackage(callingUid, callingPackage);
2545
2546 // Verify they have phone permission from user
2547 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
2548 if (mAppOps.checkOp(AppOpsManager.OP_READ_PHONE_STATE, callingUid,
2549 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2550 throw new SecurityException(
2551 "Calling package " + callingPackage + " does not hold " + READ_PHONE_STATE);
2552 }
2553
2554 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002555 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002556 final long token = Binder.clearCallingIdentity();
2557 try {
2558 si = mContext.getSystemService(SubscriptionManager.class)
2559 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002560 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002561 } finally {
2562 Binder.restoreCallingIdentity(token);
2563 }
2564
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002565 // First check: is caller the CarrierService?
Jeff Sharkey53313d72017-07-13 16:47:32 -06002566 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002567 return;
2568 }
2569
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002570 // Second check: has the CarrierService delegated access?
2571 if (config != null) {
2572 final String overridePackage = config
2573 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2574 if (!TextUtils.isEmpty(overridePackage)
2575 && Objects.equals(overridePackage, callingPackage)) {
2576 return;
2577 }
2578 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002579
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002580 // Third check: is caller the fallback/default CarrierService?
2581 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2582 if (!TextUtils.isEmpty(defaultPackage)
2583 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002584 return;
2585 }
2586
2587 throw new SecurityException("Calling package " + callingPackage
2588 + " has no access to subscription plans for " + subId);
2589 }
2590
2591 @Override
2592 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2593 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2594
Jeff Sharkey53313d72017-07-13 16:47:32 -06002595 final String fake = SystemProperties.get("fw.fake_plan");
2596 if (!TextUtils.isEmpty(fake)) {
2597 final List<SubscriptionPlan> plans = new ArrayList<>();
2598 if ("month_hard".equals(fake)) {
2599 plans.add(SubscriptionPlan.Builder
2600 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2601 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002602 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2603 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2604 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2605 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2606 .build());
2607 } else if ("month_soft".equals(fake)) {
2608 plans.add(SubscriptionPlan.Builder
2609 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2610 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2611 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2612 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002613 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2614 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2615 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2616 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2617 .build());
2618 } else if ("month_none".equals(fake)) {
2619 plans.add(SubscriptionPlan.Builder
2620 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2621 .setTitle("G-Mobile")
2622 .build());
2623 } else if ("prepaid".equals(fake)) {
2624 plans.add(SubscriptionPlan.Builder
2625 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2626 ZonedDateTime.now().plusDays(10))
2627 .setTitle("G-Mobile")
2628 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2629 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2630 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2631 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2632 .build());
2633 } else if ("prepaid_crazy".equals(fake)) {
2634 plans.add(SubscriptionPlan.Builder
2635 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2636 ZonedDateTime.now().plusDays(10))
2637 .setTitle("G-Mobile Anytime")
2638 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2639 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2640 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2641 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2642 .build());
2643 plans.add(SubscriptionPlan.Builder
2644 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2645 ZonedDateTime.now().plusDays(20))
2646 .setTitle("G-Mobile Nickel Nights")
2647 .setSummary("5¢/GB between 1-5AM")
2648 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2649 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2650 .build());
2651 plans.add(SubscriptionPlan.Builder
2652 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2653 ZonedDateTime.now().plusDays(20))
2654 .setTitle("G-Mobile Bonus 3G")
2655 .setSummary("Unlimited 3G data")
2656 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2657 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2658 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2659 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2660 .build());
2661 }
2662 return plans.toArray(new SubscriptionPlan[plans.size()]);
2663 }
2664
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002665 synchronized (mUidRulesFirstLock) {
2666 synchronized (mNetworkPoliciesSecondLock) {
2667 return mSubscriptionPlans.get(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002668 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002669 }
2670 }
2671
2672 @Override
2673 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2674 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2675
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002676 for (SubscriptionPlan plan : plans) {
2677 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002678 }
2679
2680 final long token = Binder.clearCallingIdentity();
2681 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002682 maybeRefreshTrustedTime();
2683 synchronized (mUidRulesFirstLock) {
2684 synchronized (mNetworkPoliciesSecondLock) {
2685 mSubscriptionPlans.put(subId, plans);
2686 // TODO: update any implicit details from newly defined plans
2687 handleNetworkPoliciesUpdateAL(false);
2688 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002689 }
2690 } finally {
2691 Binder.restoreCallingIdentity(token);
2692 }
2693 }
2694
2695 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002696 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002697 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002698
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002699 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2700
Dianne Hackborn497175b2014-07-01 12:56:08 -07002701 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002702 for (String arg : args) {
2703 argSet.add(arg);
2704 }
2705
Felipe Lemef0823852016-06-08 13:43:08 -07002706 synchronized (mUidRulesFirstLock) {
2707 synchronized (mNetworkPoliciesSecondLock) {
2708 if (argSet.contains("--unsnooze")) {
2709 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2710 mNetworkPolicy.valueAt(i).clearSnooze();
2711 }
2712
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002713 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002714
2715 fout.println("Cleared snooze timestamps");
2716 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002717 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002718
Felipe Lemef0823852016-06-08 13:43:08 -07002719 fout.print("System ready: "); fout.println(mSystemReady);
2720 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2721 fout.print("Restrict power: "); fout.println(mRestrictPower);
2722 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2723 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002724 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002725 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2726 fout.println(mNetworkPolicy.valueAt(i).toString());
2727 }
2728 fout.decreaseIndent();
2729
2730 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2731
2732 fout.println("Policy for UIDs:");
2733 fout.increaseIndent();
2734 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002735 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002736 final int uid = mUidPolicy.keyAt(i);
2737 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002738 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002739 fout.print(uid);
2740 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002741 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002742 fout.println();
2743 }
2744 fout.decreaseIndent();
2745
2746 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2747 if (size > 0) {
2748 fout.println("Power save whitelist (except idle) app ids:");
2749 fout.increaseIndent();
2750 for (int i = 0; i < size; i++) {
2751 fout.print("UID=");
2752 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2753 fout.print(": ");
2754 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2755 fout.println();
2756 }
2757 fout.decreaseIndent();
2758 }
2759
2760 size = mPowerSaveWhitelistAppIds.size();
2761 if (size > 0) {
2762 fout.println("Power save whitelist app ids:");
2763 fout.increaseIndent();
2764 for (int i = 0; i < size; i++) {
2765 fout.print("UID=");
2766 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2767 fout.print(": ");
2768 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2769 fout.println();
2770 }
2771 fout.decreaseIndent();
2772 }
2773
Felipe Lemef0823852016-06-08 13:43:08 -07002774 size = mDefaultRestrictBackgroundWhitelistUids.size();
2775 if (size > 0) {
2776 fout.println("Default restrict background whitelist uids:");
2777 fout.increaseIndent();
2778 for (int i = 0; i < size; i++) {
2779 fout.print("UID=");
2780 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2781 fout.println();
2782 }
2783 fout.decreaseIndent();
2784 }
2785
2786 size = mRestrictBackgroundWhitelistRevokedUids.size();
2787 if (size > 0) {
2788 fout.println("Default restrict background whitelist uids revoked by users:");
2789 fout.increaseIndent();
2790 for (int i = 0; i < size; i++) {
2791 fout.print("UID=");
2792 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2793 fout.println();
2794 }
2795 fout.decreaseIndent();
2796 }
2797
2798 final SparseBooleanArray knownUids = new SparseBooleanArray();
2799 collectKeys(mUidState, knownUids);
2800 collectKeys(mUidRules, knownUids);
2801
2802 fout.println("Status for all known UIDs:");
2803 fout.increaseIndent();
2804 size = knownUids.size();
2805 for (int i = 0; i < size; i++) {
2806 final int uid = knownUids.keyAt(i);
2807 fout.print("UID=");
2808 fout.print(uid);
2809
2810 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2811 fout.print(" state=");
2812 fout.print(state);
2813 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2814 fout.print(" (fg)");
2815 } else {
2816 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2817 ? " (fg svc)" : " (bg)");
2818 }
2819
2820 final int uidRules = mUidRules.get(uid, RULE_NONE);
2821 fout.print(" rules=");
2822 fout.print(uidRulesToString(uidRules));
2823 fout.println();
2824 }
2825 fout.decreaseIndent();
2826
2827 fout.println("Status for just UIDs with rules:");
2828 fout.increaseIndent();
2829 size = mUidRules.size();
2830 for (int i = 0; i < size; i++) {
2831 final int uid = mUidRules.keyAt(i);
2832 fout.print("UID=");
2833 fout.print(uid);
2834 final int uidRules = mUidRules.get(uid, RULE_NONE);
2835 fout.print(" rules=");
2836 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002837 fout.println();
2838 }
2839 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08002840
2841 fout.println("Observed uid state changes:");
2842 fout.increaseIndent();
2843 mObservedHistory.dumpUL(fout);
2844 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002845 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002846 }
2847 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002848
2849 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002850 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002851 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002852 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002853 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002854 }
2855
2856 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002857 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002858 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2859
Felipe Lemef0823852016-06-08 13:43:08 -07002860 synchronized (mUidRulesFirstLock) {
2861 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002862 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002863 }
2864
Felipe Lemef0823852016-06-08 13:43:08 -07002865 private boolean isUidForegroundUL(int uid) {
2866 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002867 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2868 }
2869
Felipe Lemef0823852016-06-08 13:43:08 -07002870 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002871 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002872 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002873 }
2874
Felipe Lemef0823852016-06-08 13:43:08 -07002875 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002876 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2877 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2878 }
2879
Felipe Lemef0823852016-06-08 13:43:08 -07002880 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002881 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002882 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002883 }
2884
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002885 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002886 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002887 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2888 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002889 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002890 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002891 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2892 try {
2893 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2894 if (oldUidState != uidState) {
2895 // state changed, push updated rules
2896 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002897 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2898 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2899 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2900 if (isUidIdle(uid)) {
2901 updateRuleForAppIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002902 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002903 if (mDeviceIdleMode) {
2904 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002905 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002906 if (mRestrictPower) {
2907 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002908 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002909 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002910 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002911 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002912 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002913 } finally {
2914 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002915 }
2916 }
2917
Felipe Lemef0823852016-06-08 13:43:08 -07002918 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002919 final int index = mUidState.indexOfKey(uid);
2920 if (index >= 0) {
2921 final int oldUidState = mUidState.valueAt(index);
2922 mUidState.removeAt(index);
2923 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002924 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00002925 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002926 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002927 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002928 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002929 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002930 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002931 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002932 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002933 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002934 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002935 }
2936 }
2937
Felipe Lemef28983d2016-03-25 12:18:23 -07002938 // adjust stats accounting based on foreground status
2939 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002940 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2941 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
2942 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
2943 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002944 try {
2945 mNetworkStats.setUidForeground(uid, uidForeground);
2946 } catch (RemoteException e) {
2947 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002948 } finally {
2949 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07002950 }
2951 }
2952
Sudheer Shankac9d94072017-02-22 22:13:55 +00002953 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
2954 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002955 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002956 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002957 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002958 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002959 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00002960 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002961 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002962 }
2963
Felipe Lemef0823852016-06-08 13:43:08 -07002964 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002965 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
2966 try {
2967 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2968 mUidFirewallPowerSaveRules);
2969 } finally {
2970 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2971 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002972 }
2973
Felipe Lemef0823852016-06-08 13:43:08 -07002974 void updateRuleForRestrictPowerUL(int uid) {
2975 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002976 }
2977
Felipe Lemef0823852016-06-08 13:43:08 -07002978 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002979 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
2980 try {
2981 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2982 mUidFirewallDozableRules);
2983 } finally {
2984 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2985 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002986 }
2987
Felipe Lemef0823852016-06-08 13:43:08 -07002988 void updateRuleForDeviceIdleUL(int uid) {
2989 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002990 }
2991
Felipe Lemef28983d2016-03-25 12:18:23 -07002992 // NOTE: since both fw_dozable and fw_powersave uses the same map
2993 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002994 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002995 SparseIntArray rules) {
2996 if (enabled) {
2997 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002998 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002999 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003000 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003001 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003002 for (int ui = users.size() - 1; ui >= 0; ui--) {
3003 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003004 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3005 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3006 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3007 updateRulesForWhitelistedAppIds(uidRules,
3008 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003009 }
3010 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003011 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003012 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003013 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3014 }
3015 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003016 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
3017 } else {
3018 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003019 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003020 }
3021
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003022 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3023 final SparseBooleanArray whitelistedAppIds, int userId) {
3024 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3025 if (whitelistedAppIds.valueAt(i)) {
3026 final int appId = whitelistedAppIds.keyAt(i);
3027 final int uid = UserHandle.getUid(userId, appId);
3028 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3029 }
3030 }
3031 }
3032
3033 /**
3034 * @param deviceIdleMode if true then we don't consider
3035 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3036 * whitelisted.
3037 */
3038 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003039 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003040 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3041 || mPowerSaveWhitelistAppIds.get(appId);
3042 if (!deviceIdleMode) {
3043 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3044 }
3045 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003046 }
3047
Felipe Lemef28983d2016-03-25 12:18:23 -07003048 // NOTE: since both fw_dozable and fw_powersave uses the same map
3049 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003050 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003051 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003052 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3053 chain == FIREWALL_CHAIN_DOZABLE);
3054 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003055 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003056 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003057 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003058 }
3059 }
3060 }
3061
Felipe Lemef0823852016-06-08 13:43:08 -07003062 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003063 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3064 try {
3065 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3066 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003067
Felipe Leme873a83a2016-09-07 11:34:10 -07003068 // Fully update the app idle firewall chain.
3069 final List<UserInfo> users = mUserManager.getUsers();
3070 for (int ui = users.size() - 1; ui >= 0; ui--) {
3071 UserInfo user = users.get(ui);
3072 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3073 for (int uid : idleUids) {
3074 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3075 // quick check: if this uid doesn't have INTERNET permission, it
3076 // doesn't have network access anyway, so it is a waste to mess
3077 // with it here.
3078 if (hasInternetPermissions(uid)) {
3079 uidRules.put(uid, FIREWALL_RULE_DENY);
3080 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003081 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003082 }
3083 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003084
Felipe Lemebc853dd2016-09-08 13:26:55 -07003085 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003086 } finally {
3087 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3088 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003089 }
3090
Felipe Lemef0823852016-06-08 13:43:08 -07003091 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003092 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003093
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003094 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3095 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3096 }
3097 try {
3098 int appId = UserHandle.getAppId(uid);
3099 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3100 && !isUidForegroundOnRestrictPowerUL(uid)) {
3101 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3102 } else {
3103 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3104 }
3105 } finally {
3106 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003107 }
3108 }
3109
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003110 /**
3111 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3112 * changed.
3113 */
Felipe Lemef0823852016-06-08 13:43:08 -07003114 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003115 boolean paroled = mUsageStats.isAppIdleParoleOn();
3116 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003117 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003118
3119 int ruleCount = mUidFirewallStandbyRules.size();
3120 for (int i = 0; i < ruleCount; i++) {
3121 int uid = mUidFirewallStandbyRules.keyAt(i);
3122 int oldRules = mUidRules.get(uid);
3123 if (enableChain) {
3124 // Chain wasn't enabled before and the other power-related
3125 // chains are whitelists, so we can clear the
3126 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3127 // the effective rules result in blocking network access.
3128 oldRules &= MASK_METERED_NETWORKS;
3129 } else {
3130 // Skip if it had no restrictions to begin with
3131 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3132 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003133 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3134 if (newUidRules == RULE_NONE) {
3135 mUidRules.delete(uid);
3136 } else {
3137 mUidRules.put(uid, newUidRules);
3138 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003139 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003140 }
3141
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003142 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003143 * Update rules that might be changed by {@link #mRestrictBackground},
3144 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003145 */
Felipe Lemef0823852016-06-08 13:43:08 -07003146 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003147 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3148 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3149 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3150 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003151 try {
Felipe Leme09700462016-09-08 09:33:48 -07003152 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003153 updateRulesForRestrictPowerUL();
3154 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003155
Felipe Leme873a83a2016-09-07 11:34:10 -07003156 // If the set of restricted networks may have changed, re-evaluate those.
3157 if (restrictedNetworksChanged) {
3158 normalizePoliciesNL();
3159 updateNetworkRulesNL();
3160 }
3161 } finally {
3162 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003163 }
3164 }
3165
Felipe Leme09700462016-09-08 09:33:48 -07003166 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003167 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003168 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3169 try {
3170 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003171 updateRulesForPowerSaveUL();
3172 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3173 } finally {
3174 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3175 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003176 }
3177
Felipe Lemef0823852016-06-08 13:43:08 -07003178 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003179 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3180 try {
3181 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3182 } finally {
3183 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3184 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003185 }
3186
3187 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3188 private static final int TYPE_RESTRICT_POWER = 2;
3189 @Retention(RetentionPolicy.SOURCE)
3190 @IntDef(flag = false, value = {
3191 TYPE_RESTRICT_BACKGROUND,
3192 TYPE_RESTRICT_POWER,
3193 })
3194 public @interface RestrictType {
3195 }
3196
3197 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003198 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003199 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3200 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3201 }
3202 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003203 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003204
3205 final PackageManager pm = mContext.getPackageManager();
3206 final List<UserInfo> users;
3207 final List<ApplicationInfo> apps;
3208
3209 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3210 try {
3211 users = mUserManager.getUsers();
3212 } finally {
3213 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3214 }
3215 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3216 try {
3217 apps = pm.getInstalledApplications(
3218 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3219 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3220 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3221 } finally {
3222 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3223 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003224
Felipe Leme873a83a2016-09-07 11:34:10 -07003225 final int usersSize = users.size();
3226 final int appsSize = apps.size();
3227 for (int i = 0; i < usersSize; i++) {
3228 final UserInfo user = users.get(i);
3229 for (int j = 0; j < appsSize; j++) {
3230 final ApplicationInfo app = apps.get(j);
3231 final int uid = UserHandle.getUid(user.id, app.uid);
3232 switch (type) {
3233 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003234 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003235 break;
3236 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003237 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003238 break;
3239 default:
3240 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3241 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003242 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003243 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003244 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003245 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003246 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003247 }
3248
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003249 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003250 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003251 final int numUsers = users.size();
3252 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003253 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003254 int uid = UserHandle.getUid(user.id, appId);
3255 // Update external firewall rules.
3256 updateRuleForAppIdleUL(uid);
3257 updateRuleForDeviceIdleUL(uid);
3258 updateRuleForRestrictPowerUL(uid);
3259 // Update internal rules.
3260 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003261 }
3262 }
3263
Felipe Leme70c57c22016-03-29 10:45:13 -07003264 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3265 // methods below could be merged into a isUidValidForRules() method.
3266 private boolean isUidValidForBlacklistRules(int uid) {
3267 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003268 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003269 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003270 return true;
3271 }
3272
3273 return false;
3274 }
3275
Felipe Leme70c57c22016-03-29 10:45:13 -07003276 private boolean isUidValidForWhitelistRules(int uid) {
3277 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3278 }
3279
Amith Yamasani15e472352015-04-24 19:06:07 -07003280 private boolean isUidIdle(int uid) {
3281 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3282 final int userId = UserHandle.getUserId(uid);
3283
songjinshi0655edd2016-05-18 19:55:32 +08003284 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003285 for (String packageName : packages) {
3286 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3287 return false;
3288 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003289 }
3290 }
3291 return true;
3292 }
3293
3294 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003295 * Checks if an uid has INTERNET permissions.
3296 * <p>
3297 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003298 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003299 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003300 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003301 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003302 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003303 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003304 }
3305 } catch (RemoteException e) {
3306 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003307 return true;
3308 }
3309
3310 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003311 * Clears all state - internal and external - associated with an UID.
3312 */
3313 private void onUidDeletedUL(int uid) {
3314 // First cleanup in-memory state synchronously...
3315 mUidRules.delete(uid);
3316 mUidPolicy.delete(uid);
3317 mUidFirewallStandbyRules.delete(uid);
3318 mUidFirewallDozableRules.delete(uid);
3319 mUidFirewallPowerSaveRules.delete(uid);
3320 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3321 mPowerSaveWhitelistAppIds.delete(uid);
3322 mPowerSaveTempWhitelistAppIds.delete(uid);
3323
3324 // ...then update iptables asynchronously.
3325 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3326 }
3327
3328 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003329 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003330 *
Felipe Leme781ba142016-05-09 16:24:48 -07003331 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003332 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003333 * <li>Doze mode
3334 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003335 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003336 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003337 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003338 *
3339 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003340 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003341 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003342 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003343 updateRuleForDeviceIdleUL(uid);
3344 updateRuleForAppIdleUL(uid);
3345 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003346
3347 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003348 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003349
3350 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003351 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003352 }
3353
Felipe Leme70c57c22016-03-29 10:45:13 -07003354 /**
3355 * Applies network rules to bandwidth controllers based on process state and user-defined
3356 * restrictions (blacklist / whitelist).
3357 *
3358 * <p>
3359 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3360 * networks:
3361 * <ul>
3362 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3363 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3364 * also blacklisted.
3365 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3366 * no UIDs other those whitelisted will have access.
3367 * <ul>
3368 *
3369 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3370 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3371 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3372 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003373 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003374 * {@link INetworkManagementService}, but this method should also be called in events (like
3375 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3376 * following rules should also be applied:
3377 *
3378 * <ul>
3379 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3380 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3381 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3382 * {@code bw_penalty_box}.
3383 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3384 * </ul>
3385 *
3386 * <p>For optimization, the rules are only applied on user apps that have internet access
3387 * permission, since there is no need to change the {@code iptables} rule if the app does not
3388 * have permission to use the internet.
3389 *
3390 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003391 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003392 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003393 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003394 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3395 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3396 "updateRulesForDataUsageRestrictionsUL: " + uid);
3397 }
3398 try {
3399 updateRulesForDataUsageRestrictionsULInner(uid);
3400 } finally {
3401 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3402 }
3403 }
3404
3405 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003406 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003407 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003408 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003409 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003410
Dianne Hackborn497175b2014-07-01 12:56:08 -07003411 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003412 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003413 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003414
Felipe Leme781ba142016-05-09 16:24:48 -07003415 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003416 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003417 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3418 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003419
Felipe Leme70c57c22016-03-29 10:45:13 -07003420 // First step: define the new rule based on user restrictions and foreground state.
3421 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003422 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3423 newRule = RULE_TEMPORARY_ALLOW_METERED;
3424 } else if (isWhitelisted) {
3425 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003426 }
3427 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003428 if (isBlacklisted) {
3429 newRule = RULE_REJECT_METERED;
3430 } else if (mRestrictBackground && isWhitelisted) {
3431 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003432 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003433 }
Felipe Leme781ba142016-05-09 16:24:48 -07003434 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003435
Felipe Lemef28983d2016-03-25 12:18:23 -07003436 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003437 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003438 + ": isForeground=" +isForeground
3439 + ", isBlacklisted=" + isBlacklisted
3440 + ", isWhitelisted=" + isWhitelisted
3441 + ", oldRule=" + uidRulesToString(oldRule)
3442 + ", newRule=" + uidRulesToString(newRule)
3443 + ", newUidRules=" + uidRulesToString(newUidRules)
3444 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003445 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003446
Felipe Leme46c4fc32016-05-04 09:21:43 -07003447 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003448 mUidRules.delete(uid);
3449 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003450 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003451 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003452
Felipe Leme70c57c22016-03-29 10:45:13 -07003453 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003454 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003455 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003456 // Temporarily whitelist foreground app, removing from blacklist if necessary
3457 // (since bw_penalty_box prevails over bw_happy_box).
3458
3459 setMeteredNetworkWhitelist(uid, true);
3460 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3461 // but ideally it should be just:
3462 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003463 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003464 setMeteredNetworkBlacklist(uid, false);
3465 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003466 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003467 // Remove temporary whitelist from app that is not on foreground anymore.
3468
3469 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3470 // but ideally they should be just:
3471 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3472 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003473 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003474 setMeteredNetworkWhitelist(uid, false);
3475 }
Felipe Leme781ba142016-05-09 16:24:48 -07003476 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003477 setMeteredNetworkBlacklist(uid, true);
3478 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003479 } else if (hasRule(newRule, RULE_REJECT_METERED)
3480 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003481 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003482 setMeteredNetworkBlacklist(uid, isBlacklisted);
Hugo Benichi2966c182017-03-28 17:17:13 +09003483 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003484 // Since blacklist prevails over whitelist, we need to handle the special case
3485 // where app is whitelisted and blacklisted at the same time (although such
3486 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003487 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003488 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003489 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3490 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003491 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003492 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003493 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003494 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003495 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3496 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003497 + ", whitelisted=" + isWhitelisted
3498 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003499 + ", newRule=" + uidRulesToString(newUidRules)
3500 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003501 }
Felipe Leme781ba142016-05-09 16:24:48 -07003502
Sudheer Shankac9d94072017-02-22 22:13:55 +00003503 // Dispatch changed rule to existing listeners.
3504 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003505 }
3506 }
3507
3508 /**
3509 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3510 * listeners in case of change.
3511 * <p>
3512 * There are 3 power-related rules that affects whether an app has background access on
3513 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3514 * restriction, it's added to the equivalent firewall chain:
3515 * <ul>
3516 * <li>App is idle: {@code fw_standby} firewall chain.
3517 * <li>Device is idle: {@code fw_dozable} firewall chain.
3518 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3519 * </ul>
3520 * <p>
3521 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3522 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3523 * <p>
3524 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3525 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003526 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003527 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3528
Sudheer Shankac9d94072017-02-22 22:13:55 +00003529 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003530
Sudheer Shankac9d94072017-02-22 22:13:55 +00003531 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003532 mUidRules.delete(uid);
3533 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003534 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003535 }
3536 }
3537
3538 /**
3539 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3540 *
3541 * @param uid the uid of the app to update rules for
3542 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3543 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3544 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003545 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003546 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003547 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003548 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3549 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3550 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3551 + (paroled ? "P" : "-"));
3552 }
3553 try {
3554 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3555 } finally {
3556 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3557 }
3558 }
3559
3560 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003561 if (!isUidValidForBlacklistRules(uid)) {
3562 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003563 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003564 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003565
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003566 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003567 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003568 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003569
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003570 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003571 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3572 int newRule = RULE_NONE;
3573
3574 // First step: define the new rule based on user restrictions and foreground state.
3575
3576 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3577 // by considering the foreground and non-foreground states.
3578 if (isForeground) {
3579 if (restrictMode) {
3580 newRule = RULE_ALLOW_ALL;
3581 }
3582 } else if (restrictMode) {
3583 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3584 }
3585
3586 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3587
3588 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003589 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003590 + ", isIdle: " + isIdle
3591 + ", mRestrictPower: " + mRestrictPower
3592 + ", mDeviceIdleMode: " + mDeviceIdleMode
3593 + ", isForeground=" + isForeground
3594 + ", isWhitelisted=" + isWhitelisted
3595 + ", oldRule=" + uidRulesToString(oldRule)
3596 + ", newRule=" + uidRulesToString(newRule)
3597 + ", newUidRules=" + uidRulesToString(newUidRules)
3598 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3599 }
3600
Felipe Leme781ba142016-05-09 16:24:48 -07003601 // Second step: notify listeners if state changed.
3602 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003603 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003604 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003605 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003606 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3607 } else {
3608 // All scenarios should have been covered above
3609 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3610 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003611 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003612 + ", newRule=" + uidRulesToString(newUidRules)
3613 + ", oldRule=" + uidRulesToString(oldUidRules));
3614 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003615 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003616 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003617
Sudheer Shankac9d94072017-02-22 22:13:55 +00003618 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003619 }
3620
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003621 private class AppIdleStateChangeListener
3622 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3623
3624 @Override
3625 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3626 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003627 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3628 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003629 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003630 synchronized (mUidRulesFirstLock) {
3631 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003632 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003633 }
3634 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003635 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003636 }
3637
3638 @Override
3639 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003640 synchronized (mUidRulesFirstLock) {
3641 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003642 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003643 }
3644 }
3645
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003646 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3647 if (listener != null) {
3648 try {
3649 listener.onUidRulesChanged(uid, uidRules);
3650 } catch (RemoteException ignored) {
3651 }
3652 }
3653 }
3654
3655 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3656 String[] meteredIfaces) {
3657 if (listener != null) {
3658 try {
3659 listener.onMeteredIfacesChanged(meteredIfaces);
3660 } catch (RemoteException ignored) {
3661 }
3662 }
3663 }
3664
3665 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3666 boolean restrictBackground) {
3667 if (listener != null) {
3668 try {
3669 listener.onRestrictBackgroundChanged(restrictBackground);
3670 } catch (RemoteException ignored) {
3671 }
3672 }
3673 }
3674
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003675 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3676 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003677 if (listener != null) {
3678 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003679 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003680 } catch (RemoteException ignored) {
3681 }
3682 }
3683 }
3684
Makoto Onuki8e777332017-03-28 11:25:47 -07003685 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003686 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003687 public boolean handleMessage(Message msg) {
3688 switch (msg.what) {
3689 case MSG_RULES_CHANGED: {
3690 final int uid = msg.arg1;
3691 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003692 final int length = mListeners.beginBroadcast();
3693 for (int i = 0; i < length; i++) {
3694 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3695 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003696 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003697 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003698 return true;
3699 }
3700 case MSG_METERED_IFACES_CHANGED: {
3701 final String[] meteredIfaces = (String[]) msg.obj;
3702 final int length = mListeners.beginBroadcast();
3703 for (int i = 0; i < length; i++) {
3704 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003705 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003706 }
3707 mListeners.finishBroadcast();
3708 return true;
3709 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003710 case MSG_LIMIT_REACHED: {
3711 final String iface = (String) msg.obj;
3712
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003713 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003714 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003715 if (mMeteredIfaces.contains(iface)) {
3716 try {
3717 // force stats update to make sure we have
3718 // numbers that caused alert to trigger.
3719 mNetworkStats.forceUpdate();
3720 } catch (RemoteException e) {
3721 // ignored; service lives in system_server
3722 }
3723
Felipe Lemef0823852016-06-08 13:43:08 -07003724 updateNetworkEnabledNL();
3725 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003726 }
3727 }
3728 return true;
3729 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003730 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3731 final boolean restrictBackground = msg.arg1 != 0;
3732 final int length = mListeners.beginBroadcast();
3733 for (int i = 0; i < length; i++) {
3734 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003735 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003736 }
3737 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003738 final Intent intent =
3739 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3740 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3741 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3742 return true;
3743 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003744 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003745 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003746 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003747 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003748 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07003749 final int length = mListeners.beginBroadcast();
3750 for (int i = 0; i < length; i++) {
3751 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003752 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003753 }
3754 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003755 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3756 if (notifyApp.booleanValue()) {
3757 broadcastRestrictBackgroundChanged(uid, notifyApp);
3758 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003759 return true;
3760 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003761 case MSG_ADVISE_PERSIST_THRESHOLD: {
3762 final long lowestRule = (Long) msg.obj;
3763 try {
3764 // make sure stats are recorded frequently enough; we aim
3765 // for 2MB threshold for 2GB/month rules.
3766 final long persistThreshold = lowestRule / 1000;
3767 mNetworkStats.advisePersistThreshold(persistThreshold);
3768 } catch (RemoteException e) {
3769 // ignored; service lives in system_server
3770 }
3771 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003772 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003773 case MSG_UPDATE_INTERFACE_QUOTA: {
3774 removeInterfaceQuota((String) msg.obj);
3775 // int params need to be stitched back into a long
3776 setInterfaceQuota((String) msg.obj,
3777 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3778 return true;
3779 }
3780 case MSG_REMOVE_INTERFACE_QUOTA: {
3781 removeInterfaceQuota((String) msg.obj);
3782 return true;
3783 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003784 case MSG_SET_FIREWALL_RULES: {
3785 final int chain = msg.arg1;
3786 final int toggle = msg.arg2;
3787 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3788 if (uidRules != null) {
3789 setUidFirewallRules(chain, uidRules);
3790 }
3791 if (toggle != CHAIN_TOGGLE_NONE) {
3792 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3793 }
3794 return true;
3795 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003796 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3797 resetUidFirewallRules(msg.arg1);
3798 return true;
3799 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003800 default: {
3801 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003802 }
3803 }
3804 }
Makoto Onuki8e777332017-03-28 11:25:47 -07003805 };
3806
3807 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
3808 @Override
3809 public boolean handleMessage(Message msg) {
3810 switch (msg.what) {
3811 case UID_MSG_STATE_CHANGED: {
3812 final int uid = msg.arg1;
3813 final int procState = msg.arg2;
3814 final long procStateSeq = (Long) msg.obj;
3815
3816 handleUidChanged(uid, procState, procStateSeq);
3817 return true;
3818 }
3819 case UID_MSG_GONE: {
3820 final int uid = msg.arg1;
3821 handleUidGone(uid);
3822 return true;
3823 }
3824 default: {
3825 return false;
3826 }
3827 }
3828 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003829
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003830 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003831
Makoto Onuki8e777332017-03-28 11:25:47 -07003832 void handleUidChanged(int uid, int procState, long procStateSeq) {
3833 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
3834 try {
3835 synchronized (mUidRulesFirstLock) {
3836 // We received a uid state change callback, add it to the history so that it
3837 // will be useful for debugging.
3838 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
3839 // Now update the network policy rules as per the updated uid state.
3840 updateUidStateUL(uid, procState);
3841 // Updating the network rules is done, so notify AMS about this.
3842 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
3843 }
3844 } finally {
3845 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3846 }
3847 }
3848
3849 void handleUidGone(int uid) {
3850 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
3851 try {
3852 synchronized (mUidRulesFirstLock) {
3853 removeUidStateUL(uid);
3854 }
3855 } finally {
3856 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3857 }
3858 }
3859
Felipe Leme57e3d312016-08-23 14:42:52 -07003860 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3861 final PackageManager pm = mContext.getPackageManager();
3862 final String[] packages = pm.getPackagesForUid(uid);
3863 if (packages != null) {
3864 final int userId = UserHandle.getUserId(uid);
3865 for (String packageName : packages) {
3866 final Intent intent =
3867 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3868 intent.setPackage(packageName);
3869 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3870 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3871 }
3872 }
3873 }
3874
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003875 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003876 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003877 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003878 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003879 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003880 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003881 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003882 }
3883 }
3884
3885 private void removeInterfaceQuota(String iface) {
3886 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003887 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003888 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003889 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003890 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003891 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003892 }
3893 }
3894
Felipe Leme70c57c22016-03-29 10:45:13 -07003895 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3896 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003897 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003898 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003899 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003900 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3901 } catch (RemoteException e) {
3902 // ignored; service lives in system_server
3903 }
3904 }
3905
3906 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3907 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3908 try {
3909 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3910 } catch (IllegalStateException e) {
3911 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003912 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003913 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003914 }
3915 }
3916
Felipe Lemebc853dd2016-09-08 13:26:55 -07003917 private static final int CHAIN_TOGGLE_NONE = 0;
3918 private static final int CHAIN_TOGGLE_ENABLE = 1;
3919 private static final int CHAIN_TOGGLE_DISABLE = 2;
3920 @Retention(RetentionPolicy.SOURCE)
3921 @IntDef(flag = false, value = {
3922 CHAIN_TOGGLE_NONE,
3923 CHAIN_TOGGLE_ENABLE,
3924 CHAIN_TOGGLE_DISABLE
3925 })
3926 public @interface ChainToggleType {
3927 }
3928
3929 /**
3930 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
3931 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
3932 *
3933 * @param chain firewall chain.
3934 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
3935 * @param toggle whether the chain should be enabled, disabled, or not changed.
3936 */
3937 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
3938 @ChainToggleType int toggle) {
3939 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
3940 }
3941
Amith Yamasani15e472352015-04-24 19:06:07 -07003942 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003943 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3944 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3945 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003946 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003947 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003948 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003949 int size = uidRules.size();
3950 int[] uids = new int[size];
3951 int[] rules = new int[size];
3952 for(int index = size - 1; index >= 0; --index) {
3953 uids[index] = uidRules.keyAt(index);
3954 rules[index] = uidRules.valueAt(index);
3955 }
3956 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003957 } catch (IllegalStateException e) {
3958 Log.wtf(TAG, "problem setting firewall uid rules", e);
3959 } catch (RemoteException e) {
3960 // ignored; service lives in system_server
3961 }
3962 }
3963
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003964 /**
3965 * Add or remove a uid to the firewall blacklist for all network ifaces.
3966 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003967 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003968 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3969 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3970 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003971 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003972 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003973 if (chain == FIREWALL_CHAIN_DOZABLE) {
3974 mUidFirewallDozableRules.put(uid, rule);
3975 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3976 mUidFirewallStandbyRules.put(uid, rule);
3977 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3978 mUidFirewallPowerSaveRules.put(uid, rule);
3979 }
3980
3981 try {
3982 mNetworkManager.setFirewallUidRule(chain, uid, rule);
3983 } catch (IllegalStateException e) {
3984 Log.wtf(TAG, "problem setting firewall uid rules", e);
3985 } catch (RemoteException e) {
3986 // ignored; service lives in system_server
3987 }
3988 } finally {
3989 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003990 }
3991 }
3992
3993 /**
3994 * Add or remove a uid to the firewall blacklist for all network ifaces.
3995 */
Felipe Lemef0823852016-06-08 13:43:08 -07003996 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003997 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3998 mFirewallChainStates.get(chain) == enable) {
3999 // All is the same, nothing to do.
4000 return;
4001 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004002 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004003 try {
4004 mNetworkManager.setFirewallChainEnabled(chain, enable);
4005 } catch (IllegalStateException e) {
4006 Log.wtf(TAG, "problem enable firewall chain", e);
4007 } catch (RemoteException e) {
4008 // ignored; service lives in system_server
4009 }
4010 }
4011
Felipe Leme03e95e22016-09-09 09:25:31 -07004012 /**
4013 * Resets all firewall rules associated with an UID.
4014 */
4015 private void resetUidFirewallRules(int uid) {
4016 try {
4017 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4018 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4019 mNetworkManager
4020 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4021 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4022 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4023 } catch (IllegalStateException e) {
4024 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4025 } catch (RemoteException e) {
4026 // ignored; service lives in system_server
4027 }
4028 }
4029
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004030 private long getTotalBytes(NetworkTemplate template, long start, long end) {
4031 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004032 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004033 } catch (RuntimeException e) {
4034 Slog.w(TAG, "problem reading network stats: " + e);
4035 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004036 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004037 // ignored; service lives in system_server
4038 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004039 }
4040 }
4041
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004042 private boolean isBandwidthControlEnabled() {
4043 final long token = Binder.clearCallingIdentity();
4044 try {
4045 return mNetworkManager.isBandwidthControlEnabled();
4046 } catch (RemoteException e) {
4047 // ignored; service lives in system_server
4048 return false;
4049 } finally {
4050 Binder.restoreCallingIdentity(token);
4051 }
4052 }
4053
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004054 /**
4055 * Try refreshing {@link #mTime} when stale.
4056 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07004057 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004058 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004059 mTime.forceRefresh();
4060 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004061 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004062
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004063 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004064 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
4065 }
4066
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004067 private static Intent buildAllowBackgroundDataIntent() {
4068 return new Intent(ACTION_ALLOW_BACKGROUND);
4069 }
4070
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004071 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4072 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
4073 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4074 return intent;
4075 }
4076
Wei Liu546cb772016-07-21 16:19:01 -07004077 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004078 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004079 intent.setComponent(ComponentName.unflattenFromString(
4080 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004081 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4082 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4083 return intent;
4084 }
4085
Wei Liu546cb772016-07-21 16:19:01 -07004086 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004087 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004088 intent.setComponent(ComponentName.unflattenFromString(
4089 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004090 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4091 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4092 return intent;
4093 }
4094
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004095 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004096 public void addIdleHandler(IdleHandler handler) {
4097 mHandler.getLooper().getQueue().addIdleHandler(handler);
4098 }
4099
jackqdyulei29c82ab2017-03-10 14:09:16 -08004100 @VisibleForTesting
4101 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4102 mRestrictBackgroundPowerState = result;
4103
4104 boolean restrictBackground = result.batterySaverEnabled;
4105 boolean shouldInvokeRestrictBackground;
4106 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4107 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4108
4109 if (result.globalBatterySaverEnabled) {
4110 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4111 // turn it on.
4112 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4113 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4114 localRestrictBgChangedInBsm = false;
4115 } else {
4116 // Try to restore the restrictBackground if it doesn't change in bsm
4117 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4118 restrictBackground = mRestrictBackgroundBeforeBsm;
4119 }
4120
4121 if (shouldInvokeRestrictBackground) {
4122 setRestrictBackground(restrictBackground);
4123 }
4124
4125 // Change it at last so setRestrictBackground() won't affect this variable
4126 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4127 }
4128
Jeff Sharkey1b861272011-05-22 00:34:52 -07004129 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4130 final int size = source.size();
4131 for (int i = 0; i < size; i++) {
4132 target.put(source.keyAt(i), true);
4133 }
4134 }
4135
Stuart Scottf1fb3972015-04-02 18:00:02 -07004136 @Override
4137 public void factoryReset(String subscriber) {
4138 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4139
Stuart Scotte3e314d2015-04-20 14:07:45 -07004140 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4141 return;
4142 }
4143
Stuart Scottf1fb3972015-04-02 18:00:02 -07004144 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004145 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004146 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4147 for (NetworkPolicy policy : policies) {
4148 if (policy.template.equals(template)) {
4149 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4150 policy.inferred = false;
4151 policy.clearSnooze();
4152 }
4153 }
4154 setNetworkPolicies(policies);
4155
4156 // Turn restrict background data off
4157 setRestrictBackground(false);
4158
Stuart Scotte3e314d2015-04-20 14:07:45 -07004159 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4160 // Remove app's "restrict background data" flag
4161 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4162 setUidPolicy(uid, POLICY_NONE);
4163 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004164 }
4165 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004166
Felipe Lemed17fda42016-04-29 11:12:45 -07004167 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4168
4169 @Override
4170 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004171 synchronized (mUidRulesFirstLock) {
4172 boolean changed = removeUserStateUL(userId, false);
4173 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004174 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004175 synchronized (mNetworkPoliciesSecondLock) {
4176 writePolicyAL();
4177 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004178 }
4179 }
4180 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004181
4182 /**
4183 * @return true if the given uid is restricted from doing networking on metered networks.
4184 */
4185 @Override
4186 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4187 final int uidRules;
4188 final boolean isBackgroundRestricted;
4189 synchronized (mUidRulesFirstLock) {
4190 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4191 isBackgroundRestricted = mRestrictBackground;
4192 }
4193 return isBackgroundRestricted
4194 && !hasRule(uidRules, RULE_ALLOW_METERED)
4195 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4196 }
4197
4198 /**
4199 * @return true if networking is blocked on the given interface for the given uid according
4200 * to current networking policies.
4201 */
4202 @Override
4203 public boolean isUidNetworkingBlocked(int uid, String ifname) {
4204 final int uidRules;
4205 final boolean isBackgroundRestricted;
4206 final boolean isNetworkMetered;
4207 synchronized (mUidRulesFirstLock) {
4208 uidRules = mUidRules.get(uid, RULE_NONE);
4209 isBackgroundRestricted = mRestrictBackground;
4210 synchronized (mNetworkPoliciesSecondLock) {
4211 isNetworkMetered = mMeteredIfaces.contains(ifname);
4212 }
4213 }
4214 if (hasRule(uidRules, RULE_REJECT_ALL)) {
4215 if (LOGV) logUidStatus(uid, "blocked by power restrictions");
4216 return true;
4217 }
4218 if (!isNetworkMetered) {
4219 if (LOGV) logUidStatus(uid, "allowed on unmetered network");
4220 return false;
4221 }
4222 if (hasRule(uidRules, RULE_REJECT_METERED)) {
4223 if (LOGV) logUidStatus(uid, "blacklisted on metered network");
4224 return true;
4225 }
4226 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4227 if (LOGV) logUidStatus(uid, "whitelisted on metered network");
4228 return false;
4229 }
4230 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4231 if (LOGV) logUidStatus(uid, "temporary whitelisted on metered network");
4232 return false;
4233 }
4234 if (isBackgroundRestricted) {
4235 if (LOGV) logUidStatus(uid, "blocked when background is restricted");
4236 return true;
4237 }
4238 if (LOGV) logUidStatus(uid, "allowed by default");
4239 return false;
4240 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004241
4242 @Override
4243 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4244 synchronized (mUidRulesFirstLock) {
4245 if (added) {
4246 mPowerSaveTempWhitelistAppIds.put(appId, true);
4247 } else {
4248 mPowerSaveTempWhitelistAppIds.delete(appId);
4249 }
4250 updateRulesForTempWhitelistChangeUL(appId);
4251 }
4252 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004253 }
4254
4255 private static boolean hasRule(int uidRules, int rule) {
4256 return (uidRules & rule) != 0;
4257 }
4258
4259 private static void logUidStatus(int uid, String descr) {
4260 Slog.d(TAG, String.format("uid %d is %s", uid, descr));
Felipe Lemed17fda42016-04-29 11:12:45 -07004261 }
Sudheer Shankae7361852017-03-07 11:51:46 -08004262
4263 /**
4264 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
4265 * (uid, procStateSeq) pairs.
4266 */
4267 @VisibleForTesting
4268 public static final class ProcStateSeqHistory {
4269 private static final int INVALID_UID = -1;
4270
4271 /**
4272 * Denotes maximum number of items this history can hold.
4273 */
4274 private final int mMaxCapacity;
4275 /**
4276 * Used for storing the uid information.
4277 */
4278 private final int[] mUids;
4279 /**
4280 * Used for storing the sequence numbers associated with {@link #mUids}.
4281 */
4282 private final long[] mProcStateSeqs;
4283 /**
4284 * Points to the next available slot for writing (uid, procStateSeq) pair.
4285 */
4286 private int mHistoryNext;
4287
4288 public ProcStateSeqHistory(int maxCapacity) {
4289 mMaxCapacity = maxCapacity;
4290 mUids = new int[mMaxCapacity];
4291 Arrays.fill(mUids, INVALID_UID);
4292 mProcStateSeqs = new long[mMaxCapacity];
4293 }
4294
4295 @GuardedBy("mUidRulesFirstLock")
4296 public void addProcStateSeqUL(int uid, long procStateSeq) {
4297 mUids[mHistoryNext] = uid;
4298 mProcStateSeqs[mHistoryNext] = procStateSeq;
4299 mHistoryNext = increaseNext(mHistoryNext, 1);
4300 }
4301
4302 @GuardedBy("mUidRulesFirstLock")
4303 public void dumpUL(IndentingPrintWriter fout) {
4304 if (mUids[0] == INVALID_UID) {
4305 fout.println("NONE");
4306 return;
4307 }
4308 int index = mHistoryNext;
4309 do {
4310 index = increaseNext(index, -1);
4311 if (mUids[index] == INVALID_UID) {
4312 break;
4313 }
4314 fout.println(getString(mUids[index], mProcStateSeqs[index]));
4315 } while (index != mHistoryNext);
4316 }
4317
4318 public static String getString(int uid, long procStateSeq) {
Sudheer Shankadb9aaf032017-06-19 19:05:31 -07004319 return "UID=" + uid + " Seq=" + procStateSeq;
Sudheer Shankae7361852017-03-07 11:51:46 -08004320 }
4321
4322 private int increaseNext(int next, int increment) {
4323 next += increment;
4324 if (next >= mMaxCapacity) {
4325 next = 0;
4326 } else if (next < 0) {
4327 next = mMaxCapacity - 1;
4328 }
4329 return next;
4330 }
4331 }
Chris Wren193ae6b2017-03-31 15:17:11 -04004332
4333 private class NotificationId {
4334 private final String mTag;
4335 private final int mId;
4336
4337 NotificationId(NetworkPolicy policy, int type) {
4338 mTag = buildNotificationTag(policy, type);
4339 mId = type;
4340 }
4341
4342 @Override
4343 public boolean equals(Object o) {
4344 if (this == o) return true;
4345 if (!(o instanceof NotificationId)) return false;
4346 NotificationId that = (NotificationId) o;
4347 return Objects.equals(mTag, that.mTag);
4348 }
4349
4350 @Override
4351 public int hashCode() {
4352 return Objects.hash(mTag);
4353 }
4354
4355 /**
4356 * Build unique tag that identifies an active {@link NetworkPolicy}
4357 * notification of a specific type, like {@link #TYPE_LIMIT}.
4358 */
4359 private String buildNotificationTag(NetworkPolicy policy, int type) {
4360 return TAG + ":" + policy.template.hashCode() + ":" + type;
4361 }
4362
4363 public String getTag() {
4364 return mTag;
4365 }
4366
4367 public int getId() {
4368 return mId;
4369 }
4370 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004371}