blob: 442c067bc6b116d13eca18bf47162542628b990d [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.DeviceIdleController;
186import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700187import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700188import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800189import com.android.server.SystemConfig;
jackqdyulei455e90a2017-02-09 15:29:16 -0800190import com.android.server.power.BatterySaverPolicy.ServiceType;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600191
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600192import libcore.io.IoUtils;
193
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700194import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700195
196import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700197import org.xmlpull.v1.XmlSerializer;
198
199import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700200import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700201import java.io.FileInputStream;
202import java.io.FileNotFoundException;
203import java.io.FileOutputStream;
204import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700205import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700206import java.lang.annotation.Retention;
207import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100208import java.nio.charset.StandardCharsets;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600209import java.time.ZoneId;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600210import java.time.ZonedDateTime;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700211import java.util.ArrayList;
212import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700213import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600214import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400215import java.util.Objects;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800216import java.util.concurrent.CountDownLatch;
217import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700218
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700219/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700220 * Service that maintains low-level network policy rules, using
221 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700222 * <p>
223 * Derives active rules by combining a given policy with other system status,
224 * and delivers to listeners, such as {@link ConnectivityManager}, for
225 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700226 *
227 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000228 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700229 * <ul>
230 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
231 * rules).
232 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
233 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000234 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
235 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700236 * </ul>
237 *
238 * <p>
239 * As such, methods that require synchronization have the following prefixes:
240 * <ul>
241 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
242 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000243 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
244 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700245 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700246 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700247public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800248 static final String TAG = "NetworkPolicy";
Hugo Benichi5d2f2b52017-04-07 08:53:25 +0900249 private static final boolean LOGD = false;
250 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700251
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700252 private static final int VERSION_INIT = 1;
253 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700254 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800255 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800256 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800257 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700258 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700259 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700260 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700261 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600262 private static final int VERSION_ADDED_CYCLE = 11;
263 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700264
Sudheer Shankae7361852017-03-07 11:51:46 -0800265 /**
266 * Max items written to {@link #ProcStateSeqHistory}.
267 */
268 @VisibleForTesting
269 public static final int MAX_PROC_STATE_SEQ_HISTORY =
270 ActivityManager.isLowRamDeviceStatic() ? 50 : 200;
271
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800272 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400273 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800274 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400275 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800276 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400277 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700278
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700279 private static final String TAG_POLICY_LIST = "policy-list";
280 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600281 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700282 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700283 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800284 private static final String TAG_WHITELIST = "whitelist";
285 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800286 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700287
288 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700289 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700290 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
291 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700292 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600293 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
294 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
295 private static final String ATTR_CYCLE_START = "cycleStart";
296 private static final String ATTR_CYCLE_END = "cycleEnd";
297 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700298 private static final String ATTR_WARNING_BYTES = "warningBytes";
299 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700300 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800301 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
302 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800303 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700304 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700305 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700306 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700307 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600308 private static final String ATTR_SUB_ID = "subId";
309 private static final String ATTR_TITLE = "title";
310 private static final String ATTR_SUMMARY = "summary";
311 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
312 private static final String ATTR_USAGE_BYTES = "usageBytes";
313 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700314
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800315 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800316 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800317 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800318 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700319
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700320 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
321
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700322 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700323 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800324 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800325 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700326 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700327 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
328 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700329 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700330 private static final int MSG_SET_FIREWALL_RULES = 14;
Felipe Leme03e95e22016-09-09 09:25:31 -0700331 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700332
Makoto Onuki8e777332017-03-28 11:25:47 -0700333 private static final int UID_MSG_STATE_CHANGED = 100;
334 private static final int UID_MSG_GONE = 101;
335
Jeff Sharkey75279902011-05-24 18:39:45 -0700336 private final Context mContext;
337 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700338 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700339 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700340 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700341 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700342 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700343 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700344
345 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700346 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700347 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700348 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800349 @GuardedBy("mUidRulesFirstLock")
350 private PowerSaveState mRestrictBackgroundPowerState;
351
352 // Store the status of restrict background before turning on battery saver.
353 // Used to restore mRestrictBackground when battery saver is turned off.
354 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700355
Felipe Lemef0823852016-06-08 13:43:08 -0700356 // See main javadoc for instructions on how to use these locks.
357 final Object mUidRulesFirstLock = new Object();
358 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700359
Felipe Lemef0823852016-06-08 13:43:08 -0700360 @GuardedBy("allLocks") volatile boolean mSystemReady;
361
Felipe Lemef0823852016-06-08 13:43:08 -0700362 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
363 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
364 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800365 // Store whether user flipped restrict background in battery saver mode
366 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700367
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700368 private final boolean mSuppressDefaultPolicy;
369
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700370 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800371 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700372 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800373 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700374
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600375 /** Defined subscription plans. */
376 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
377
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700378 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700379 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700380 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700381 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700382
Felipe Lemef0823852016-06-08 13:43:08 -0700383 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700384 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700385 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700386 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700387 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800388 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700389
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700390 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700391 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700392 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
393
Jeff Sharkey32566012014-12-02 18:30:14 -0800394 /**
395 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700396 * in power save mode, except device idle (doze) still applies.
397 * TODO: An int array might be sufficient
398 */
Felipe Lemef0823852016-06-08 13:43:08 -0700399 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700400 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
401
402 /**
403 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800404 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700405 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800406 */
Felipe Lemef0823852016-06-08 13:43:08 -0700407 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700408 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700409
Felipe Lemef0823852016-06-08 13:43:08 -0700410 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700411 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
412
Felipe Lemeb85a6372016-01-14 16:16:16 -0800413 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800414 * UIDs that have been initially white-listed by system to avoid restricted background.
415 */
Felipe Lemef0823852016-06-08 13:43:08 -0700416 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800417 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
418 new SparseBooleanArray();
419
420 /**
421 * UIDs that have been initially white-listed by system to avoid restricted background,
422 * but later revoked by user.
423 */
Felipe Lemef0823852016-06-08 13:43:08 -0700424 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800425 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
426 new SparseBooleanArray();
427
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700428 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700429 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800430 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700431 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700432 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800433 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700434
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700435 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700436 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400437 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700438
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700439 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700440 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800441 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700442
Jeff Sharkey32566012014-12-02 18:30:14 -0800443 private final RemoteCallbackList<INetworkPolicyListener>
444 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700445
Dianne Hackborn497175b2014-07-01 12:56:08 -0700446 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700447 @VisibleForTesting
448 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700449
450 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700451
Felipe Lemef0823852016-06-08 13:43:08 -0700452 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700453 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700454
Svet Ganov16a16892015-04-16 10:32:04 -0700455 private final AppOpsManager mAppOps;
456
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800457 private final IPackageManager mIPm;
458
Sudheer Shankae7361852017-03-07 11:51:46 -0800459 private ActivityManagerInternal mActivityManagerInternal;
460
461 /**
462 * This is used for debugging purposes. Whenever the IUidObserver.onUidStateChanged is called,
463 * the uid and procStateSeq will be written to this and will be printed as part of dump.
464 */
465 @VisibleForTesting
466 public ProcStateSeqHistory mObservedHistory
467 = new ProcStateSeqHistory(MAX_PROC_STATE_SEQ_HISTORY);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800468
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700469 // TODO: keep whitelist of system-critical services that should never have
470 // rules enforced, such as system, phone, and radio UIDs.
471
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700472 // TODO: migrate notifications to SystemUI
473
Jeff Sharkey75279902011-05-24 18:39:45 -0700474 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700475 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
476 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700477 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
478 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700479 }
480
481 private static File getSystemDir() {
482 return new File(Environment.getDataDirectory(), "system");
483 }
484
485 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700486 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700487 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700488 mContext = checkNotNull(context, "missing context");
489 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700490 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700491 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700492 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700493 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700494 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700495 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700496 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700497 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700498
Amith Yamasani450a16b2013-09-18 16:28:50 -0700499 HandlerThread thread = new HandlerThread(TAG);
500 thread.start();
501 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700502
Makoto Onuki8e777332017-03-28 11:25:47 -0700503 // We create another thread for the UID events, which are more time-critical.
504 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
505 /*allowIo=*/ false);
506 mUidEventThread.start();
507 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
508
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700509 mSuppressDefaultPolicy = suppressDefaultPolicy;
510
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700511 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700512
513 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800514
Felipe Lemed17fda42016-04-29 11:12:45 -0700515 // Expose private service for system components to use.
516 LocalServices.addService(NetworkPolicyManagerInternal.class,
517 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700518 }
519
520 public void bindConnectivityManager(IConnectivityManager connManager) {
521 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700522 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700523
Jeff Sharkey497e4432011-06-14 17:27:29 -0700524 public void bindNotificationManager(INotificationManager notifManager) {
525 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
526 }
527
Felipe Lemef0823852016-06-08 13:43:08 -0700528 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700529 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700530 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
531 mPowerSaveWhitelistExceptIdleAppIds.clear();
532 if (whitelist != null) {
533 for (int uid : whitelist) {
534 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
535 }
536 }
537 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700538 mPowerSaveWhitelistAppIds.clear();
539 if (whitelist != null) {
540 for (int uid : whitelist) {
541 mPowerSaveWhitelistAppIds.put(uid, true);
542 }
543 }
544 } catch (RemoteException e) {
545 }
546 }
547
Felipe Lemea9505cc2016-02-26 10:28:41 -0800548 /**
549 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
550 * revoke the whitelist.
551 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700552 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800553 */
Felipe Lemef0823852016-06-08 13:43:08 -0700554 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800555 final List<UserInfo> users = mUserManager.getUsers();
556 final int numberUsers = users.size();
557
Felipe Lemea110eec2016-04-29 09:58:06 -0700558 boolean changed = false;
559 for (int i = 0; i < numberUsers; i++) {
560 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700561 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700562 }
563 return changed;
564 }
565
Felipe Lemef0823852016-06-08 13:43:08 -0700566 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700567 final SystemConfig sysConfig = SystemConfig.getInstance();
568 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800569 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
570 boolean changed = false;
571 for (int i = 0; i < allowDataUsage.size(); i++) {
572 final String pkg = allowDataUsage.valueAt(i);
573 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700574 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
575 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800576 final ApplicationInfo app;
577 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700578 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800579 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700580 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
581 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800582 continue;
583 }
584 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700585 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
586 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800587 continue;
588 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700589 final int uid = UserHandle.getUid(userId, app.uid);
590 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
591 if (LOGD)
592 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
593 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800594 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700595 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700596 if (LOGD)
597 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
598 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700599 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700600 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800601 }
602 }
603 return changed;
604 }
605
Felipe Lemef0823852016-06-08 13:43:08 -0700606 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700607 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700608 // Clear the states of the current whitelist
609 final int N = mPowerSaveTempWhitelistAppIds.size();
610 for (int i = 0; i < N; i++) {
611 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
612 }
613 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700614 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700615 if (whitelist != null) {
616 for (int uid : whitelist) {
617 mPowerSaveTempWhitelistAppIds.put(uid, true);
618 }
619 }
620 } catch (RemoteException e) {
621 }
622 }
623
Amith Yamasani06f08062015-06-12 13:23:33 -0700624 /**
625 * Remove unnecessary entries in the temp whitelist
626 */
Felipe Lemef0823852016-06-08 13:43:08 -0700627 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700628 final int N = mPowerSaveTempWhitelistAppIds.size();
629 for (int i = N - 1; i >= 0; i--) {
630 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
631 mPowerSaveTempWhitelistAppIds.removeAt(i);
632 }
633 }
634 }
635
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800636 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700637 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800638 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700639 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800640 // Boost thread's priority during system server init
641 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700642 if (!isBandwidthControlEnabled()) {
643 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
644 return;
645 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700646
Felipe Leme873a83a2016-09-07 11:34:10 -0700647 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700648
Felipe Leme873a83a2016-09-07 11:34:10 -0700649 synchronized (mUidRulesFirstLock) {
650 synchronized (mNetworkPoliciesSecondLock) {
651 updatePowerSaveWhitelistUL();
652 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
653 mPowerManagerInternal.registerLowPowerModeObserver(
654 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800655 @Override
656 public int getServiceType() {
657 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700658 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800659
660 @Override
661 public void onLowPowerModeChanged(PowerSaveState result) {
662 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800663 if (LOGD) {
664 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
665 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800666 synchronized (mUidRulesFirstLock) {
667 if (mRestrictPower != enabled) {
668 mRestrictPower = enabled;
669 updateRulesForRestrictPowerUL();
670 }
671 }
672 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800673 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800674 mRestrictPower = mPowerManagerInternal.getLowPowerState(
675 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700676
677 mSystemReady = true;
678
679 // read policy from disk
680 readPolicyAL();
681
jackqdyulei29c82ab2017-03-10 14:09:16 -0800682 // Update the restrictBackground if battery saver is turned on
683 mRestrictBackgroundBeforeBsm = mRestrictBackground;
684 mRestrictBackgroundPowerState = mPowerManagerInternal
685 .getLowPowerState(ServiceType.DATA_SAVER);
686 final boolean localRestrictBackground =
687 mRestrictBackgroundPowerState.batterySaverEnabled;
688 if (localRestrictBackground && localRestrictBackground != mRestrictBackground) {
689 mRestrictBackground = localRestrictBackground;
690 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
691 mRestrictBackground ? 1 : 0, 0).sendToTarget();
692 }
693 mPowerManagerInternal.registerLowPowerModeObserver(
694 new PowerManagerInternal.LowPowerModeListener() {
695 @Override
696 public int getServiceType() {
697 return ServiceType.DATA_SAVER;
698 }
699
700 @Override
701 public void onLowPowerModeChanged(PowerSaveState result) {
702 synchronized (mUidRulesFirstLock) {
703 updateRestrictBackgroundByLowPowerModeUL(result);
704 }
705 }
706 });
707
Felipe Leme873a83a2016-09-07 11:34:10 -0700708 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
709 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700710 }
Felipe Lemef0823852016-06-08 13:43:08 -0700711
Felipe Leme873a83a2016-09-07 11:34:10 -0700712 setRestrictBackgroundUL(mRestrictBackground);
713 updateRulesForGlobalChangeAL(false);
714 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700715 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800716 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700717
Sudheer Shankae7361852017-03-07 11:51:46 -0800718 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700719 try {
720 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000721 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800722 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700723 mNetworkManager.registerObserver(mAlertObserver);
724 } catch (RemoteException e) {
725 // ignored; both services live in system_server
726 }
727
728 // listen for changes to power save whitelist
729 final IntentFilter whitelistFilter = new IntentFilter(
730 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
731 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
732
733 DeviceIdleController.LocalService deviceIdleService
734 = LocalServices.getService(DeviceIdleController.LocalService.class);
735 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
736
737 // watch for network interfaces to be claimed
738 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
739 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
740
741 // listen for package changes to update policy
742 final IntentFilter packageFilter = new IntentFilter();
743 packageFilter.addAction(ACTION_PACKAGE_ADDED);
744 packageFilter.addDataScheme("package");
745 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
746
747 // listen for UID changes to update policy
748 mContext.registerReceiver(
749 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
750
751 // listen for user changes to update policy
752 final IntentFilter userFilter = new IntentFilter();
753 userFilter.addAction(ACTION_USER_ADDED);
754 userFilter.addAction(ACTION_USER_REMOVED);
755 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
756
757 // listen for stats update events
758 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
759 mContext.registerReceiver(
760 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
761
762 // listen for restrict background changes from notifications
763 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
764 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
765
766 // listen for snooze warning from notifications
767 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
768 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
769 MANAGE_NETWORK_POLICY, mHandler);
770
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600771 // listen for configured wifi networks to be loaded
772 final IntentFilter wifiFilter =
773 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
774 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700775
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700776 // listen for carrier config changes to update data cycle information
777 final IntentFilter carrierConfigFilter = new IntentFilter(
778 ACTION_CARRIER_CONFIG_CHANGED);
779 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
780
Felipe Leme873a83a2016-09-07 11:34:10 -0700781 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800782 // tell systemReady() that the service has been initialized
783 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700784 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800785 // Restore the default priority after init is done
786 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700787 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700788 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700789 }
790
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800791 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
792 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
793 mHandler.post(() -> initService(initCompleteSignal));
794 return initCompleteSignal;
795 }
796
797 public void systemReady(CountDownLatch initCompleteSignal) {
798 // wait for initService to complete
799 try {
800 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
801 throw new IllegalStateException("Service " + TAG +" init timeout");
802 }
803 } catch (InterruptedException e) {
804 Thread.currentThread().interrupt();
805 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
806 }
807 }
808
Sudheer Shankac9d94072017-02-22 22:13:55 +0000809 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700810 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700811 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
812 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700813 }
814
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700815 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700816 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700817 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700818
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700819 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700820 }
821
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700822 @Override public void onUidIdle(int uid, boolean disabled) {
823 }
824
825 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700826 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700827 };
828
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700829 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700830 @Override
831 public void onReceive(Context context, Intent intent) {
832 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700833 synchronized (mUidRulesFirstLock) {
834 updatePowerSaveWhitelistUL();
835 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700836 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700837 }
838 }
839 };
840
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700841 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
842 @Override
843 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700844 synchronized (mUidRulesFirstLock) {
845 updatePowerSaveTempWhitelistUL();
846 updateRulesForTempWhitelistChangeUL();
847 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700848 }
849 }
850 };
851
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700852 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700853 @Override
854 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700855 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700856
857 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700858 final int uid = intent.getIntExtra(EXTRA_UID, -1);
859 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700860
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700861 if (ACTION_PACKAGE_ADDED.equals(action)) {
862 // update rules for UID, since it might be subject to
863 // global background data policy
864 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700865 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700866 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700867 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700868 }
869 }
870 };
871
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700872 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700873 @Override
874 public void onReceive(Context context, Intent intent) {
875 // on background handler thread, and UID_REMOVED is protected
876
877 final int uid = intent.getIntExtra(EXTRA_UID, -1);
878 if (uid == -1) return;
879
880 // remove any policy and update rules to clean up
881 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700882 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700883 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700884 synchronized (mNetworkPoliciesSecondLock) {
885 writePolicyAL();
886 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700887 }
888 }
889 };
890
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700891 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700892 @Override
893 public void onReceive(Context context, Intent intent) {
894 // on background handler thread, and USER_ADDED and USER_REMOVED
895 // broadcasts are protected
896
897 final String action = intent.getAction();
898 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
899 if (userId == -1) return;
900
Amith Yamasani15e472352015-04-24 19:06:07 -0700901 switch (action) {
902 case ACTION_USER_REMOVED:
903 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700904 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800905 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700906 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700907 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700908 if (action == ACTION_USER_ADDED) {
909 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700910 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700911 }
912 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700913 synchronized (mNetworkPoliciesSecondLock) {
914 updateRulesForGlobalChangeAL(true);
915 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700916 }
917 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700918 }
919 }
920 };
921
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700922 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700923 * Receiver that watches for {@link INetworkStatsService} updates, which we
924 * use to check against {@link NetworkPolicy#warningBytes}.
925 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700926 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700927 @Override
928 public void onReceive(Context context, Intent intent) {
929 // on background handler thread, and verified
930 // READ_NETWORK_USAGE_HISTORY permission above.
931
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800932 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700933 synchronized (mNetworkPoliciesSecondLock) {
934 updateNetworkEnabledNL();
935 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700936 }
937 }
938 };
939
940 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700941 * Receiver that watches for {@link Notification} control of
942 * {@link #mRestrictBackground}.
943 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700944 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700945 @Override
946 public void onReceive(Context context, Intent intent) {
947 // on background handler thread, and verified MANAGE_NETWORK_POLICY
948 // permission above.
949
950 setRestrictBackground(false);
951 }
952 };
953
954 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800955 * Receiver that watches for {@link Notification} control of
956 * {@link NetworkPolicy#lastWarningSnooze}.
957 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700958 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800959 @Override
960 public void onReceive(Context context, Intent intent) {
961 // on background handler thread, and verified MANAGE_NETWORK_POLICY
962 // permission above.
963
964 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
965 performSnooze(template, TYPE_WARNING);
966 }
967 };
968
969 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600970 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
971 * we can perform upgrade logic.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700972 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600973 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700974 @Override
975 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900976 synchronized (mUidRulesFirstLock) {
977 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600978 upgradeWifiMeteredOverrideAL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700979 }
980 }
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600981 // Only need to perform upgrade logic once
982 mContext.unregisterReceiver(this);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700983 }
984 };
985
986 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700987 * Observer that watches for {@link INetworkManagementService} alerts.
988 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700989 final private INetworkManagementEventObserver mAlertObserver
990 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700991 @Override
992 public void limitReached(String limitName, String iface) {
993 // only someone like NMS should be calling us
994 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
995
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800996 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
997 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700998 }
999 }
1000 };
1001
1002 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001003 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1004 * to show visible notifications as needed.
1005 */
Felipe Lemef0823852016-06-08 13:43:08 -07001006 void updateNotificationsNL() {
1007 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001008
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001009 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001010 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001011 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001012
1013 // TODO: when switching to kernel notifications, compute next future
1014 // cycle boundary to recompute notifications.
1015
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001016 // examine stats for each active policy
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001017 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1018 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001019 // ignore policies that aren't relevant to user
1020 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001021 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001022
Jeff Sharkey53313d72017-07-13 16:47:32 -06001023 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1024 .cycleIterator(policy).next();
1025 final long start = cycle.first.toInstant().toEpochMilli();
1026 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001027 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001028
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001029 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001030 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001031 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1032 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001033 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001034 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001035 }
1036
Jeff Sharkey497e4432011-06-14 17:27:29 -07001037 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001038 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001039
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001040 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001041 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001042 }
1043 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001044 }
1045
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001046 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001047 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001048 final NotificationId notificationId = beforeNotifs.valueAt(i);
1049 if (!mActiveNotifs.contains(notificationId)) {
1050 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001051 }
1052 }
1053 }
1054
1055 /**
1056 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001057 * current device state, such as when
1058 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1059 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001060 */
1061 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001062 if (template.isMatchRuleMobile()) {
1063 final TelephonyManager tele = TelephonyManager.from(mContext);
1064 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001065
Jeff Sharkey32566012014-12-02 18:30:14 -08001066 // Mobile template is relevant when any active subscriber matches
1067 final int[] subIds = sub.getActiveSubscriptionIdList();
1068 for (int subId : subIds) {
1069 final String subscriberId = tele.getSubscriberId(subId);
1070 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001071 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001072 if (template.matches(probeIdent)) {
1073 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001074 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001075 }
1076 return false;
1077 } else {
1078 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001079 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001080 }
1081
1082 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001083 * Notify that given {@link NetworkTemplate} is over
1084 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1085 */
Felipe Lemef0823852016-06-08 13:43:08 -07001086 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001087 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001088 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001089 mOverLimitNotified.add(template);
1090 }
1091 }
1092
Felipe Lemef0823852016-06-08 13:43:08 -07001093 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001094 mOverLimitNotified.remove(template);
1095 }
1096
1097 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001098 * Show notification for combined {@link NetworkPolicy} and specific type,
1099 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1100 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001101 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001102 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001103 final Notification.Builder builder =
1104 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001105 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001106 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001107 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001108 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001109
1110 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001111 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001112 switch (type) {
1113 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001114 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001115 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001116
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001117 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001118 builder.setTicker(title);
1119 builder.setContentTitle(title);
1120 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001121 builder.setDefaults(Notification.DEFAULT_ALL);
Julia Reynoldsbad42972017-04-25 13:52:49 -04001122 builder.setChannelId(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001123
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001124 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1125 builder.setDeleteIntent(PendingIntent.getBroadcast(
1126 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1127
Wei Liu546cb772016-07-21 16:19:01 -07001128 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001129 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001130 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1131
Jeff Sharkey497e4432011-06-14 17:27:29 -07001132 break;
1133 }
1134 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001135 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001136
1137 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001138 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001139 switch (policy.template.getMatchRule()) {
1140 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001141 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001142 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001143 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001144 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001145 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001146 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001147 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001148 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001149 case MATCH_WIFI:
1150 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001151 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001152 break;
1153 default:
1154 title = null;
1155 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001156 }
1157
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001158 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001159 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001160 builder.setTicker(title);
1161 builder.setContentTitle(title);
1162 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001163
Wei Liu546cb772016-07-21 16:19:01 -07001164 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001165 builder.setContentIntent(PendingIntent.getActivity(
1166 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1167 break;
1168 }
1169 case TYPE_LIMIT_SNOOZED: {
1170 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001171 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001172 Formatter.formatFileSize(mContext, overBytes));
1173
1174 final CharSequence title;
1175 switch (policy.template.getMatchRule()) {
1176 case MATCH_MOBILE_3G_LOWER:
1177 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1178 break;
1179 case MATCH_MOBILE_4G:
1180 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1181 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001182 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001183 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1184 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001185 case MATCH_WIFI:
1186 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1187 break;
1188 default:
1189 title = null;
1190 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001191 }
1192
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001193 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001194 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001195 builder.setTicker(title);
1196 builder.setContentTitle(title);
1197 builder.setContentText(body);
1198
Wei Liu546cb772016-07-21 16:19:01 -07001199 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001200 builder.setContentIntent(PendingIntent.getActivity(
1201 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001202 break;
1203 }
1204 }
1205
1206 // TODO: move to NotificationManager once we can mock it
1207 try {
1208 final String packageName = mContext.getPackageName();
Chris Wren193ae6b2017-03-31 15:17:11 -04001209 if (!TextUtils.isEmpty(body)) {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001210 builder.setStyle(new Notification.BigTextStyle()
1211 .bigText(body));
1212 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001213 mNotifManager.enqueueNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001214 packageName, packageName, notificationId.getTag(), notificationId.getId(),
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001215 builder.build(), UserHandle.USER_ALL);
Chris Wren193ae6b2017-03-31 15:17:11 -04001216 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001217 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001218 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001219 }
1220 }
1221
Chris Wren193ae6b2017-03-31 15:17:11 -04001222 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001223 // TODO: move to NotificationManager once we can mock it
1224 try {
1225 final String packageName = mContext.getPackageName();
1226 mNotifManager.cancelNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001227 packageName, notificationId.getTag(), notificationId.getId(),
1228 UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001229 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001230 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001231 }
1232 }
1233
1234 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001235 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001236 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001237 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001238 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001239 @Override
1240 public void onReceive(Context context, Intent intent) {
1241 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1242 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001243
1244 maybeRefreshTrustedTime();
Hugo Benichi446c9c92017-04-10 09:41:10 +09001245 synchronized (mUidRulesFirstLock) {
1246 synchronized (mNetworkPoliciesSecondLock) {
1247 ensureActiveMobilePolicyAL();
1248 normalizePoliciesNL();
1249 updateNetworkEnabledNL();
1250 updateNetworkRulesNL();
1251 updateNotificationsNL();
1252 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001253 }
1254 }
1255 };
1256
1257 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001258 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1259 * if necessary.
1260 *
1261 * @param subId that has its associated NetworkPolicy updated if necessary
1262 * @return if any policies were updated
1263 */
1264 private boolean maybeUpdateMobilePolicyCycleNL(int subId) {
1265 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleNL()");
1266 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1267
1268 if (config == null) {
1269 return false;
1270 }
1271
1272 boolean policyUpdated = false;
1273 final String subscriberId = TelephonyManager.from(mContext).getSubscriberId(subId);
1274
1275 // find and update the mobile NetworkPolicy for this subscriber id
1276 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1277 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1278 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1279 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1280 if (template.matches(probeIdent)) {
1281 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1282
1283 // only update the policy if the user didn't change any of the defaults.
1284 if (!policy.inferred) {
1285 // TODO: inferred could be split, so that if a user changes their data limit or
1286 // warning, it doesn't prevent their cycle date from being updated.
1287 if (LOGD) Slog.v(TAG, "Didn't update NetworkPolicy because policy.inferred");
1288 continue;
1289 }
1290
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001291 final int currentCycleDay;
1292 if (policy.cycleRule.isMonthly()) {
1293 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1294 } else {
1295 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1296 }
1297
1298 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001299 final long warningBytes = getWarningBytesFromCarrierConfig(config,
1300 policy.warningBytes);
1301 final long limitBytes = getLimitBytesFromCarrierConfig(config,
1302 policy.limitBytes);
1303
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001304 if (currentCycleDay == cycleDay &&
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001305 policy.warningBytes == warningBytes &&
1306 policy.limitBytes == limitBytes) {
1307 continue;
1308 }
1309
1310 policyUpdated = true;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001311 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001312 policy.warningBytes = warningBytes;
1313 policy.limitBytes = limitBytes;
1314
1315 if (LOGD) {
1316 Slog.d(TAG, "Updated NetworkPolicy " + policy + " which matches subscriber "
1317 + NetworkIdentity.scrubSubscriberId(subscriberId)
1318 + " from CarrierConfigManager");
1319 }
1320 }
1321 }
1322
1323 return policyUpdated;
1324 }
1325
1326 /**
1327 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1328 *
1329 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1330 * to do so, it returns the fallback value.
1331 *
1332 * @param config The CarrierConfig to read the value from.
1333 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1334 * @return cycleDay to use in the mobile NetworkPolicy.
1335 */
1336 @VisibleForTesting
1337 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1338 int fallbackCycleDay) {
1339 if (config == null) {
1340 return fallbackCycleDay;
1341 }
1342 int cycleDay =
1343 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1344 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1345 return fallbackCycleDay;
1346 }
1347 // validate cycleDay value
1348 final Calendar cal = Calendar.getInstance();
1349 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1350 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1351 Slog.e(TAG, "Invalid date in "
1352 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1353 return fallbackCycleDay;
1354 }
1355 return cycleDay;
1356 }
1357
1358 /**
1359 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1360 *
1361 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1362 * to do so, it returns the fallback value.
1363 *
1364 * @param config The CarrierConfig to read the value from.
1365 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1366 * @return warningBytes to use in the mobile NetworkPolicy.
1367 */
1368 @VisibleForTesting
1369 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1370 long fallbackWarningBytes) {
1371 if (config == null) {
1372 return fallbackWarningBytes;
1373 }
1374 long warningBytes =
1375 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1376
1377 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1378 return WARNING_DISABLED;
1379 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1380 return getPlatformDefaultWarningBytes();
1381 } else if (warningBytes < 0) {
1382 Slog.e(TAG, "Invalid value in "
1383 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1384 + "non-negative value but got: " + warningBytes);
1385 return fallbackWarningBytes;
1386 }
1387
1388 return warningBytes;
1389 }
1390
1391 /**
1392 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1393 *
1394 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1395 * to do so, it returns the fallback value.
1396 *
1397 * @param config The CarrierConfig to read the value from.
1398 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1399 * @return limitBytes to use in the mobile NetworkPolicy.
1400 */
1401 @VisibleForTesting
1402 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1403 long fallbackLimitBytes) {
1404 if (config == null) {
1405 return fallbackLimitBytes;
1406 }
1407 long limitBytes =
1408 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1409
1410 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1411 return LIMIT_DISABLED;
1412 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1413 return getPlatformDefaultLimitBytes();
1414 } else if (limitBytes < 0) {
1415 Slog.e(TAG, "Invalid value in "
1416 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1417 + "non-negative value but got: " + limitBytes);
1418 return fallbackLimitBytes;
1419 }
1420 return limitBytes;
1421 }
1422
1423 /**
1424 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1425 */
1426 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1427 @Override
1428 public void onReceive(Context context, Intent intent) {
1429 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1430 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1431
1432 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1433 return;
1434 }
1435 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
1436 final TelephonyManager tele = TelephonyManager.from(mContext);
1437 final String subscriberId = tele.getSubscriberId(subId);
1438
1439 maybeRefreshTrustedTime();
1440 synchronized (mUidRulesFirstLock) {
1441 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001442 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001443 if (added) return;
1444 final boolean updated = maybeUpdateMobilePolicyCycleNL(subId);
1445 if (!updated) return;
1446 // update network and notification rules, as the data cycle changed and it's
1447 // possible that we should be triggering warnings/limits now
1448 handleNetworkPoliciesUpdateAL(true);
1449 }
1450 }
1451 }
1452 };
1453
1454 /**
1455 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1456 * one has been updated.
1457 *
1458 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1459 * update.
1460 */
1461 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1462 if (shouldNormalizePolicies) {
1463 normalizePoliciesNL();
1464 }
1465 updateNetworkEnabledNL();
1466 updateNetworkRulesNL();
1467 updateNotificationsNL();
1468 writePolicyAL();
1469 }
1470
1471 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001472 * Proactively control network data connections when they exceed
1473 * {@link NetworkPolicy#limitBytes}.
1474 */
Felipe Lemef0823852016-06-08 13:43:08 -07001475 void updateNetworkEnabledNL() {
1476 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001477
1478 // TODO: reset any policy-disabled networks when any policy is removed
1479 // completely, which is currently rare case.
1480
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001481 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1482 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001483 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001484 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001485 setNetworkTemplateEnabled(policy.template, true);
1486 continue;
1487 }
1488
Jeff Sharkey53313d72017-07-13 16:47:32 -06001489 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1490 .cycleIterator(policy).next();
1491 final long start = cycle.first.toInstant().toEpochMilli();
1492 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001493 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001494
1495 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001496 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1497 && policy.lastLimitSnooze < start;
1498 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001499
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001500 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001501 }
1502 }
1503
1504 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001505 * Proactively disable networks that match the given
1506 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001507 */
1508 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001509 // TODO: reach into ConnectivityManager to proactively disable bringing
1510 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001511
1512 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1513 // If mobile data usage hits the limit or if the user resumes the data, we need to
1514 // notify telephony.
1515 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1516 final TelephonyManager tm = TelephonyManager.from(mContext);
1517
1518 final int[] subIds = sm.getActiveSubscriptionIdList();
1519 for (int subId : subIds) {
1520 final String subscriberId = tm.getSubscriberId(subId);
1521 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1522 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1523 // Template is matched when subscriber id matches.
1524 if (template.matches(probeIdent)) {
1525 tm.setPolicyDataEnabled(enabled, subId);
1526 }
1527 }
1528 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001529 }
1530
1531 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001532 * Examine all connected {@link NetworkState}, looking for
1533 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1534 * remaining quota based on usage cycle and historical stats.
1535 */
Felipe Lemef0823852016-06-08 13:43:08 -07001536 void updateNetworkRulesNL() {
1537 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001538
1539 final NetworkState[] states;
1540 try {
1541 states = mConnManager.getAllNetworkState();
1542 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001543 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001544 return;
1545 }
1546
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001547 // First, generate identities of all connected networks so we can
1548 // quickly compare them against all defined policies below.
1549 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001550 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001551 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001552 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001553 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001554
1555 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001556 if (baseIface != null) {
1557 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001558 }
1559
1560 // Stacked interfaces are considered to have same identity as
1561 // their parent network.
1562 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1563 for (LinkProperties stackedLink : stackedLinks) {
1564 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001565 if (stackedIface != null) {
1566 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001567 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001568 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001569 }
1570 }
1571
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001572 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001573 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001574 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001575 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001576 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001577
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001578 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001579 for (int j = connIdents.size() - 1; j >= 0; j--) {
1580 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1581 if (policy.template.matches(ident.second)) {
1582 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001583 }
1584 }
1585
1586 if (ifaceList.size() > 0) {
1587 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001588 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001589 }
1590 }
1591
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001592 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001593 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001594
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001595 // apply each policy that we found ifaces for; compute remaining data
1596 // based on current cycle and historical stats, and push to kernel.
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001597 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1598 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1599 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001600
Jeff Sharkey53313d72017-07-13 16:47:32 -06001601 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1602 .cycleIterator(policy).next();
1603 final long start = cycle.first.toInstant().toEpochMilli();
1604 final long end = cycle.second.toInstant().toEpochMilli();
1605 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001606
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001607 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001608 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001609 }
1610
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001611 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001612 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001613 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001614 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001615 if (!hasLimit) {
1616 // metered network, but no policy limit; we still need to
1617 // restrict apps, so push really high quota.
1618 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001619 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001620 // snoozing past quota, but we still need to restrict apps,
1621 // so push really high quota.
1622 quotaBytes = Long.MAX_VALUE;
1623 } else {
1624 // remaining "quota" bytes are based on total usage in
1625 // current cycle. kernel doesn't like 0-byte rules, so we
1626 // set 1-byte quota and disable the radio later.
1627 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1628 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001629
1630 if (ifaces.length > 1) {
1631 // TODO: switch to shared quota once NMS supports
1632 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001633 }
1634
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001635 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001636 // long quotaBytes split up into two ints to fit in message
1637 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1638 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1639 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001640 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001641 }
1642 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001643
1644 // keep track of lowest warning or limit of active policies
1645 if (hasWarning && policy.warningBytes < lowestRule) {
1646 lowestRule = policy.warningBytes;
1647 }
1648 if (hasLimit && policy.limitBytes < lowestRule) {
1649 lowestRule = policy.limitBytes;
1650 }
1651 }
1652
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001653 for (int i = connIfaces.size()-1; i >= 0; i--) {
1654 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001655 // long quotaBytes split up into two ints to fit in message
1656 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1657 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1658 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001659 newMeteredIfaces.add(iface);
1660 }
1661
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001662 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001663
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001664 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001665 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1666 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001667 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001668 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1669 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001670 }
1671 }
1672 mMeteredIfaces = newMeteredIfaces;
1673
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001674 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001675 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001676 }
1677
1678 /**
1679 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1680 * have at least a default mobile policy defined.
1681 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001682 private void ensureActiveMobilePolicyAL() {
1683 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001684 if (mSuppressDefaultPolicy) return;
1685
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001686 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001687 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001688
Jeff Sharkey32566012014-12-02 18:30:14 -08001689 final int[] subIds = sub.getActiveSubscriptionIdList();
1690 for (int subId : subIds) {
1691 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001692 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001693 }
1694 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001695
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001696 /**
1697 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1698 * have at least a default mobile policy defined.
1699 *
1700 * @param subId to build a default policy for
1701 * @param subscriberId that we check for an existing policy
1702 * @return true if a mobile network policy was added, or false one already existed.
1703 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001704 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001705 // Poke around to see if we already have a policy
1706 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001707 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001708 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1709 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1710 if (template.matches(probeIdent)) {
1711 if (LOGD) {
1712 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1713 + NetworkIdentity.scrubSubscriberId(subscriberId));
1714 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001715 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001716 }
1717 }
1718
Jeff Sharkey32566012014-12-02 18:30:14 -08001719 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1720 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001721 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001722 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001723 return true;
1724 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001725
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001726 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001727 final int dataWarningConfig = mContext.getResources().getInteger(
1728 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001729 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001730 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001731 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001732 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001733 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001734 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001735
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001736 private long getPlatformDefaultLimitBytes() {
1737 return LIMIT_DISABLED;
1738 }
1739
1740 @VisibleForTesting
1741 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
1742 PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1743
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001744 final int cycleDay = getCycleDayFromCarrierConfig(config,
1745 ZonedDateTime.now().getDayOfMonth());
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001746 final long warningBytes = getWarningBytesFromCarrierConfig(config,
1747 getPlatformDefaultWarningBytes());
1748 final long limitBytes = getLimitBytesFromCarrierConfig(config,
1749 getPlatformDefaultLimitBytes());
1750
Jeff Sharkey32566012014-12-02 18:30:14 -08001751 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001752 final RecurrenceRule cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1753 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001754 warningBytes, limitBytes, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1755 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001756 }
1757
Felipe Lemef0823852016-06-08 13:43:08 -07001758 private void readPolicyAL() {
1759 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001760
1761 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001762 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001763 mSubscriptionPlans.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001764 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001765
1766 FileInputStream fis = null;
1767 try {
1768 fis = mPolicyFile.openRead();
1769 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001770 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001771
Felipe Leme46b451f2016-08-19 08:46:17 -07001772 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1773 // to skip UIDs that were explicitly blacklisted.
1774 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1775
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001776 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001777 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001778 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001779 while ((type = in.next()) != END_DOCUMENT) {
1780 final String tag = in.getName();
1781 if (type == START_TAG) {
1782 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001783 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001784 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001785 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1786 mRestrictBackground = readBooleanAttribute(
1787 in, ATTR_RESTRICT_BACKGROUND);
1788 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001789 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001790 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001791 if (mRestrictBackground != oldValue) {
1792 // Some early services may have read the default value,
1793 // so notify them that it's changed
1794 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1795 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1796 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001797
1798 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1799 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1800 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001801 final String networkId;
1802 if (version >= VERSION_ADDED_NETWORK_ID) {
1803 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1804 } else {
1805 networkId = null;
1806 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001807 final RecurrenceRule cycleRule;
1808 if (version >= VERSION_ADDED_CYCLE) {
1809 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1810 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1811 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1812 cycleRule = new RecurrenceRule(
1813 RecurrenceRule.convertZonedDateTime(start),
1814 RecurrenceRule.convertZonedDateTime(end),
1815 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001816 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001817 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1818 final String cycleTimezone;
1819 if (version >= VERSION_ADDED_TIMEZONE) {
1820 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1821 } else {
1822 cycleTimezone = "UTC";
1823 }
1824 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001825 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001826 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1827 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001828 final long lastLimitSnooze;
1829 if (version >= VERSION_SPLIT_SNOOZE) {
1830 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1831 } else if (version >= VERSION_ADDED_SNOOZE) {
1832 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001833 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001834 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001835 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001836 final boolean metered;
1837 if (version >= VERSION_ADDED_METERED) {
1838 metered = readBooleanAttribute(in, ATTR_METERED);
1839 } else {
1840 switch (networkTemplate) {
1841 case MATCH_MOBILE_3G_LOWER:
1842 case MATCH_MOBILE_4G:
1843 case MATCH_MOBILE_ALL:
1844 metered = true;
1845 break;
1846 default:
1847 metered = false;
1848 }
1849 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001850 final long lastWarningSnooze;
1851 if (version >= VERSION_SPLIT_SNOOZE) {
1852 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1853 } else {
1854 lastWarningSnooze = SNOOZE_NEVER;
1855 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001856 final boolean inferred;
1857 if (version >= VERSION_ADDED_INFERRED) {
1858 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1859 } else {
1860 inferred = false;
1861 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001862
Jeff Sharkey32566012014-12-02 18:30:14 -08001863 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1864 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001865 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001866 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
1867 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001868 lastLimitSnooze, metered, inferred));
1869 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001870
1871 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
1872 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1873 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1874 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1875 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
1876 RecurrenceRule.convertZonedDateTime(start),
1877 RecurrenceRule.convertZonedDateTime(end),
1878 RecurrenceRule.convertPeriod(period));
1879 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
1880 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
1881
1882 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
1883 SubscriptionPlan.BYTES_UNKNOWN);
1884 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
1885 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
1886 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
1887 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
1888 builder.setDataLimit(limitBytes, limitBehavior);
1889 }
1890
1891 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
1892 SubscriptionPlan.BYTES_UNKNOWN);
1893 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
1894 SubscriptionPlan.TIME_UNKNOWN);
1895 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
1896 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
1897 builder.setDataUsage(usageBytes, usageTime);
1898 }
1899
1900 final int subId = readIntAttribute(in, ATTR_SUB_ID);
1901 final SubscriptionPlan plan = builder.build();
1902 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
1903 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
1904
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001905 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001906 final int uid = readIntAttribute(in, ATTR_UID);
1907 final int policy = readIntAttribute(in, ATTR_POLICY);
1908
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001909 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001910 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001911 } else {
1912 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1913 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001914 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001915 final int appId = readIntAttribute(in, ATTR_APP_ID);
1916 final int policy = readIntAttribute(in, ATTR_POLICY);
1917
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001918 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001919 // app policy is deprecated so this is only used in pre system user split.
1920 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001921 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001922 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001923 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001924 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001925 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001926 } else if (TAG_WHITELIST.equals(tag)) {
1927 insideWhitelist = true;
1928 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1929 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001930 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001931 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1932 final int uid = readIntAttribute(in, ATTR_UID);
1933 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001934 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001935 } else if (type == END_TAG) {
1936 if (TAG_WHITELIST.equals(tag)) {
1937 insideWhitelist = false;
1938 }
1939
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001940 }
1941 }
1942
Felipe Leme46b451f2016-08-19 08:46:17 -07001943 final int size = whitelistedRestrictBackground.size();
1944 for (int i = 0; i < size; i++) {
1945 final int uid = whitelistedRestrictBackground.keyAt(i);
1946 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1947 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1948 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1949 + " because its policy is " + uidPoliciesToString(policy));
1950 continue;
1951 }
1952 if (UserHandle.isApp(uid)) {
1953 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1954 if (LOGV)
1955 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1956 setUidPolicyUncheckedUL(uid, newPolicy, false);
1957 } else {
1958 Slog.w(TAG, "unable to update policy on UID " + uid);
1959 }
1960 }
1961
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001962 } catch (FileNotFoundException e) {
1963 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001964 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001965 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001966 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001967 } finally {
1968 IoUtils.closeQuietly(fis);
1969 }
1970 }
1971
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001972 /**
1973 * Upgrade legacy background data flags, notifying listeners of one last
1974 * change to always-true.
1975 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001976 private void upgradeDefaultBackgroundDataUL() {
1977 // This method is only called when we're unable to find the network policy flag, which
1978 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001979
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001980 // Seed from the default value configured for this device.
1981 mRestrictBackground = Settings.Global.getInt(
1982 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
1983
1984 // NOTE: We used to read the legacy setting here :
1985 //
1986 // final int legacyFlagValue = Settings.Secure.getInt(
1987 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
1988 //
1989 // This is no longer necessary because we will never upgrade directly from Gingerbread
1990 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
1991 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001992 }
1993
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001994 /**
1995 * Perform upgrade step of moving any user-defined meterness overrides over
1996 * into {@link WifiConfiguration}.
1997 */
1998 private void upgradeWifiMeteredOverrideAL() {
1999 boolean modified = false;
2000 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2001 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2002 for (int i = 0; i < mNetworkPolicy.size(); ) {
2003 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2004 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2005 && !policy.inferred) {
2006 mNetworkPolicy.removeAt(i);
2007 modified = true;
2008
2009 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2010 for (WifiConfiguration config : configs) {
2011 if (Objects.equals(resolveNetworkId(config), networkId)) {
2012 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2013 config.meteredOverride = policy.metered
2014 ? WifiConfiguration.METERED_OVERRIDE_METERED
2015 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2016 wm.updateNetwork(config);
2017 }
2018 }
2019 } else {
2020 i++;
2021 }
2022 }
2023 if (modified) {
2024 writePolicyAL();
2025 }
2026 }
2027
Felipe Lemef0823852016-06-08 13:43:08 -07002028 void writePolicyAL() {
2029 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002030
2031 FileOutputStream fos = null;
2032 try {
2033 fos = mPolicyFile.startWrite();
2034
2035 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002036 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002037 out.startDocument(null, true);
2038
2039 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002040 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002041 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002042
2043 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002044 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2045 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002046 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002047 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002048
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002049 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002050 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2051 final String subscriberId = template.getSubscriberId();
2052 if (subscriberId != null) {
2053 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002054 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002055 final String networkId = template.getNetworkId();
2056 if (networkId != null) {
2057 out.attribute(null, ATTR_NETWORK_ID, networkId);
2058 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002059 writeStringAttribute(out, ATTR_CYCLE_START,
2060 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2061 writeStringAttribute(out, ATTR_CYCLE_END,
2062 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2063 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2064 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002065 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2066 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002067 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2068 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002069 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002070 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002071 out.endTag(null, TAG_NETWORK_POLICY);
2072 }
2073
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002074 // write all known subscription plans
2075 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2076 final int subId = mSubscriptionPlans.keyAt(i);
2077 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2078 if (ArrayUtils.isEmpty(plans)) continue;
2079
2080 for (SubscriptionPlan plan : plans) {
2081 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2082 writeIntAttribute(out, ATTR_SUB_ID, subId);
2083 final RecurrenceRule cycleRule = plan.getCycleRule();
2084 writeStringAttribute(out, ATTR_CYCLE_START,
2085 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2086 writeStringAttribute(out, ATTR_CYCLE_END,
2087 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2088 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2089 RecurrenceRule.convertPeriod(cycleRule.period));
2090 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2091 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2092 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2093 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2094 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2095 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2096 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2097 }
2098 }
2099
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002100 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002101 for (int i = 0; i < mUidPolicy.size(); i++) {
2102 final int uid = mUidPolicy.keyAt(i);
2103 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002104
Jeff Sharkey497e4432011-06-14 17:27:29 -07002105 // skip writing empty policies
2106 if (policy == POLICY_NONE) continue;
2107
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002108 out.startTag(null, TAG_UID_POLICY);
2109 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002110 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002111 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002112 }
2113
2114 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002115
2116 // write all whitelists
2117 out.startTag(null, TAG_WHITELIST);
2118
Felipe Lemea9505cc2016-02-26 10:28:41 -08002119 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002120 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002121 for (int i = 0; i < size; i++) {
2122 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2123 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2124 writeIntAttribute(out, ATTR_UID, uid);
2125 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2126 }
2127
Felipe Lemeb85a6372016-01-14 16:16:16 -08002128 out.endTag(null, TAG_WHITELIST);
2129
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002130 out.endDocument();
2131
2132 mPolicyFile.finishWrite(fos);
2133 } catch (IOException e) {
2134 if (fos != null) {
2135 mPolicyFile.failWrite(fos);
2136 }
2137 }
2138 }
2139
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002140 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002141 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002142 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002143
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002144 if (!UserHandle.isApp(uid)) {
2145 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002146 }
Felipe Lemef0823852016-06-08 13:43:08 -07002147 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002148 final long token = Binder.clearCallingIdentity();
2149 try {
2150 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2151 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002152 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002153 }
2154 } finally {
2155 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002156 }
2157 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002158 }
2159
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002160 @Override
2161 public void addUidPolicy(int uid, int policy) {
2162 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002163
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002164 if (!UserHandle.isApp(uid)) {
2165 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2166 }
2167
Felipe Lemef0823852016-06-08 13:43:08 -07002168 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002169 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2170 policy |= oldPolicy;
2171 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002172 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002173 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002174 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002175 }
2176
2177 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002178 public void removeUidPolicy(int uid, int policy) {
2179 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2180
2181 if (!UserHandle.isApp(uid)) {
2182 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2183 }
2184
Felipe Lemef0823852016-06-08 13:43:08 -07002185 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002186 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2187 policy = oldPolicy & ~policy;
2188 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002189 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002190 }
2191 }
2192 }
2193
Felipe Lemef0823852016-06-08 13:43:08 -07002194 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2195 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002196
Felipe Leme57e3d312016-08-23 14:42:52 -07002197 final boolean notifyApp;
2198 if (!isUidValidForWhitelistRules(uid)) {
2199 notifyApp = false;
2200 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002201 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2202 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2203 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2204 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002205 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2206 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002207 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2208 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2209 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2210 if (LOGD)
2211 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2212 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2213 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002214 notifyApp = wasBlocked != isBlocked;
2215 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002216 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2217 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002218 }
2219
Felipe Lemef0823852016-06-08 13:43:08 -07002220 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002221 if (policy == POLICY_NONE) {
2222 mUidPolicy.delete(uid);
2223 } else {
2224 mUidPolicy.put(uid, policy);
2225 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002226
2227 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002228 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002229 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002230 synchronized (mNetworkPoliciesSecondLock) {
2231 writePolicyAL();
2232 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002233 }
2234 }
2235
2236 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002237 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002238 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2239
Felipe Lemef0823852016-06-08 13:43:08 -07002240 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002241 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002242 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002243 }
2244
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002245 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002246 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002247 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2248
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002249 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002250 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002251 for (int i = 0; i < mUidPolicy.size(); i++) {
2252 final int uid = mUidPolicy.keyAt(i);
2253 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002254 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2255 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002256 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002257 }
2258 }
2259 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002260 return uids;
2261 }
2262
2263 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002264 * Removes any persistable state associated with given {@link UserHandle}, persisting
2265 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002266 */
Felipe Lemef0823852016-06-08 13:43:08 -07002267 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002268
Felipe Lemef0823852016-06-08 13:43:08 -07002269 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07002270 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002271
Felipe Lemea110eec2016-04-29 09:58:06 -07002272 // Remove entries from revoked default restricted background UID whitelist
2273 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2274 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2275 if (UserHandle.getUserId(uid) == userId) {
2276 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002277 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002278 }
2279 }
2280
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002281 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002282 int[] uids = new int[0];
2283 for (int i = 0; i < mUidPolicy.size(); i++) {
2284 final int uid = mUidPolicy.keyAt(i);
2285 if (UserHandle.getUserId(uid) == userId) {
2286 uids = appendInt(uids, uid);
2287 }
2288 }
2289
2290 if (uids.length > 0) {
2291 for (int uid : uids) {
2292 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002293 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002294 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002295 }
Felipe Lemef0823852016-06-08 13:43:08 -07002296 synchronized (mNetworkPoliciesSecondLock) {
2297 updateRulesForGlobalChangeAL(true);
2298 if (writePolicy && changed) {
2299 writePolicyAL();
2300 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002301 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002302 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002303 }
2304
2305 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002306 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002307 // TODO: create permission for observing network policy
2308 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002309 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002310 }
2311
2312 @Override
2313 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002314 // TODO: create permission for observing network policy
2315 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002316 mListeners.unregister(listener);
2317 }
2318
Jeff Sharkey1b861272011-05-22 00:34:52 -07002319 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002320 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002321 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2322
Felipe Leme6a05eee2016-02-19 14:43:51 -08002323 final long token = Binder.clearCallingIdentity();
2324 try {
2325 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002326 synchronized (mUidRulesFirstLock) {
2327 synchronized (mNetworkPoliciesSecondLock) {
2328 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002329 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002330 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002331 }
2332 } finally {
2333 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002334 }
2335 }
2336
Hugo Benichi446c9c92017-04-10 09:41:10 +09002337 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002338 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002339 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2340 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002341 }
2342
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002343 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002344 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002345 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002346 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002347 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2348 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2349 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002350 } catch (SecurityException e) {
2351 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002352
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002353 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2354 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2355 return new NetworkPolicy[0];
2356 }
Svet Ganov16a16892015-04-16 10:32:04 -07002357 }
2358
Felipe Lemef0823852016-06-08 13:43:08 -07002359 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002360 final int size = mNetworkPolicy.size();
2361 final NetworkPolicy[] policies = new NetworkPolicy[size];
2362 for (int i = 0; i < size; i++) {
2363 policies[i] = mNetworkPolicy.valueAt(i);
2364 }
2365 return policies;
2366 }
2367 }
2368
Felipe Lemef0823852016-06-08 13:43:08 -07002369 private void normalizePoliciesNL() {
2370 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002371 }
2372
Felipe Lemef0823852016-06-08 13:43:08 -07002373 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002374 final TelephonyManager tele = TelephonyManager.from(mContext);
2375 final String[] merged = tele.getMergedSubscriberIds();
2376
2377 mNetworkPolicy.clear();
2378 for (NetworkPolicy policy : policies) {
2379 // When two normalized templates conflict, prefer the most
2380 // restrictive policy
2381 policy.template = NetworkTemplate.normalize(policy.template, merged);
2382 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2383 if (existing == null || existing.compareTo(policy) > 0) {
2384 if (existing != null) {
2385 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2386 }
2387 mNetworkPolicy.put(policy.template, policy);
2388 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002389 }
2390 }
2391
2392 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002393 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002394 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002395
2396 final long token = Binder.clearCallingIdentity();
2397 try {
2398 performSnooze(template, TYPE_LIMIT);
2399 } finally {
2400 Binder.restoreCallingIdentity(token);
2401 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002402 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002403
Dianne Hackborn497175b2014-07-01 12:56:08 -07002404 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002405 maybeRefreshTrustedTime();
2406 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002407 synchronized (mUidRulesFirstLock) {
2408 synchronized (mNetworkPoliciesSecondLock) {
2409 // find and snooze local policy that matches
2410 final NetworkPolicy policy = mNetworkPolicy.get(template);
2411 if (policy == null) {
2412 throw new IllegalArgumentException("unable to find policy for " + template);
2413 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002414
Felipe Lemef0823852016-06-08 13:43:08 -07002415 switch (type) {
2416 case TYPE_WARNING:
2417 policy.lastWarningSnooze = currentTime;
2418 break;
2419 case TYPE_LIMIT:
2420 policy.lastLimitSnooze = currentTime;
2421 break;
2422 default:
2423 throw new IllegalArgumentException("unexpected type");
2424 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002425
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002426 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002427 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002428 }
2429 }
2430
2431 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002432 public void onTetheringChanged(String iface, boolean tethering) {
2433 // No need to enforce permission because setRestrictBackground() will do it.
2434 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002435 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002436 if (mRestrictBackground && tethering) {
2437 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2438 setRestrictBackground(false);
2439 }
2440 }
2441 }
2442
2443 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002444 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002445 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002446 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002447 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2448 final long token = Binder.clearCallingIdentity();
2449 try {
2450 maybeRefreshTrustedTime();
2451 synchronized (mUidRulesFirstLock) {
2452 if (restrictBackground == mRestrictBackground) {
2453 // Ideally, UI should never allow this scenario...
2454 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2455 return;
2456 }
2457 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002458 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002459
2460 } finally {
2461 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002462 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002463
Felipe Leme29e72ea2016-09-08 13:26:55 -07002464 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2465 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002466 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002467 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002468 }
2469 }
2470
Felipe Lemef0823852016-06-08 13:43:08 -07002471 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002472 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002473 final boolean oldRestrictBackground = mRestrictBackground;
2474 mRestrictBackground = restrictBackground;
2475 // Must whitelist foreground apps before turning data saver mode on.
2476 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2477 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002478 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002479 try {
2480 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2481 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2482 mRestrictBackground = oldRestrictBackground;
2483 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002484 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002485 return;
2486 }
2487 } catch (RemoteException e) {
2488 // ignored; service lives in system_server
2489 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002490
2491 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2492 mRestrictBackgroundChangedInBsm = true;
2493 }
Felipe Lemef0823852016-06-08 13:43:08 -07002494 synchronized (mNetworkPoliciesSecondLock) {
2495 updateNotificationsNL();
2496 writePolicyAL();
2497 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002498 }
2499
Felipe Lemeb85a6372016-01-14 16:16:16 -08002500 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002501 public int getRestrictBackgroundByCaller() {
2502 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2503 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002504
Felipe Lemef0823852016-06-08 13:43:08 -07002505 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002506 // Must clear identity because getUidPolicy() is restricted to system.
2507 final long token = Binder.clearCallingIdentity();
2508 final int policy;
2509 try {
2510 policy = getUidPolicy(uid);
2511 } finally {
2512 Binder.restoreCallingIdentity(token);
2513 }
2514 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2515 // App is blacklisted.
2516 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2517 }
Felipe Leme1b103232016-01-22 09:44:57 -08002518 if (!mRestrictBackground) {
2519 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2520 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002521 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002522 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2523 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2524 }
2525 }
2526
2527 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002528 public boolean getRestrictBackground() {
2529 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2530
Felipe Lemef0823852016-06-08 13:43:08 -07002531 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002532 return mRestrictBackground;
2533 }
2534 }
2535
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002536 @Override
2537 public void setDeviceIdleMode(boolean enabled) {
2538 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002539 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2540 try {
2541 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002542 if (mDeviceIdleMode == enabled) {
2543 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002544 }
Felipe Lemeea014392016-09-06 13:59:54 -07002545 mDeviceIdleMode = enabled;
2546 if (mSystemReady) {
2547 // Device idle change means we need to rebuild rules for all
2548 // known apps, so do a global refresh.
2549 updateRulesForRestrictPowerUL();
2550 }
2551 }
2552 if (enabled) {
2553 EventLogTags.writeDeviceIdleOnPhase("net");
2554 } else {
2555 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002556 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002557 } finally {
2558 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002559 }
2560 }
2561
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002562 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002563 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2564 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002565 final long token = Binder.clearCallingIdentity();
2566 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002567 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2568 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2569 for (WifiConfiguration config : configs) {
2570 if (Objects.equals(resolveNetworkId(config), networkId)) {
2571 config.meteredOverride = meteredOverride;
2572 wm.updateNetwork(config);
2573 }
2574 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002575 } finally {
2576 Binder.restoreCallingIdentity(token);
2577 }
2578 }
2579
Jeff Sharkey46645002011-07-27 21:11:21 -07002580 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002581 @Deprecated
2582 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2583 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2584 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2585 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002586 }
2587
Jeff Sharkey53313d72017-07-13 16:47:32 -06002588 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2589 // Verify they're not lying about package name
2590 mAppOps.checkPackage(callingUid, callingPackage);
2591
2592 // Verify they have phone permission from user
2593 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
2594 if (mAppOps.checkOp(AppOpsManager.OP_READ_PHONE_STATE, callingUid,
2595 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2596 throw new SecurityException(
2597 "Calling package " + callingPackage + " does not hold " + READ_PHONE_STATE);
2598 }
2599
2600 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002601 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002602 final long token = Binder.clearCallingIdentity();
2603 try {
2604 si = mContext.getSystemService(SubscriptionManager.class)
2605 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002606 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002607 } finally {
2608 Binder.restoreCallingIdentity(token);
2609 }
2610
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002611 // First check: is caller the CarrierService?
Jeff Sharkey53313d72017-07-13 16:47:32 -06002612 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002613 return;
2614 }
2615
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002616 // Second check: has the CarrierService delegated access?
2617 if (config != null) {
2618 final String overridePackage = config
2619 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2620 if (!TextUtils.isEmpty(overridePackage)
2621 && Objects.equals(overridePackage, callingPackage)) {
2622 return;
2623 }
2624 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002625
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002626 // Third check: is caller the fallback/default CarrierService?
2627 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2628 if (!TextUtils.isEmpty(defaultPackage)
2629 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002630 return;
2631 }
2632
2633 throw new SecurityException("Calling package " + callingPackage
2634 + " has no access to subscription plans for " + subId);
2635 }
2636
2637 @Override
2638 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2639 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2640
Jeff Sharkey53313d72017-07-13 16:47:32 -06002641 final String fake = SystemProperties.get("fw.fake_plan");
2642 if (!TextUtils.isEmpty(fake)) {
2643 final List<SubscriptionPlan> plans = new ArrayList<>();
2644 if ("month_hard".equals(fake)) {
2645 plans.add(SubscriptionPlan.Builder
2646 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2647 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002648 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2649 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2650 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2651 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2652 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002653 plans.add(SubscriptionPlan.Builder
2654 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2655 .setTitle("G-Mobile Happy")
2656 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2657 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2658 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2659 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2660 .build());
2661 plans.add(SubscriptionPlan.Builder
2662 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2663 .setTitle("G-Mobile, Charged after limit")
2664 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2665 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2666 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2667 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2668 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002669 } else if ("month_soft".equals(fake)) {
2670 plans.add(SubscriptionPlan.Builder
2671 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2672 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2673 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2674 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002675 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2676 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2677 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2678 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2679 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002680 plans.add(SubscriptionPlan.Builder
2681 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2682 .setTitle("G-Mobile, Throttled after limit")
2683 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2684 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2685 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2686 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2687 .build());
2688 plans.add(SubscriptionPlan.Builder
2689 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2690 .setTitle("G-Mobile, No data connection after limit")
2691 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2692 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2693 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2694 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2695 .build());
2696
Jeff Sharkey53313d72017-07-13 16:47:32 -06002697 } else if ("month_none".equals(fake)) {
2698 plans.add(SubscriptionPlan.Builder
2699 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2700 .setTitle("G-Mobile")
2701 .build());
2702 } else if ("prepaid".equals(fake)) {
2703 plans.add(SubscriptionPlan.Builder
2704 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2705 ZonedDateTime.now().plusDays(10))
2706 .setTitle("G-Mobile")
2707 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2708 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2709 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2710 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2711 .build());
2712 } else if ("prepaid_crazy".equals(fake)) {
2713 plans.add(SubscriptionPlan.Builder
2714 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2715 ZonedDateTime.now().plusDays(10))
2716 .setTitle("G-Mobile Anytime")
2717 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2718 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2719 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2720 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2721 .build());
2722 plans.add(SubscriptionPlan.Builder
2723 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2724 ZonedDateTime.now().plusDays(20))
2725 .setTitle("G-Mobile Nickel Nights")
2726 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002727 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2728 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002729 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2730 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2731 .build());
2732 plans.add(SubscriptionPlan.Builder
2733 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2734 ZonedDateTime.now().plusDays(20))
2735 .setTitle("G-Mobile Bonus 3G")
2736 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002737 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002738 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2739 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2740 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2741 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002742 } else if ("unlimited".equals(fake)) {
2743 plans.add(SubscriptionPlan.Builder
2744 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2745 ZonedDateTime.now().plusDays(10))
2746 .setTitle("G-Mobile Awesome")
2747 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2748 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2749 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2750 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2751 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002752 }
2753 return plans.toArray(new SubscriptionPlan[plans.size()]);
2754 }
2755
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002756 synchronized (mUidRulesFirstLock) {
2757 synchronized (mNetworkPoliciesSecondLock) {
2758 return mSubscriptionPlans.get(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002759 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002760 }
2761 }
2762
2763 @Override
2764 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2765 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2766
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002767 for (SubscriptionPlan plan : plans) {
2768 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002769 }
2770
2771 final long token = Binder.clearCallingIdentity();
2772 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002773 maybeRefreshTrustedTime();
2774 synchronized (mUidRulesFirstLock) {
2775 synchronized (mNetworkPoliciesSecondLock) {
2776 mSubscriptionPlans.put(subId, plans);
2777 // TODO: update any implicit details from newly defined plans
2778 handleNetworkPoliciesUpdateAL(false);
2779 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002780 }
2781 } finally {
2782 Binder.restoreCallingIdentity(token);
2783 }
2784 }
2785
2786 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002787 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002788 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002789
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002790 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2791
Dianne Hackborn497175b2014-07-01 12:56:08 -07002792 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002793 for (String arg : args) {
2794 argSet.add(arg);
2795 }
2796
Felipe Lemef0823852016-06-08 13:43:08 -07002797 synchronized (mUidRulesFirstLock) {
2798 synchronized (mNetworkPoliciesSecondLock) {
2799 if (argSet.contains("--unsnooze")) {
2800 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2801 mNetworkPolicy.valueAt(i).clearSnooze();
2802 }
2803
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002804 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002805
2806 fout.println("Cleared snooze timestamps");
2807 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002808 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002809
Felipe Lemef0823852016-06-08 13:43:08 -07002810 fout.print("System ready: "); fout.println(mSystemReady);
2811 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2812 fout.print("Restrict power: "); fout.println(mRestrictPower);
2813 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2814 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002815 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002816 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2817 fout.println(mNetworkPolicy.valueAt(i).toString());
2818 }
2819 fout.decreaseIndent();
2820
2821 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2822
2823 fout.println("Policy for UIDs:");
2824 fout.increaseIndent();
2825 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002826 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002827 final int uid = mUidPolicy.keyAt(i);
2828 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002829 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002830 fout.print(uid);
2831 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002832 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002833 fout.println();
2834 }
2835 fout.decreaseIndent();
2836
2837 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2838 if (size > 0) {
2839 fout.println("Power save whitelist (except idle) app ids:");
2840 fout.increaseIndent();
2841 for (int i = 0; i < size; i++) {
2842 fout.print("UID=");
2843 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2844 fout.print(": ");
2845 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2846 fout.println();
2847 }
2848 fout.decreaseIndent();
2849 }
2850
2851 size = mPowerSaveWhitelistAppIds.size();
2852 if (size > 0) {
2853 fout.println("Power save whitelist app ids:");
2854 fout.increaseIndent();
2855 for (int i = 0; i < size; i++) {
2856 fout.print("UID=");
2857 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2858 fout.print(": ");
2859 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2860 fout.println();
2861 }
2862 fout.decreaseIndent();
2863 }
2864
Felipe Lemef0823852016-06-08 13:43:08 -07002865 size = mDefaultRestrictBackgroundWhitelistUids.size();
2866 if (size > 0) {
2867 fout.println("Default restrict background whitelist uids:");
2868 fout.increaseIndent();
2869 for (int i = 0; i < size; i++) {
2870 fout.print("UID=");
2871 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2872 fout.println();
2873 }
2874 fout.decreaseIndent();
2875 }
2876
2877 size = mRestrictBackgroundWhitelistRevokedUids.size();
2878 if (size > 0) {
2879 fout.println("Default restrict background whitelist uids revoked by users:");
2880 fout.increaseIndent();
2881 for (int i = 0; i < size; i++) {
2882 fout.print("UID=");
2883 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2884 fout.println();
2885 }
2886 fout.decreaseIndent();
2887 }
2888
2889 final SparseBooleanArray knownUids = new SparseBooleanArray();
2890 collectKeys(mUidState, knownUids);
2891 collectKeys(mUidRules, knownUids);
2892
2893 fout.println("Status for all known UIDs:");
2894 fout.increaseIndent();
2895 size = knownUids.size();
2896 for (int i = 0; i < size; i++) {
2897 final int uid = knownUids.keyAt(i);
2898 fout.print("UID=");
2899 fout.print(uid);
2900
2901 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2902 fout.print(" state=");
2903 fout.print(state);
2904 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2905 fout.print(" (fg)");
2906 } else {
2907 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2908 ? " (fg svc)" : " (bg)");
2909 }
2910
2911 final int uidRules = mUidRules.get(uid, RULE_NONE);
2912 fout.print(" rules=");
2913 fout.print(uidRulesToString(uidRules));
2914 fout.println();
2915 }
2916 fout.decreaseIndent();
2917
2918 fout.println("Status for just UIDs with rules:");
2919 fout.increaseIndent();
2920 size = mUidRules.size();
2921 for (int i = 0; i < size; i++) {
2922 final int uid = mUidRules.keyAt(i);
2923 fout.print("UID=");
2924 fout.print(uid);
2925 final int uidRules = mUidRules.get(uid, RULE_NONE);
2926 fout.print(" rules=");
2927 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002928 fout.println();
2929 }
2930 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08002931
2932 fout.println("Observed uid state changes:");
2933 fout.increaseIndent();
2934 mObservedHistory.dumpUL(fout);
2935 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002936 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002937 }
2938 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002939
2940 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002941 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002942 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002943 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002944 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002945 }
2946
2947 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002948 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002949 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2950
Felipe Lemef0823852016-06-08 13:43:08 -07002951 synchronized (mUidRulesFirstLock) {
2952 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002953 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002954 }
2955
Felipe Lemef0823852016-06-08 13:43:08 -07002956 private boolean isUidForegroundUL(int uid) {
2957 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002958 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2959 }
2960
Felipe Lemef0823852016-06-08 13:43:08 -07002961 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002962 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002963 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002964 }
2965
Felipe Lemef0823852016-06-08 13:43:08 -07002966 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002967 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2968 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2969 }
2970
Felipe Lemef0823852016-06-08 13:43:08 -07002971 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002972 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002973 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002974 }
2975
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002976 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002977 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002978 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2979 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002980 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002981 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002982 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2983 try {
2984 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2985 if (oldUidState != uidState) {
2986 // state changed, push updated rules
2987 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002988 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2989 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2990 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2991 if (isUidIdle(uid)) {
2992 updateRuleForAppIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002993 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002994 if (mDeviceIdleMode) {
2995 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002996 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002997 if (mRestrictPower) {
2998 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002999 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003000 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003001 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003002 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003003 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003004 } finally {
3005 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003006 }
3007 }
3008
Felipe Lemef0823852016-06-08 13:43:08 -07003009 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003010 final int index = mUidState.indexOfKey(uid);
3011 if (index >= 0) {
3012 final int oldUidState = mUidState.valueAt(index);
3013 mUidState.removeAt(index);
3014 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003015 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003016 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003017 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003018 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003019 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003020 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003021 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003022 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003023 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003024 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003025 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003026 }
3027 }
3028
Felipe Lemef28983d2016-03-25 12:18:23 -07003029 // adjust stats accounting based on foreground status
3030 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003031 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3032 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3033 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3034 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003035 try {
3036 mNetworkStats.setUidForeground(uid, uidForeground);
3037 } catch (RemoteException e) {
3038 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003039 } finally {
3040 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003041 }
3042 }
3043
Sudheer Shankac9d94072017-02-22 22:13:55 +00003044 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3045 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003046 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003047 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003048 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003049 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003050 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003051 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003052 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003053 }
3054
Felipe Lemef0823852016-06-08 13:43:08 -07003055 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003056 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3057 try {
3058 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3059 mUidFirewallPowerSaveRules);
3060 } finally {
3061 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3062 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003063 }
3064
Felipe Lemef0823852016-06-08 13:43:08 -07003065 void updateRuleForRestrictPowerUL(int uid) {
3066 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003067 }
3068
Felipe Lemef0823852016-06-08 13:43:08 -07003069 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003070 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3071 try {
3072 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3073 mUidFirewallDozableRules);
3074 } finally {
3075 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3076 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003077 }
3078
Felipe Lemef0823852016-06-08 13:43:08 -07003079 void updateRuleForDeviceIdleUL(int uid) {
3080 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003081 }
3082
Felipe Lemef28983d2016-03-25 12:18:23 -07003083 // NOTE: since both fw_dozable and fw_powersave uses the same map
3084 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003085 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003086 SparseIntArray rules) {
3087 if (enabled) {
3088 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003089 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003090 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003091 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003092 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003093 for (int ui = users.size() - 1; ui >= 0; ui--) {
3094 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003095 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3096 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3097 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3098 updateRulesForWhitelistedAppIds(uidRules,
3099 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003100 }
3101 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003102 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003103 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003104 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3105 }
3106 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003107 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
3108 } else {
3109 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003110 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003111 }
3112
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003113 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3114 final SparseBooleanArray whitelistedAppIds, int userId) {
3115 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3116 if (whitelistedAppIds.valueAt(i)) {
3117 final int appId = whitelistedAppIds.keyAt(i);
3118 final int uid = UserHandle.getUid(userId, appId);
3119 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3120 }
3121 }
3122 }
3123
3124 /**
3125 * @param deviceIdleMode if true then we don't consider
3126 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3127 * whitelisted.
3128 */
3129 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003130 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003131 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3132 || mPowerSaveWhitelistAppIds.get(appId);
3133 if (!deviceIdleMode) {
3134 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3135 }
3136 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003137 }
3138
Felipe Lemef28983d2016-03-25 12:18:23 -07003139 // NOTE: since both fw_dozable and fw_powersave uses the same map
3140 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003141 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003142 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003143 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3144 chain == FIREWALL_CHAIN_DOZABLE);
3145 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003146 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003147 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003148 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003149 }
3150 }
3151 }
3152
Felipe Lemef0823852016-06-08 13:43:08 -07003153 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003154 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3155 try {
3156 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3157 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003158
Felipe Leme873a83a2016-09-07 11:34:10 -07003159 // Fully update the app idle firewall chain.
3160 final List<UserInfo> users = mUserManager.getUsers();
3161 for (int ui = users.size() - 1; ui >= 0; ui--) {
3162 UserInfo user = users.get(ui);
3163 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3164 for (int uid : idleUids) {
3165 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3166 // quick check: if this uid doesn't have INTERNET permission, it
3167 // doesn't have network access anyway, so it is a waste to mess
3168 // with it here.
3169 if (hasInternetPermissions(uid)) {
3170 uidRules.put(uid, FIREWALL_RULE_DENY);
3171 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003172 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003173 }
3174 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003175
Felipe Lemebc853dd2016-09-08 13:26:55 -07003176 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003177 } finally {
3178 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3179 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003180 }
3181
Felipe Lemef0823852016-06-08 13:43:08 -07003182 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003183 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003184
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003185 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3186 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3187 }
3188 try {
3189 int appId = UserHandle.getAppId(uid);
3190 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3191 && !isUidForegroundOnRestrictPowerUL(uid)) {
3192 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3193 } else {
3194 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3195 }
3196 } finally {
3197 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003198 }
3199 }
3200
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003201 /**
3202 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3203 * changed.
3204 */
Felipe Lemef0823852016-06-08 13:43:08 -07003205 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003206 boolean paroled = mUsageStats.isAppIdleParoleOn();
3207 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003208 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003209
3210 int ruleCount = mUidFirewallStandbyRules.size();
3211 for (int i = 0; i < ruleCount; i++) {
3212 int uid = mUidFirewallStandbyRules.keyAt(i);
3213 int oldRules = mUidRules.get(uid);
3214 if (enableChain) {
3215 // Chain wasn't enabled before and the other power-related
3216 // chains are whitelists, so we can clear the
3217 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3218 // the effective rules result in blocking network access.
3219 oldRules &= MASK_METERED_NETWORKS;
3220 } else {
3221 // Skip if it had no restrictions to begin with
3222 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3223 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003224 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3225 if (newUidRules == RULE_NONE) {
3226 mUidRules.delete(uid);
3227 } else {
3228 mUidRules.put(uid, newUidRules);
3229 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003230 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003231 }
3232
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003233 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003234 * Update rules that might be changed by {@link #mRestrictBackground},
3235 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003236 */
Felipe Lemef0823852016-06-08 13:43:08 -07003237 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003238 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3239 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3240 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3241 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003242 try {
Felipe Leme09700462016-09-08 09:33:48 -07003243 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003244 updateRulesForRestrictPowerUL();
3245 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003246
Felipe Leme873a83a2016-09-07 11:34:10 -07003247 // If the set of restricted networks may have changed, re-evaluate those.
3248 if (restrictedNetworksChanged) {
3249 normalizePoliciesNL();
3250 updateNetworkRulesNL();
3251 }
3252 } finally {
3253 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003254 }
3255 }
3256
Felipe Leme09700462016-09-08 09:33:48 -07003257 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003258 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003259 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3260 try {
3261 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003262 updateRulesForPowerSaveUL();
3263 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3264 } finally {
3265 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3266 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003267 }
3268
Felipe Lemef0823852016-06-08 13:43:08 -07003269 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003270 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3271 try {
3272 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3273 } finally {
3274 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3275 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003276 }
3277
3278 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3279 private static final int TYPE_RESTRICT_POWER = 2;
3280 @Retention(RetentionPolicy.SOURCE)
3281 @IntDef(flag = false, value = {
3282 TYPE_RESTRICT_BACKGROUND,
3283 TYPE_RESTRICT_POWER,
3284 })
3285 public @interface RestrictType {
3286 }
3287
3288 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003289 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003290 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3291 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3292 }
3293 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003294 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003295
3296 final PackageManager pm = mContext.getPackageManager();
3297 final List<UserInfo> users;
3298 final List<ApplicationInfo> apps;
3299
3300 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3301 try {
3302 users = mUserManager.getUsers();
3303 } finally {
3304 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3305 }
3306 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3307 try {
3308 apps = pm.getInstalledApplications(
3309 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3310 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3311 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3312 } finally {
3313 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3314 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003315
Felipe Leme873a83a2016-09-07 11:34:10 -07003316 final int usersSize = users.size();
3317 final int appsSize = apps.size();
3318 for (int i = 0; i < usersSize; i++) {
3319 final UserInfo user = users.get(i);
3320 for (int j = 0; j < appsSize; j++) {
3321 final ApplicationInfo app = apps.get(j);
3322 final int uid = UserHandle.getUid(user.id, app.uid);
3323 switch (type) {
3324 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003325 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003326 break;
3327 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003328 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003329 break;
3330 default:
3331 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3332 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003333 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003334 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003335 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003336 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003337 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003338 }
3339
Felipe Lemef0823852016-06-08 13:43:08 -07003340 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003341 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08003342 for (int i = 0; i < users.size(); i++) {
3343 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08003344 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003345 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003346 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07003347 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07003348 updateRuleForAppIdleUL(uid);
3349 updateRuleForDeviceIdleUL(uid);
3350 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003351 // Update internal rules.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003352 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003353 }
3354 }
3355 }
3356
Felipe Leme70c57c22016-03-29 10:45:13 -07003357 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3358 // methods below could be merged into a isUidValidForRules() method.
3359 private boolean isUidValidForBlacklistRules(int uid) {
3360 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003361 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003362 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003363 return true;
3364 }
3365
3366 return false;
3367 }
3368
Felipe Leme70c57c22016-03-29 10:45:13 -07003369 private boolean isUidValidForWhitelistRules(int uid) {
3370 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3371 }
3372
Amith Yamasani15e472352015-04-24 19:06:07 -07003373 private boolean isUidIdle(int uid) {
3374 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3375 final int userId = UserHandle.getUserId(uid);
3376
songjinshi0655edd2016-05-18 19:55:32 +08003377 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003378 for (String packageName : packages) {
3379 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3380 return false;
3381 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003382 }
3383 }
3384 return true;
3385 }
3386
3387 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003388 * Checks if an uid has INTERNET permissions.
3389 * <p>
3390 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003391 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003392 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003393 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003394 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003395 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003396 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003397 }
3398 } catch (RemoteException e) {
3399 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003400 return true;
3401 }
3402
3403 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003404 * Clears all state - internal and external - associated with an UID.
3405 */
3406 private void onUidDeletedUL(int uid) {
3407 // First cleanup in-memory state synchronously...
3408 mUidRules.delete(uid);
3409 mUidPolicy.delete(uid);
3410 mUidFirewallStandbyRules.delete(uid);
3411 mUidFirewallDozableRules.delete(uid);
3412 mUidFirewallPowerSaveRules.delete(uid);
3413 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3414 mPowerSaveWhitelistAppIds.delete(uid);
3415 mPowerSaveTempWhitelistAppIds.delete(uid);
3416
3417 // ...then update iptables asynchronously.
3418 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3419 }
3420
3421 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003422 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003423 *
Felipe Leme781ba142016-05-09 16:24:48 -07003424 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003425 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003426 * <li>Doze mode
3427 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003428 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003429 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003430 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003431 *
3432 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003433 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003434 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003435 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003436 updateRuleForDeviceIdleUL(uid);
3437 updateRuleForAppIdleUL(uid);
3438 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003439
3440 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003441 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003442
3443 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003444 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003445 }
3446
Felipe Leme70c57c22016-03-29 10:45:13 -07003447 /**
3448 * Applies network rules to bandwidth controllers based on process state and user-defined
3449 * restrictions (blacklist / whitelist).
3450 *
3451 * <p>
3452 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3453 * networks:
3454 * <ul>
3455 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3456 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3457 * also blacklisted.
3458 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3459 * no UIDs other those whitelisted will have access.
3460 * <ul>
3461 *
3462 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3463 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3464 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3465 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003466 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003467 * {@link INetworkManagementService}, but this method should also be called in events (like
3468 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3469 * following rules should also be applied:
3470 *
3471 * <ul>
3472 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3473 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3474 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3475 * {@code bw_penalty_box}.
3476 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3477 * </ul>
3478 *
3479 * <p>For optimization, the rules are only applied on user apps that have internet access
3480 * permission, since there is no need to change the {@code iptables} rule if the app does not
3481 * have permission to use the internet.
3482 *
3483 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003484 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003485 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003486 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003487 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3488 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3489 "updateRulesForDataUsageRestrictionsUL: " + uid);
3490 }
3491 try {
3492 updateRulesForDataUsageRestrictionsULInner(uid);
3493 } finally {
3494 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3495 }
3496 }
3497
3498 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003499 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003500 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003501 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003502 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003503
Dianne Hackborn497175b2014-07-01 12:56:08 -07003504 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003505 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003506 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003507
Felipe Leme781ba142016-05-09 16:24:48 -07003508 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003509 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003510 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3511 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003512
Felipe Leme70c57c22016-03-29 10:45:13 -07003513 // First step: define the new rule based on user restrictions and foreground state.
3514 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003515 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3516 newRule = RULE_TEMPORARY_ALLOW_METERED;
3517 } else if (isWhitelisted) {
3518 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003519 }
3520 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003521 if (isBlacklisted) {
3522 newRule = RULE_REJECT_METERED;
3523 } else if (mRestrictBackground && isWhitelisted) {
3524 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003525 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003526 }
Felipe Leme781ba142016-05-09 16:24:48 -07003527 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003528
Felipe Lemef28983d2016-03-25 12:18:23 -07003529 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003530 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003531 + ": isForeground=" +isForeground
3532 + ", isBlacklisted=" + isBlacklisted
3533 + ", isWhitelisted=" + isWhitelisted
3534 + ", oldRule=" + uidRulesToString(oldRule)
3535 + ", newRule=" + uidRulesToString(newRule)
3536 + ", newUidRules=" + uidRulesToString(newUidRules)
3537 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003538 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003539
Felipe Leme46c4fc32016-05-04 09:21:43 -07003540 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003541 mUidRules.delete(uid);
3542 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003543 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003544 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003545
Felipe Leme70c57c22016-03-29 10:45:13 -07003546 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003547 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003548 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003549 // Temporarily whitelist foreground app, removing from blacklist if necessary
3550 // (since bw_penalty_box prevails over bw_happy_box).
3551
3552 setMeteredNetworkWhitelist(uid, true);
3553 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3554 // but ideally it should be just:
3555 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003556 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003557 setMeteredNetworkBlacklist(uid, false);
3558 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003559 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003560 // Remove temporary whitelist from app that is not on foreground anymore.
3561
3562 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3563 // but ideally they should be just:
3564 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3565 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003566 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003567 setMeteredNetworkWhitelist(uid, false);
3568 }
Felipe Leme781ba142016-05-09 16:24:48 -07003569 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003570 setMeteredNetworkBlacklist(uid, true);
3571 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003572 } else if (hasRule(newRule, RULE_REJECT_METERED)
3573 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003574 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003575 setMeteredNetworkBlacklist(uid, isBlacklisted);
Hugo Benichi2966c182017-03-28 17:17:13 +09003576 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003577 // Since blacklist prevails over whitelist, we need to handle the special case
3578 // where app is whitelisted and blacklisted at the same time (although such
3579 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003580 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003581 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003582 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3583 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003584 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003585 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003586 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003587 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003588 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3589 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003590 + ", whitelisted=" + isWhitelisted
3591 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003592 + ", newRule=" + uidRulesToString(newUidRules)
3593 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003594 }
Felipe Leme781ba142016-05-09 16:24:48 -07003595
Sudheer Shankac9d94072017-02-22 22:13:55 +00003596 // Dispatch changed rule to existing listeners.
3597 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003598 }
3599 }
3600
3601 /**
3602 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3603 * listeners in case of change.
3604 * <p>
3605 * There are 3 power-related rules that affects whether an app has background access on
3606 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3607 * restriction, it's added to the equivalent firewall chain:
3608 * <ul>
3609 * <li>App is idle: {@code fw_standby} firewall chain.
3610 * <li>Device is idle: {@code fw_dozable} firewall chain.
3611 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3612 * </ul>
3613 * <p>
3614 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3615 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3616 * <p>
3617 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3618 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003619 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003620 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3621
Sudheer Shankac9d94072017-02-22 22:13:55 +00003622 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003623
Sudheer Shankac9d94072017-02-22 22:13:55 +00003624 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003625 mUidRules.delete(uid);
3626 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003627 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003628 }
3629 }
3630
3631 /**
3632 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3633 *
3634 * @param uid the uid of the app to update rules for
3635 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3636 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3637 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003638 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003639 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003640 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003641 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3642 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3643 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3644 + (paroled ? "P" : "-"));
3645 }
3646 try {
3647 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3648 } finally {
3649 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3650 }
3651 }
3652
3653 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003654 if (!isUidValidForBlacklistRules(uid)) {
3655 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003656 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003657 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003658
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003659 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003660 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003661 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003662
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003663 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003664 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3665 int newRule = RULE_NONE;
3666
3667 // First step: define the new rule based on user restrictions and foreground state.
3668
3669 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3670 // by considering the foreground and non-foreground states.
3671 if (isForeground) {
3672 if (restrictMode) {
3673 newRule = RULE_ALLOW_ALL;
3674 }
3675 } else if (restrictMode) {
3676 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3677 }
3678
3679 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3680
3681 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003682 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003683 + ", isIdle: " + isIdle
3684 + ", mRestrictPower: " + mRestrictPower
3685 + ", mDeviceIdleMode: " + mDeviceIdleMode
3686 + ", isForeground=" + isForeground
3687 + ", isWhitelisted=" + isWhitelisted
3688 + ", oldRule=" + uidRulesToString(oldRule)
3689 + ", newRule=" + uidRulesToString(newRule)
3690 + ", newUidRules=" + uidRulesToString(newUidRules)
3691 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3692 }
3693
Felipe Leme781ba142016-05-09 16:24:48 -07003694 // Second step: notify listeners if state changed.
3695 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003696 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003697 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003698 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003699 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3700 } else {
3701 // All scenarios should have been covered above
3702 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3703 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003704 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003705 + ", newRule=" + uidRulesToString(newUidRules)
3706 + ", oldRule=" + uidRulesToString(oldUidRules));
3707 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003708 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003709 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003710
Sudheer Shankac9d94072017-02-22 22:13:55 +00003711 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003712 }
3713
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003714 private class AppIdleStateChangeListener
3715 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3716
3717 @Override
3718 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3719 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003720 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3721 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003722 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003723 synchronized (mUidRulesFirstLock) {
3724 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003725 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003726 }
3727 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003728 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003729 }
3730
3731 @Override
3732 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003733 synchronized (mUidRulesFirstLock) {
3734 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003735 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003736 }
3737 }
3738
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003739 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3740 if (listener != null) {
3741 try {
3742 listener.onUidRulesChanged(uid, uidRules);
3743 } catch (RemoteException ignored) {
3744 }
3745 }
3746 }
3747
3748 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3749 String[] meteredIfaces) {
3750 if (listener != null) {
3751 try {
3752 listener.onMeteredIfacesChanged(meteredIfaces);
3753 } catch (RemoteException ignored) {
3754 }
3755 }
3756 }
3757
3758 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3759 boolean restrictBackground) {
3760 if (listener != null) {
3761 try {
3762 listener.onRestrictBackgroundChanged(restrictBackground);
3763 } catch (RemoteException ignored) {
3764 }
3765 }
3766 }
3767
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003768 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3769 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003770 if (listener != null) {
3771 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003772 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003773 } catch (RemoteException ignored) {
3774 }
3775 }
3776 }
3777
Makoto Onuki8e777332017-03-28 11:25:47 -07003778 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003779 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003780 public boolean handleMessage(Message msg) {
3781 switch (msg.what) {
3782 case MSG_RULES_CHANGED: {
3783 final int uid = msg.arg1;
3784 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003785 final int length = mListeners.beginBroadcast();
3786 for (int i = 0; i < length; i++) {
3787 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3788 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003789 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003790 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003791 return true;
3792 }
3793 case MSG_METERED_IFACES_CHANGED: {
3794 final String[] meteredIfaces = (String[]) msg.obj;
3795 final int length = mListeners.beginBroadcast();
3796 for (int i = 0; i < length; i++) {
3797 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003798 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003799 }
3800 mListeners.finishBroadcast();
3801 return true;
3802 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003803 case MSG_LIMIT_REACHED: {
3804 final String iface = (String) msg.obj;
3805
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003806 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003807 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003808 if (mMeteredIfaces.contains(iface)) {
3809 try {
3810 // force stats update to make sure we have
3811 // numbers that caused alert to trigger.
3812 mNetworkStats.forceUpdate();
3813 } catch (RemoteException e) {
3814 // ignored; service lives in system_server
3815 }
3816
Felipe Lemef0823852016-06-08 13:43:08 -07003817 updateNetworkEnabledNL();
3818 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003819 }
3820 }
3821 return true;
3822 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003823 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3824 final boolean restrictBackground = msg.arg1 != 0;
3825 final int length = mListeners.beginBroadcast();
3826 for (int i = 0; i < length; i++) {
3827 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003828 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003829 }
3830 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003831 final Intent intent =
3832 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3833 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3834 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3835 return true;
3836 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003837 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003838 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003839 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003840 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003841 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07003842 final int length = mListeners.beginBroadcast();
3843 for (int i = 0; i < length; i++) {
3844 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003845 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003846 }
3847 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003848 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3849 if (notifyApp.booleanValue()) {
3850 broadcastRestrictBackgroundChanged(uid, notifyApp);
3851 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003852 return true;
3853 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003854 case MSG_ADVISE_PERSIST_THRESHOLD: {
3855 final long lowestRule = (Long) msg.obj;
3856 try {
3857 // make sure stats are recorded frequently enough; we aim
3858 // for 2MB threshold for 2GB/month rules.
3859 final long persistThreshold = lowestRule / 1000;
3860 mNetworkStats.advisePersistThreshold(persistThreshold);
3861 } catch (RemoteException e) {
3862 // ignored; service lives in system_server
3863 }
3864 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003865 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003866 case MSG_UPDATE_INTERFACE_QUOTA: {
3867 removeInterfaceQuota((String) msg.obj);
3868 // int params need to be stitched back into a long
3869 setInterfaceQuota((String) msg.obj,
3870 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3871 return true;
3872 }
3873 case MSG_REMOVE_INTERFACE_QUOTA: {
3874 removeInterfaceQuota((String) msg.obj);
3875 return true;
3876 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003877 case MSG_SET_FIREWALL_RULES: {
3878 final int chain = msg.arg1;
3879 final int toggle = msg.arg2;
3880 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3881 if (uidRules != null) {
3882 setUidFirewallRules(chain, uidRules);
3883 }
3884 if (toggle != CHAIN_TOGGLE_NONE) {
3885 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3886 }
3887 return true;
3888 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003889 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3890 resetUidFirewallRules(msg.arg1);
3891 return true;
3892 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003893 default: {
3894 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003895 }
3896 }
3897 }
Makoto Onuki8e777332017-03-28 11:25:47 -07003898 };
3899
3900 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
3901 @Override
3902 public boolean handleMessage(Message msg) {
3903 switch (msg.what) {
3904 case UID_MSG_STATE_CHANGED: {
3905 final int uid = msg.arg1;
3906 final int procState = msg.arg2;
3907 final long procStateSeq = (Long) msg.obj;
3908
3909 handleUidChanged(uid, procState, procStateSeq);
3910 return true;
3911 }
3912 case UID_MSG_GONE: {
3913 final int uid = msg.arg1;
3914 handleUidGone(uid);
3915 return true;
3916 }
3917 default: {
3918 return false;
3919 }
3920 }
3921 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003922
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003923 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003924
Makoto Onuki8e777332017-03-28 11:25:47 -07003925 void handleUidChanged(int uid, int procState, long procStateSeq) {
3926 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
3927 try {
3928 synchronized (mUidRulesFirstLock) {
3929 // We received a uid state change callback, add it to the history so that it
3930 // will be useful for debugging.
3931 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
3932 // Now update the network policy rules as per the updated uid state.
3933 updateUidStateUL(uid, procState);
3934 // Updating the network rules is done, so notify AMS about this.
3935 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
3936 }
3937 } finally {
3938 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3939 }
3940 }
3941
3942 void handleUidGone(int uid) {
3943 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
3944 try {
3945 synchronized (mUidRulesFirstLock) {
3946 removeUidStateUL(uid);
3947 }
3948 } finally {
3949 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3950 }
3951 }
3952
Felipe Leme57e3d312016-08-23 14:42:52 -07003953 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3954 final PackageManager pm = mContext.getPackageManager();
3955 final String[] packages = pm.getPackagesForUid(uid);
3956 if (packages != null) {
3957 final int userId = UserHandle.getUserId(uid);
3958 for (String packageName : packages) {
3959 final Intent intent =
3960 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3961 intent.setPackage(packageName);
3962 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3963 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3964 }
3965 }
3966 }
3967
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003968 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003969 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003970 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003971 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003972 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003973 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003974 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003975 }
3976 }
3977
3978 private void removeInterfaceQuota(String iface) {
3979 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003980 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003981 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003982 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003983 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003984 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003985 }
3986 }
3987
Felipe Leme70c57c22016-03-29 10:45:13 -07003988 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3989 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003990 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003991 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003992 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003993 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3994 } catch (RemoteException e) {
3995 // ignored; service lives in system_server
3996 }
3997 }
3998
3999 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4000 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4001 try {
4002 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4003 } catch (IllegalStateException e) {
4004 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004005 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004006 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004007 }
4008 }
4009
Felipe Lemebc853dd2016-09-08 13:26:55 -07004010 private static final int CHAIN_TOGGLE_NONE = 0;
4011 private static final int CHAIN_TOGGLE_ENABLE = 1;
4012 private static final int CHAIN_TOGGLE_DISABLE = 2;
4013 @Retention(RetentionPolicy.SOURCE)
4014 @IntDef(flag = false, value = {
4015 CHAIN_TOGGLE_NONE,
4016 CHAIN_TOGGLE_ENABLE,
4017 CHAIN_TOGGLE_DISABLE
4018 })
4019 public @interface ChainToggleType {
4020 }
4021
4022 /**
4023 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
4024 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
4025 *
4026 * @param chain firewall chain.
4027 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4028 * @param toggle whether the chain should be enabled, disabled, or not changed.
4029 */
4030 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
4031 @ChainToggleType int toggle) {
4032 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
4033 }
4034
Amith Yamasani15e472352015-04-24 19:06:07 -07004035 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004036 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4037 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4038 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004039 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004040 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004041 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004042 int size = uidRules.size();
4043 int[] uids = new int[size];
4044 int[] rules = new int[size];
4045 for(int index = size - 1; index >= 0; --index) {
4046 uids[index] = uidRules.keyAt(index);
4047 rules[index] = uidRules.valueAt(index);
4048 }
4049 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004050 } catch (IllegalStateException e) {
4051 Log.wtf(TAG, "problem setting firewall uid rules", e);
4052 } catch (RemoteException e) {
4053 // ignored; service lives in system_server
4054 }
4055 }
4056
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004057 /**
4058 * Add or remove a uid to the firewall blacklist for all network ifaces.
4059 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004060 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004061 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4062 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4063 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004064 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004065 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004066 if (chain == FIREWALL_CHAIN_DOZABLE) {
4067 mUidFirewallDozableRules.put(uid, rule);
4068 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4069 mUidFirewallStandbyRules.put(uid, rule);
4070 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4071 mUidFirewallPowerSaveRules.put(uid, rule);
4072 }
4073
4074 try {
4075 mNetworkManager.setFirewallUidRule(chain, uid, rule);
4076 } catch (IllegalStateException e) {
4077 Log.wtf(TAG, "problem setting firewall uid rules", e);
4078 } catch (RemoteException e) {
4079 // ignored; service lives in system_server
4080 }
4081 } finally {
4082 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004083 }
4084 }
4085
4086 /**
4087 * Add or remove a uid to the firewall blacklist for all network ifaces.
4088 */
Felipe Lemef0823852016-06-08 13:43:08 -07004089 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004090 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4091 mFirewallChainStates.get(chain) == enable) {
4092 // All is the same, nothing to do.
4093 return;
4094 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004095 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004096 try {
4097 mNetworkManager.setFirewallChainEnabled(chain, enable);
4098 } catch (IllegalStateException e) {
4099 Log.wtf(TAG, "problem enable firewall chain", e);
4100 } catch (RemoteException e) {
4101 // ignored; service lives in system_server
4102 }
4103 }
4104
Felipe Leme03e95e22016-09-09 09:25:31 -07004105 /**
4106 * Resets all firewall rules associated with an UID.
4107 */
4108 private void resetUidFirewallRules(int uid) {
4109 try {
4110 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4111 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4112 mNetworkManager
4113 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4114 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4115 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4116 } catch (IllegalStateException e) {
4117 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4118 } catch (RemoteException e) {
4119 // ignored; service lives in system_server
4120 }
4121 }
4122
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004123 private long getTotalBytes(NetworkTemplate template, long start, long end) {
4124 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004125 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004126 } catch (RuntimeException e) {
4127 Slog.w(TAG, "problem reading network stats: " + e);
4128 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004129 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004130 // ignored; service lives in system_server
4131 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004132 }
4133 }
4134
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004135 private boolean isBandwidthControlEnabled() {
4136 final long token = Binder.clearCallingIdentity();
4137 try {
4138 return mNetworkManager.isBandwidthControlEnabled();
4139 } catch (RemoteException e) {
4140 // ignored; service lives in system_server
4141 return false;
4142 } finally {
4143 Binder.restoreCallingIdentity(token);
4144 }
4145 }
4146
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004147 /**
4148 * Try refreshing {@link #mTime} when stale.
4149 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07004150 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004151 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004152 mTime.forceRefresh();
4153 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004154 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004155
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004156 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004157 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
4158 }
4159
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004160 private static Intent buildAllowBackgroundDataIntent() {
4161 return new Intent(ACTION_ALLOW_BACKGROUND);
4162 }
4163
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004164 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4165 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
4166 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4167 return intent;
4168 }
4169
Wei Liu546cb772016-07-21 16:19:01 -07004170 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004171 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004172 intent.setComponent(ComponentName.unflattenFromString(
4173 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004174 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4175 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4176 return intent;
4177 }
4178
Wei Liu546cb772016-07-21 16:19:01 -07004179 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004180 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004181 intent.setComponent(ComponentName.unflattenFromString(
4182 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004183 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4184 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4185 return intent;
4186 }
4187
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004188 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004189 public void addIdleHandler(IdleHandler handler) {
4190 mHandler.getLooper().getQueue().addIdleHandler(handler);
4191 }
4192
jackqdyulei29c82ab2017-03-10 14:09:16 -08004193 @VisibleForTesting
4194 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4195 mRestrictBackgroundPowerState = result;
4196
4197 boolean restrictBackground = result.batterySaverEnabled;
4198 boolean shouldInvokeRestrictBackground;
4199 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4200 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4201
4202 if (result.globalBatterySaverEnabled) {
4203 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4204 // turn it on.
4205 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4206 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4207 localRestrictBgChangedInBsm = false;
4208 } else {
4209 // Try to restore the restrictBackground if it doesn't change in bsm
4210 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4211 restrictBackground = mRestrictBackgroundBeforeBsm;
4212 }
4213
4214 if (shouldInvokeRestrictBackground) {
4215 setRestrictBackground(restrictBackground);
4216 }
4217
4218 // Change it at last so setRestrictBackground() won't affect this variable
4219 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4220 }
4221
Jeff Sharkey1b861272011-05-22 00:34:52 -07004222 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4223 final int size = source.size();
4224 for (int i = 0; i < size; i++) {
4225 target.put(source.keyAt(i), true);
4226 }
4227 }
4228
Stuart Scottf1fb3972015-04-02 18:00:02 -07004229 @Override
4230 public void factoryReset(String subscriber) {
4231 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4232
Stuart Scotte3e314d2015-04-20 14:07:45 -07004233 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4234 return;
4235 }
4236
Stuart Scottf1fb3972015-04-02 18:00:02 -07004237 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004238 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004239 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4240 for (NetworkPolicy policy : policies) {
4241 if (policy.template.equals(template)) {
4242 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4243 policy.inferred = false;
4244 policy.clearSnooze();
4245 }
4246 }
4247 setNetworkPolicies(policies);
4248
4249 // Turn restrict background data off
4250 setRestrictBackground(false);
4251
Stuart Scotte3e314d2015-04-20 14:07:45 -07004252 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4253 // Remove app's "restrict background data" flag
4254 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4255 setUidPolicy(uid, POLICY_NONE);
4256 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004257 }
4258 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004259
Felipe Lemed17fda42016-04-29 11:12:45 -07004260 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4261
4262 @Override
4263 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004264 synchronized (mUidRulesFirstLock) {
4265 boolean changed = removeUserStateUL(userId, false);
4266 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004267 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004268 synchronized (mNetworkPoliciesSecondLock) {
4269 writePolicyAL();
4270 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004271 }
4272 }
4273 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004274
4275 /**
4276 * @return true if the given uid is restricted from doing networking on metered networks.
4277 */
4278 @Override
4279 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4280 final int uidRules;
4281 final boolean isBackgroundRestricted;
4282 synchronized (mUidRulesFirstLock) {
4283 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4284 isBackgroundRestricted = mRestrictBackground;
4285 }
4286 return isBackgroundRestricted
4287 && !hasRule(uidRules, RULE_ALLOW_METERED)
4288 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4289 }
4290
4291 /**
4292 * @return true if networking is blocked on the given interface for the given uid according
4293 * to current networking policies.
4294 */
4295 @Override
4296 public boolean isUidNetworkingBlocked(int uid, String ifname) {
4297 final int uidRules;
4298 final boolean isBackgroundRestricted;
4299 final boolean isNetworkMetered;
4300 synchronized (mUidRulesFirstLock) {
4301 uidRules = mUidRules.get(uid, RULE_NONE);
4302 isBackgroundRestricted = mRestrictBackground;
4303 synchronized (mNetworkPoliciesSecondLock) {
4304 isNetworkMetered = mMeteredIfaces.contains(ifname);
4305 }
4306 }
4307 if (hasRule(uidRules, RULE_REJECT_ALL)) {
4308 if (LOGV) logUidStatus(uid, "blocked by power restrictions");
4309 return true;
4310 }
4311 if (!isNetworkMetered) {
4312 if (LOGV) logUidStatus(uid, "allowed on unmetered network");
4313 return false;
4314 }
4315 if (hasRule(uidRules, RULE_REJECT_METERED)) {
4316 if (LOGV) logUidStatus(uid, "blacklisted on metered network");
4317 return true;
4318 }
4319 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4320 if (LOGV) logUidStatus(uid, "whitelisted on metered network");
4321 return false;
4322 }
4323 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4324 if (LOGV) logUidStatus(uid, "temporary whitelisted on metered network");
4325 return false;
4326 }
4327 if (isBackgroundRestricted) {
4328 if (LOGV) logUidStatus(uid, "blocked when background is restricted");
4329 return true;
4330 }
4331 if (LOGV) logUidStatus(uid, "allowed by default");
4332 return false;
4333 }
4334 }
4335
4336 private static boolean hasRule(int uidRules, int rule) {
4337 return (uidRules & rule) != 0;
4338 }
4339
4340 private static void logUidStatus(int uid, String descr) {
4341 Slog.d(TAG, String.format("uid %d is %s", uid, descr));
Felipe Lemed17fda42016-04-29 11:12:45 -07004342 }
Sudheer Shankae7361852017-03-07 11:51:46 -08004343
4344 /**
4345 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
4346 * (uid, procStateSeq) pairs.
4347 */
4348 @VisibleForTesting
4349 public static final class ProcStateSeqHistory {
4350 private static final int INVALID_UID = -1;
4351
4352 /**
4353 * Denotes maximum number of items this history can hold.
4354 */
4355 private final int mMaxCapacity;
4356 /**
4357 * Used for storing the uid information.
4358 */
4359 private final int[] mUids;
4360 /**
4361 * Used for storing the sequence numbers associated with {@link #mUids}.
4362 */
4363 private final long[] mProcStateSeqs;
4364 /**
4365 * Points to the next available slot for writing (uid, procStateSeq) pair.
4366 */
4367 private int mHistoryNext;
4368
4369 public ProcStateSeqHistory(int maxCapacity) {
4370 mMaxCapacity = maxCapacity;
4371 mUids = new int[mMaxCapacity];
4372 Arrays.fill(mUids, INVALID_UID);
4373 mProcStateSeqs = new long[mMaxCapacity];
4374 }
4375
4376 @GuardedBy("mUidRulesFirstLock")
4377 public void addProcStateSeqUL(int uid, long procStateSeq) {
4378 mUids[mHistoryNext] = uid;
4379 mProcStateSeqs[mHistoryNext] = procStateSeq;
4380 mHistoryNext = increaseNext(mHistoryNext, 1);
4381 }
4382
4383 @GuardedBy("mUidRulesFirstLock")
4384 public void dumpUL(IndentingPrintWriter fout) {
4385 if (mUids[0] == INVALID_UID) {
4386 fout.println("NONE");
4387 return;
4388 }
4389 int index = mHistoryNext;
4390 do {
4391 index = increaseNext(index, -1);
4392 if (mUids[index] == INVALID_UID) {
4393 break;
4394 }
4395 fout.println(getString(mUids[index], mProcStateSeqs[index]));
4396 } while (index != mHistoryNext);
4397 }
4398
4399 public static String getString(int uid, long procStateSeq) {
Sudheer Shankadb9aaf032017-06-19 19:05:31 -07004400 return "UID=" + uid + " Seq=" + procStateSeq;
Sudheer Shankae7361852017-03-07 11:51:46 -08004401 }
4402
4403 private int increaseNext(int next, int increment) {
4404 next += increment;
4405 if (next >= mMaxCapacity) {
4406 next = 0;
4407 } else if (next < 0) {
4408 next = mMaxCapacity - 1;
4409 }
4410 return next;
4411 }
4412 }
Chris Wren193ae6b2017-03-31 15:17:11 -04004413
4414 private class NotificationId {
4415 private final String mTag;
4416 private final int mId;
4417
4418 NotificationId(NetworkPolicy policy, int type) {
4419 mTag = buildNotificationTag(policy, type);
4420 mId = type;
4421 }
4422
4423 @Override
4424 public boolean equals(Object o) {
4425 if (this == o) return true;
4426 if (!(o instanceof NotificationId)) return false;
4427 NotificationId that = (NotificationId) o;
4428 return Objects.equals(mTag, that.mTag);
4429 }
4430
4431 @Override
4432 public int hashCode() {
4433 return Objects.hash(mTag);
4434 }
4435
4436 /**
4437 * Build unique tag that identifies an active {@link NetworkPolicy}
4438 * notification of a specific type, like {@link #TYPE_LIMIT}.
4439 */
4440 private String buildNotificationTag(NetworkPolicy policy, int type) {
4441 return TAG + ":" + policy.template.hashCode() + ":" + type;
4442 }
4443
4444 public String getTag() {
4445 return mTag;
4446 }
4447
4448 public int getId() {
4449 return mId;
4450 }
4451 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004452}