blob: f70486a8b889ae1bc9da50198b046c77bf1248b1 [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());
2653 } else if ("month_soft".equals(fake)) {
2654 plans.add(SubscriptionPlan.Builder
2655 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2656 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2657 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2658 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002659 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2660 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2661 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2662 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2663 .build());
2664 } else if ("month_none".equals(fake)) {
2665 plans.add(SubscriptionPlan.Builder
2666 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2667 .setTitle("G-Mobile")
2668 .build());
2669 } else if ("prepaid".equals(fake)) {
2670 plans.add(SubscriptionPlan.Builder
2671 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2672 ZonedDateTime.now().plusDays(10))
2673 .setTitle("G-Mobile")
2674 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2675 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2676 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2677 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2678 .build());
2679 } else if ("prepaid_crazy".equals(fake)) {
2680 plans.add(SubscriptionPlan.Builder
2681 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2682 ZonedDateTime.now().plusDays(10))
2683 .setTitle("G-Mobile Anytime")
2684 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2685 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2686 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2687 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2688 .build());
2689 plans.add(SubscriptionPlan.Builder
2690 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2691 ZonedDateTime.now().plusDays(20))
2692 .setTitle("G-Mobile Nickel Nights")
2693 .setSummary("5¢/GB between 1-5AM")
2694 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2695 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2696 .build());
2697 plans.add(SubscriptionPlan.Builder
2698 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2699 ZonedDateTime.now().plusDays(20))
2700 .setTitle("G-Mobile Bonus 3G")
2701 .setSummary("Unlimited 3G data")
2702 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2703 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2704 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2705 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2706 .build());
2707 }
2708 return plans.toArray(new SubscriptionPlan[plans.size()]);
2709 }
2710
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002711 synchronized (mUidRulesFirstLock) {
2712 synchronized (mNetworkPoliciesSecondLock) {
2713 return mSubscriptionPlans.get(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002714 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002715 }
2716 }
2717
2718 @Override
2719 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2720 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2721
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002722 for (SubscriptionPlan plan : plans) {
2723 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002724 }
2725
2726 final long token = Binder.clearCallingIdentity();
2727 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002728 maybeRefreshTrustedTime();
2729 synchronized (mUidRulesFirstLock) {
2730 synchronized (mNetworkPoliciesSecondLock) {
2731 mSubscriptionPlans.put(subId, plans);
2732 // TODO: update any implicit details from newly defined plans
2733 handleNetworkPoliciesUpdateAL(false);
2734 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002735 }
2736 } finally {
2737 Binder.restoreCallingIdentity(token);
2738 }
2739 }
2740
2741 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002742 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002743 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002744
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002745 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2746
Dianne Hackborn497175b2014-07-01 12:56:08 -07002747 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002748 for (String arg : args) {
2749 argSet.add(arg);
2750 }
2751
Felipe Lemef0823852016-06-08 13:43:08 -07002752 synchronized (mUidRulesFirstLock) {
2753 synchronized (mNetworkPoliciesSecondLock) {
2754 if (argSet.contains("--unsnooze")) {
2755 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2756 mNetworkPolicy.valueAt(i).clearSnooze();
2757 }
2758
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002759 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002760
2761 fout.println("Cleared snooze timestamps");
2762 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002763 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002764
Felipe Lemef0823852016-06-08 13:43:08 -07002765 fout.print("System ready: "); fout.println(mSystemReady);
2766 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2767 fout.print("Restrict power: "); fout.println(mRestrictPower);
2768 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2769 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002770 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002771 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2772 fout.println(mNetworkPolicy.valueAt(i).toString());
2773 }
2774 fout.decreaseIndent();
2775
2776 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2777
2778 fout.println("Policy for UIDs:");
2779 fout.increaseIndent();
2780 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002781 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002782 final int uid = mUidPolicy.keyAt(i);
2783 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002784 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002785 fout.print(uid);
2786 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002787 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002788 fout.println();
2789 }
2790 fout.decreaseIndent();
2791
2792 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2793 if (size > 0) {
2794 fout.println("Power save whitelist (except idle) app ids:");
2795 fout.increaseIndent();
2796 for (int i = 0; i < size; i++) {
2797 fout.print("UID=");
2798 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2799 fout.print(": ");
2800 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2801 fout.println();
2802 }
2803 fout.decreaseIndent();
2804 }
2805
2806 size = mPowerSaveWhitelistAppIds.size();
2807 if (size > 0) {
2808 fout.println("Power save whitelist app ids:");
2809 fout.increaseIndent();
2810 for (int i = 0; i < size; i++) {
2811 fout.print("UID=");
2812 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2813 fout.print(": ");
2814 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2815 fout.println();
2816 }
2817 fout.decreaseIndent();
2818 }
2819
Felipe Lemef0823852016-06-08 13:43:08 -07002820 size = mDefaultRestrictBackgroundWhitelistUids.size();
2821 if (size > 0) {
2822 fout.println("Default restrict background whitelist uids:");
2823 fout.increaseIndent();
2824 for (int i = 0; i < size; i++) {
2825 fout.print("UID=");
2826 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2827 fout.println();
2828 }
2829 fout.decreaseIndent();
2830 }
2831
2832 size = mRestrictBackgroundWhitelistRevokedUids.size();
2833 if (size > 0) {
2834 fout.println("Default restrict background whitelist uids revoked by users:");
2835 fout.increaseIndent();
2836 for (int i = 0; i < size; i++) {
2837 fout.print("UID=");
2838 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2839 fout.println();
2840 }
2841 fout.decreaseIndent();
2842 }
2843
2844 final SparseBooleanArray knownUids = new SparseBooleanArray();
2845 collectKeys(mUidState, knownUids);
2846 collectKeys(mUidRules, knownUids);
2847
2848 fout.println("Status for all known UIDs:");
2849 fout.increaseIndent();
2850 size = knownUids.size();
2851 for (int i = 0; i < size; i++) {
2852 final int uid = knownUids.keyAt(i);
2853 fout.print("UID=");
2854 fout.print(uid);
2855
2856 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2857 fout.print(" state=");
2858 fout.print(state);
2859 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2860 fout.print(" (fg)");
2861 } else {
2862 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2863 ? " (fg svc)" : " (bg)");
2864 }
2865
2866 final int uidRules = mUidRules.get(uid, RULE_NONE);
2867 fout.print(" rules=");
2868 fout.print(uidRulesToString(uidRules));
2869 fout.println();
2870 }
2871 fout.decreaseIndent();
2872
2873 fout.println("Status for just UIDs with rules:");
2874 fout.increaseIndent();
2875 size = mUidRules.size();
2876 for (int i = 0; i < size; i++) {
2877 final int uid = mUidRules.keyAt(i);
2878 fout.print("UID=");
2879 fout.print(uid);
2880 final int uidRules = mUidRules.get(uid, RULE_NONE);
2881 fout.print(" rules=");
2882 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002883 fout.println();
2884 }
2885 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08002886
2887 fout.println("Observed uid state changes:");
2888 fout.increaseIndent();
2889 mObservedHistory.dumpUL(fout);
2890 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002891 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002892 }
2893 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002894
2895 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002896 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002897 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002898 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002899 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002900 }
2901
2902 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002903 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002904 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2905
Felipe Lemef0823852016-06-08 13:43:08 -07002906 synchronized (mUidRulesFirstLock) {
2907 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002908 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002909 }
2910
Felipe Lemef0823852016-06-08 13:43:08 -07002911 private boolean isUidForegroundUL(int uid) {
2912 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002913 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2914 }
2915
Felipe Lemef0823852016-06-08 13:43:08 -07002916 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002917 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002918 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002919 }
2920
Felipe Lemef0823852016-06-08 13:43:08 -07002921 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002922 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2923 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2924 }
2925
Felipe Lemef0823852016-06-08 13:43:08 -07002926 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002927 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002928 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002929 }
2930
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002931 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002932 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002933 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2934 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002935 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002936 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002937 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2938 try {
2939 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2940 if (oldUidState != uidState) {
2941 // state changed, push updated rules
2942 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002943 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2944 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2945 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2946 if (isUidIdle(uid)) {
2947 updateRuleForAppIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002948 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002949 if (mDeviceIdleMode) {
2950 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002951 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002952 if (mRestrictPower) {
2953 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002954 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002955 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002956 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002957 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002958 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002959 } finally {
2960 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002961 }
2962 }
2963
Felipe Lemef0823852016-06-08 13:43:08 -07002964 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002965 final int index = mUidState.indexOfKey(uid);
2966 if (index >= 0) {
2967 final int oldUidState = mUidState.valueAt(index);
2968 mUidState.removeAt(index);
2969 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002970 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00002971 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002972 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002973 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002974 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002975 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002976 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002977 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002978 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002979 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002980 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002981 }
2982 }
2983
Felipe Lemef28983d2016-03-25 12:18:23 -07002984 // adjust stats accounting based on foreground status
2985 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002986 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2987 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
2988 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
2989 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002990 try {
2991 mNetworkStats.setUidForeground(uid, uidForeground);
2992 } catch (RemoteException e) {
2993 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002994 } finally {
2995 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07002996 }
2997 }
2998
Sudheer Shankac9d94072017-02-22 22:13:55 +00002999 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3000 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003001 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003002 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003003 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003004 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003005 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003006 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003007 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003008 }
3009
Felipe Lemef0823852016-06-08 13:43:08 -07003010 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003011 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3012 try {
3013 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3014 mUidFirewallPowerSaveRules);
3015 } finally {
3016 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3017 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003018 }
3019
Felipe Lemef0823852016-06-08 13:43:08 -07003020 void updateRuleForRestrictPowerUL(int uid) {
3021 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003022 }
3023
Felipe Lemef0823852016-06-08 13:43:08 -07003024 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003025 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3026 try {
3027 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3028 mUidFirewallDozableRules);
3029 } finally {
3030 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3031 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003032 }
3033
Felipe Lemef0823852016-06-08 13:43:08 -07003034 void updateRuleForDeviceIdleUL(int uid) {
3035 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003036 }
3037
Felipe Lemef28983d2016-03-25 12:18:23 -07003038 // NOTE: since both fw_dozable and fw_powersave uses the same map
3039 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003040 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003041 SparseIntArray rules) {
3042 if (enabled) {
3043 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003044 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003045 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003046 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003047 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003048 for (int ui = users.size() - 1; ui >= 0; ui--) {
3049 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003050 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3051 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3052 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3053 updateRulesForWhitelistedAppIds(uidRules,
3054 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003055 }
3056 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003057 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003058 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003059 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3060 }
3061 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003062 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
3063 } else {
3064 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003065 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003066 }
3067
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003068 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3069 final SparseBooleanArray whitelistedAppIds, int userId) {
3070 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3071 if (whitelistedAppIds.valueAt(i)) {
3072 final int appId = whitelistedAppIds.keyAt(i);
3073 final int uid = UserHandle.getUid(userId, appId);
3074 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3075 }
3076 }
3077 }
3078
3079 /**
3080 * @param deviceIdleMode if true then we don't consider
3081 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3082 * whitelisted.
3083 */
3084 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003085 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003086 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3087 || mPowerSaveWhitelistAppIds.get(appId);
3088 if (!deviceIdleMode) {
3089 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3090 }
3091 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003092 }
3093
Felipe Lemef28983d2016-03-25 12:18:23 -07003094 // NOTE: since both fw_dozable and fw_powersave uses the same map
3095 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003096 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003097 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003098 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3099 chain == FIREWALL_CHAIN_DOZABLE);
3100 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003101 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003102 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003103 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003104 }
3105 }
3106 }
3107
Felipe Lemef0823852016-06-08 13:43:08 -07003108 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003109 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3110 try {
3111 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3112 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003113
Felipe Leme873a83a2016-09-07 11:34:10 -07003114 // Fully update the app idle firewall chain.
3115 final List<UserInfo> users = mUserManager.getUsers();
3116 for (int ui = users.size() - 1; ui >= 0; ui--) {
3117 UserInfo user = users.get(ui);
3118 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3119 for (int uid : idleUids) {
3120 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3121 // quick check: if this uid doesn't have INTERNET permission, it
3122 // doesn't have network access anyway, so it is a waste to mess
3123 // with it here.
3124 if (hasInternetPermissions(uid)) {
3125 uidRules.put(uid, FIREWALL_RULE_DENY);
3126 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003127 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003128 }
3129 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003130
Felipe Lemebc853dd2016-09-08 13:26:55 -07003131 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003132 } finally {
3133 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3134 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003135 }
3136
Felipe Lemef0823852016-06-08 13:43:08 -07003137 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003138 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003139
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003140 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3141 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3142 }
3143 try {
3144 int appId = UserHandle.getAppId(uid);
3145 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3146 && !isUidForegroundOnRestrictPowerUL(uid)) {
3147 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3148 } else {
3149 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3150 }
3151 } finally {
3152 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003153 }
3154 }
3155
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003156 /**
3157 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3158 * changed.
3159 */
Felipe Lemef0823852016-06-08 13:43:08 -07003160 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003161 boolean paroled = mUsageStats.isAppIdleParoleOn();
3162 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003163 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003164
3165 int ruleCount = mUidFirewallStandbyRules.size();
3166 for (int i = 0; i < ruleCount; i++) {
3167 int uid = mUidFirewallStandbyRules.keyAt(i);
3168 int oldRules = mUidRules.get(uid);
3169 if (enableChain) {
3170 // Chain wasn't enabled before and the other power-related
3171 // chains are whitelists, so we can clear the
3172 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3173 // the effective rules result in blocking network access.
3174 oldRules &= MASK_METERED_NETWORKS;
3175 } else {
3176 // Skip if it had no restrictions to begin with
3177 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3178 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003179 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3180 if (newUidRules == RULE_NONE) {
3181 mUidRules.delete(uid);
3182 } else {
3183 mUidRules.put(uid, newUidRules);
3184 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003185 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003186 }
3187
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003188 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003189 * Update rules that might be changed by {@link #mRestrictBackground},
3190 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003191 */
Felipe Lemef0823852016-06-08 13:43:08 -07003192 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003193 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3194 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3195 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3196 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003197 try {
Felipe Leme09700462016-09-08 09:33:48 -07003198 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003199 updateRulesForRestrictPowerUL();
3200 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003201
Felipe Leme873a83a2016-09-07 11:34:10 -07003202 // If the set of restricted networks may have changed, re-evaluate those.
3203 if (restrictedNetworksChanged) {
3204 normalizePoliciesNL();
3205 updateNetworkRulesNL();
3206 }
3207 } finally {
3208 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003209 }
3210 }
3211
Felipe Leme09700462016-09-08 09:33:48 -07003212 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003213 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003214 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3215 try {
3216 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003217 updateRulesForPowerSaveUL();
3218 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3219 } finally {
3220 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3221 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003222 }
3223
Felipe Lemef0823852016-06-08 13:43:08 -07003224 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003225 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3226 try {
3227 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3228 } finally {
3229 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3230 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003231 }
3232
3233 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3234 private static final int TYPE_RESTRICT_POWER = 2;
3235 @Retention(RetentionPolicy.SOURCE)
3236 @IntDef(flag = false, value = {
3237 TYPE_RESTRICT_BACKGROUND,
3238 TYPE_RESTRICT_POWER,
3239 })
3240 public @interface RestrictType {
3241 }
3242
3243 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003244 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003245 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3246 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3247 }
3248 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003249 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003250
3251 final PackageManager pm = mContext.getPackageManager();
3252 final List<UserInfo> users;
3253 final List<ApplicationInfo> apps;
3254
3255 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3256 try {
3257 users = mUserManager.getUsers();
3258 } finally {
3259 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3260 }
3261 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3262 try {
3263 apps = pm.getInstalledApplications(
3264 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3265 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3266 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3267 } finally {
3268 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3269 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003270
Felipe Leme873a83a2016-09-07 11:34:10 -07003271 final int usersSize = users.size();
3272 final int appsSize = apps.size();
3273 for (int i = 0; i < usersSize; i++) {
3274 final UserInfo user = users.get(i);
3275 for (int j = 0; j < appsSize; j++) {
3276 final ApplicationInfo app = apps.get(j);
3277 final int uid = UserHandle.getUid(user.id, app.uid);
3278 switch (type) {
3279 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003280 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003281 break;
3282 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003283 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003284 break;
3285 default:
3286 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3287 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003288 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003289 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003290 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003291 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003292 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003293 }
3294
Felipe Lemef0823852016-06-08 13:43:08 -07003295 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003296 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08003297 for (int i = 0; i < users.size(); i++) {
3298 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08003299 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003300 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003301 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07003302 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07003303 updateRuleForAppIdleUL(uid);
3304 updateRuleForDeviceIdleUL(uid);
3305 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003306 // Update internal rules.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003307 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003308 }
3309 }
3310 }
3311
Felipe Leme70c57c22016-03-29 10:45:13 -07003312 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3313 // methods below could be merged into a isUidValidForRules() method.
3314 private boolean isUidValidForBlacklistRules(int uid) {
3315 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003316 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003317 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003318 return true;
3319 }
3320
3321 return false;
3322 }
3323
Felipe Leme70c57c22016-03-29 10:45:13 -07003324 private boolean isUidValidForWhitelistRules(int uid) {
3325 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3326 }
3327
Amith Yamasani15e472352015-04-24 19:06:07 -07003328 private boolean isUidIdle(int uid) {
3329 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3330 final int userId = UserHandle.getUserId(uid);
3331
songjinshi0655edd2016-05-18 19:55:32 +08003332 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003333 for (String packageName : packages) {
3334 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3335 return false;
3336 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003337 }
3338 }
3339 return true;
3340 }
3341
3342 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003343 * Checks if an uid has INTERNET permissions.
3344 * <p>
3345 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003346 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003347 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003348 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003349 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003350 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003351 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003352 }
3353 } catch (RemoteException e) {
3354 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003355 return true;
3356 }
3357
3358 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003359 * Clears all state - internal and external - associated with an UID.
3360 */
3361 private void onUidDeletedUL(int uid) {
3362 // First cleanup in-memory state synchronously...
3363 mUidRules.delete(uid);
3364 mUidPolicy.delete(uid);
3365 mUidFirewallStandbyRules.delete(uid);
3366 mUidFirewallDozableRules.delete(uid);
3367 mUidFirewallPowerSaveRules.delete(uid);
3368 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3369 mPowerSaveWhitelistAppIds.delete(uid);
3370 mPowerSaveTempWhitelistAppIds.delete(uid);
3371
3372 // ...then update iptables asynchronously.
3373 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3374 }
3375
3376 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003377 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003378 *
Felipe Leme781ba142016-05-09 16:24:48 -07003379 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003380 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003381 * <li>Doze mode
3382 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003383 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003384 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003385 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003386 *
3387 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003388 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003389 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003390 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003391 updateRuleForDeviceIdleUL(uid);
3392 updateRuleForAppIdleUL(uid);
3393 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003394
3395 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003396 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003397
3398 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003399 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003400 }
3401
Felipe Leme70c57c22016-03-29 10:45:13 -07003402 /**
3403 * Applies network rules to bandwidth controllers based on process state and user-defined
3404 * restrictions (blacklist / whitelist).
3405 *
3406 * <p>
3407 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3408 * networks:
3409 * <ul>
3410 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3411 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3412 * also blacklisted.
3413 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3414 * no UIDs other those whitelisted will have access.
3415 * <ul>
3416 *
3417 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3418 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3419 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3420 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003421 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003422 * {@link INetworkManagementService}, but this method should also be called in events (like
3423 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3424 * following rules should also be applied:
3425 *
3426 * <ul>
3427 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3428 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3429 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3430 * {@code bw_penalty_box}.
3431 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3432 * </ul>
3433 *
3434 * <p>For optimization, the rules are only applied on user apps that have internet access
3435 * permission, since there is no need to change the {@code iptables} rule if the app does not
3436 * have permission to use the internet.
3437 *
3438 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003439 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003440 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003441 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003442 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3443 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3444 "updateRulesForDataUsageRestrictionsUL: " + uid);
3445 }
3446 try {
3447 updateRulesForDataUsageRestrictionsULInner(uid);
3448 } finally {
3449 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3450 }
3451 }
3452
3453 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003454 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003455 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003456 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003457 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003458
Dianne Hackborn497175b2014-07-01 12:56:08 -07003459 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003460 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003461 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003462
Felipe Leme781ba142016-05-09 16:24:48 -07003463 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003464 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003465 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3466 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003467
Felipe Leme70c57c22016-03-29 10:45:13 -07003468 // First step: define the new rule based on user restrictions and foreground state.
3469 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003470 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3471 newRule = RULE_TEMPORARY_ALLOW_METERED;
3472 } else if (isWhitelisted) {
3473 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003474 }
3475 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003476 if (isBlacklisted) {
3477 newRule = RULE_REJECT_METERED;
3478 } else if (mRestrictBackground && isWhitelisted) {
3479 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003480 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003481 }
Felipe Leme781ba142016-05-09 16:24:48 -07003482 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003483
Felipe Lemef28983d2016-03-25 12:18:23 -07003484 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003485 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003486 + ": isForeground=" +isForeground
3487 + ", isBlacklisted=" + isBlacklisted
3488 + ", isWhitelisted=" + isWhitelisted
3489 + ", oldRule=" + uidRulesToString(oldRule)
3490 + ", newRule=" + uidRulesToString(newRule)
3491 + ", newUidRules=" + uidRulesToString(newUidRules)
3492 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003493 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003494
Felipe Leme46c4fc32016-05-04 09:21:43 -07003495 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003496 mUidRules.delete(uid);
3497 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003498 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003499 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003500
Felipe Leme70c57c22016-03-29 10:45:13 -07003501 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003502 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003503 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003504 // Temporarily whitelist foreground app, removing from blacklist if necessary
3505 // (since bw_penalty_box prevails over bw_happy_box).
3506
3507 setMeteredNetworkWhitelist(uid, true);
3508 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3509 // but ideally it should be just:
3510 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003511 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003512 setMeteredNetworkBlacklist(uid, false);
3513 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003514 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003515 // Remove temporary whitelist from app that is not on foreground anymore.
3516
3517 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3518 // but ideally they should be just:
3519 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3520 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003521 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003522 setMeteredNetworkWhitelist(uid, false);
3523 }
Felipe Leme781ba142016-05-09 16:24:48 -07003524 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003525 setMeteredNetworkBlacklist(uid, true);
3526 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003527 } else if (hasRule(newRule, RULE_REJECT_METERED)
3528 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003529 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003530 setMeteredNetworkBlacklist(uid, isBlacklisted);
Hugo Benichi2966c182017-03-28 17:17:13 +09003531 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003532 // Since blacklist prevails over whitelist, we need to handle the special case
3533 // where app is whitelisted and blacklisted at the same time (although such
3534 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003535 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003536 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003537 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3538 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003539 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003540 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003541 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003542 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003543 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3544 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003545 + ", whitelisted=" + isWhitelisted
3546 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003547 + ", newRule=" + uidRulesToString(newUidRules)
3548 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003549 }
Felipe Leme781ba142016-05-09 16:24:48 -07003550
Sudheer Shankac9d94072017-02-22 22:13:55 +00003551 // Dispatch changed rule to existing listeners.
3552 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003553 }
3554 }
3555
3556 /**
3557 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3558 * listeners in case of change.
3559 * <p>
3560 * There are 3 power-related rules that affects whether an app has background access on
3561 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3562 * restriction, it's added to the equivalent firewall chain:
3563 * <ul>
3564 * <li>App is idle: {@code fw_standby} firewall chain.
3565 * <li>Device is idle: {@code fw_dozable} firewall chain.
3566 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3567 * </ul>
3568 * <p>
3569 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3570 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3571 * <p>
3572 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3573 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003574 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003575 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3576
Sudheer Shankac9d94072017-02-22 22:13:55 +00003577 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003578
Sudheer Shankac9d94072017-02-22 22:13:55 +00003579 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003580 mUidRules.delete(uid);
3581 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003582 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003583 }
3584 }
3585
3586 /**
3587 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3588 *
3589 * @param uid the uid of the app to update rules for
3590 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3591 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3592 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003593 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003594 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003595 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003596 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3597 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3598 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3599 + (paroled ? "P" : "-"));
3600 }
3601 try {
3602 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3603 } finally {
3604 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3605 }
3606 }
3607
3608 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003609 if (!isUidValidForBlacklistRules(uid)) {
3610 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003611 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003612 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003613
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003614 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003615 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003616 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003617
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003618 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003619 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3620 int newRule = RULE_NONE;
3621
3622 // First step: define the new rule based on user restrictions and foreground state.
3623
3624 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3625 // by considering the foreground and non-foreground states.
3626 if (isForeground) {
3627 if (restrictMode) {
3628 newRule = RULE_ALLOW_ALL;
3629 }
3630 } else if (restrictMode) {
3631 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3632 }
3633
3634 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3635
3636 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003637 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003638 + ", isIdle: " + isIdle
3639 + ", mRestrictPower: " + mRestrictPower
3640 + ", mDeviceIdleMode: " + mDeviceIdleMode
3641 + ", isForeground=" + isForeground
3642 + ", isWhitelisted=" + isWhitelisted
3643 + ", oldRule=" + uidRulesToString(oldRule)
3644 + ", newRule=" + uidRulesToString(newRule)
3645 + ", newUidRules=" + uidRulesToString(newUidRules)
3646 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3647 }
3648
Felipe Leme781ba142016-05-09 16:24:48 -07003649 // Second step: notify listeners if state changed.
3650 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003651 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003652 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003653 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003654 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3655 } else {
3656 // All scenarios should have been covered above
3657 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3658 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003659 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003660 + ", newRule=" + uidRulesToString(newUidRules)
3661 + ", oldRule=" + uidRulesToString(oldUidRules));
3662 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003663 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003664 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003665
Sudheer Shankac9d94072017-02-22 22:13:55 +00003666 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003667 }
3668
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003669 private class AppIdleStateChangeListener
3670 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3671
3672 @Override
3673 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3674 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003675 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3676 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003677 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003678 synchronized (mUidRulesFirstLock) {
3679 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003680 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003681 }
3682 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003683 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003684 }
3685
3686 @Override
3687 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003688 synchronized (mUidRulesFirstLock) {
3689 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003690 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003691 }
3692 }
3693
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003694 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3695 if (listener != null) {
3696 try {
3697 listener.onUidRulesChanged(uid, uidRules);
3698 } catch (RemoteException ignored) {
3699 }
3700 }
3701 }
3702
3703 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3704 String[] meteredIfaces) {
3705 if (listener != null) {
3706 try {
3707 listener.onMeteredIfacesChanged(meteredIfaces);
3708 } catch (RemoteException ignored) {
3709 }
3710 }
3711 }
3712
3713 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3714 boolean restrictBackground) {
3715 if (listener != null) {
3716 try {
3717 listener.onRestrictBackgroundChanged(restrictBackground);
3718 } catch (RemoteException ignored) {
3719 }
3720 }
3721 }
3722
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003723 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3724 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003725 if (listener != null) {
3726 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003727 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003728 } catch (RemoteException ignored) {
3729 }
3730 }
3731 }
3732
Makoto Onuki8e777332017-03-28 11:25:47 -07003733 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003734 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003735 public boolean handleMessage(Message msg) {
3736 switch (msg.what) {
3737 case MSG_RULES_CHANGED: {
3738 final int uid = msg.arg1;
3739 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003740 final int length = mListeners.beginBroadcast();
3741 for (int i = 0; i < length; i++) {
3742 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3743 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003744 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003745 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003746 return true;
3747 }
3748 case MSG_METERED_IFACES_CHANGED: {
3749 final String[] meteredIfaces = (String[]) msg.obj;
3750 final int length = mListeners.beginBroadcast();
3751 for (int i = 0; i < length; i++) {
3752 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003753 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003754 }
3755 mListeners.finishBroadcast();
3756 return true;
3757 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003758 case MSG_LIMIT_REACHED: {
3759 final String iface = (String) msg.obj;
3760
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003761 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003762 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003763 if (mMeteredIfaces.contains(iface)) {
3764 try {
3765 // force stats update to make sure we have
3766 // numbers that caused alert to trigger.
3767 mNetworkStats.forceUpdate();
3768 } catch (RemoteException e) {
3769 // ignored; service lives in system_server
3770 }
3771
Felipe Lemef0823852016-06-08 13:43:08 -07003772 updateNetworkEnabledNL();
3773 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003774 }
3775 }
3776 return true;
3777 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003778 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3779 final boolean restrictBackground = msg.arg1 != 0;
3780 final int length = mListeners.beginBroadcast();
3781 for (int i = 0; i < length; i++) {
3782 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003783 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003784 }
3785 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003786 final Intent intent =
3787 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3788 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3789 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3790 return true;
3791 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003792 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003793 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003794 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003795 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003796 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07003797 final int length = mListeners.beginBroadcast();
3798 for (int i = 0; i < length; i++) {
3799 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003800 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003801 }
3802 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003803 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3804 if (notifyApp.booleanValue()) {
3805 broadcastRestrictBackgroundChanged(uid, notifyApp);
3806 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003807 return true;
3808 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003809 case MSG_ADVISE_PERSIST_THRESHOLD: {
3810 final long lowestRule = (Long) msg.obj;
3811 try {
3812 // make sure stats are recorded frequently enough; we aim
3813 // for 2MB threshold for 2GB/month rules.
3814 final long persistThreshold = lowestRule / 1000;
3815 mNetworkStats.advisePersistThreshold(persistThreshold);
3816 } catch (RemoteException e) {
3817 // ignored; service lives in system_server
3818 }
3819 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003820 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003821 case MSG_UPDATE_INTERFACE_QUOTA: {
3822 removeInterfaceQuota((String) msg.obj);
3823 // int params need to be stitched back into a long
3824 setInterfaceQuota((String) msg.obj,
3825 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3826 return true;
3827 }
3828 case MSG_REMOVE_INTERFACE_QUOTA: {
3829 removeInterfaceQuota((String) msg.obj);
3830 return true;
3831 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003832 case MSG_SET_FIREWALL_RULES: {
3833 final int chain = msg.arg1;
3834 final int toggle = msg.arg2;
3835 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3836 if (uidRules != null) {
3837 setUidFirewallRules(chain, uidRules);
3838 }
3839 if (toggle != CHAIN_TOGGLE_NONE) {
3840 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3841 }
3842 return true;
3843 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003844 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3845 resetUidFirewallRules(msg.arg1);
3846 return true;
3847 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003848 default: {
3849 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003850 }
3851 }
3852 }
Makoto Onuki8e777332017-03-28 11:25:47 -07003853 };
3854
3855 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
3856 @Override
3857 public boolean handleMessage(Message msg) {
3858 switch (msg.what) {
3859 case UID_MSG_STATE_CHANGED: {
3860 final int uid = msg.arg1;
3861 final int procState = msg.arg2;
3862 final long procStateSeq = (Long) msg.obj;
3863
3864 handleUidChanged(uid, procState, procStateSeq);
3865 return true;
3866 }
3867 case UID_MSG_GONE: {
3868 final int uid = msg.arg1;
3869 handleUidGone(uid);
3870 return true;
3871 }
3872 default: {
3873 return false;
3874 }
3875 }
3876 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003877
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003878 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003879
Makoto Onuki8e777332017-03-28 11:25:47 -07003880 void handleUidChanged(int uid, int procState, long procStateSeq) {
3881 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
3882 try {
3883 synchronized (mUidRulesFirstLock) {
3884 // We received a uid state change callback, add it to the history so that it
3885 // will be useful for debugging.
3886 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
3887 // Now update the network policy rules as per the updated uid state.
3888 updateUidStateUL(uid, procState);
3889 // Updating the network rules is done, so notify AMS about this.
3890 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
3891 }
3892 } finally {
3893 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3894 }
3895 }
3896
3897 void handleUidGone(int uid) {
3898 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
3899 try {
3900 synchronized (mUidRulesFirstLock) {
3901 removeUidStateUL(uid);
3902 }
3903 } finally {
3904 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3905 }
3906 }
3907
Felipe Leme57e3d312016-08-23 14:42:52 -07003908 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3909 final PackageManager pm = mContext.getPackageManager();
3910 final String[] packages = pm.getPackagesForUid(uid);
3911 if (packages != null) {
3912 final int userId = UserHandle.getUserId(uid);
3913 for (String packageName : packages) {
3914 final Intent intent =
3915 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3916 intent.setPackage(packageName);
3917 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3918 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3919 }
3920 }
3921 }
3922
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003923 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003924 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003925 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003926 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003927 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003928 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003929 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003930 }
3931 }
3932
3933 private void removeInterfaceQuota(String iface) {
3934 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003935 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003936 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003937 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003938 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003939 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003940 }
3941 }
3942
Felipe Leme70c57c22016-03-29 10:45:13 -07003943 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3944 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003945 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003946 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003947 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003948 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3949 } catch (RemoteException e) {
3950 // ignored; service lives in system_server
3951 }
3952 }
3953
3954 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3955 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3956 try {
3957 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3958 } catch (IllegalStateException e) {
3959 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003960 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003961 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003962 }
3963 }
3964
Felipe Lemebc853dd2016-09-08 13:26:55 -07003965 private static final int CHAIN_TOGGLE_NONE = 0;
3966 private static final int CHAIN_TOGGLE_ENABLE = 1;
3967 private static final int CHAIN_TOGGLE_DISABLE = 2;
3968 @Retention(RetentionPolicy.SOURCE)
3969 @IntDef(flag = false, value = {
3970 CHAIN_TOGGLE_NONE,
3971 CHAIN_TOGGLE_ENABLE,
3972 CHAIN_TOGGLE_DISABLE
3973 })
3974 public @interface ChainToggleType {
3975 }
3976
3977 /**
3978 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
3979 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
3980 *
3981 * @param chain firewall chain.
3982 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
3983 * @param toggle whether the chain should be enabled, disabled, or not changed.
3984 */
3985 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
3986 @ChainToggleType int toggle) {
3987 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
3988 }
3989
Amith Yamasani15e472352015-04-24 19:06:07 -07003990 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003991 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3992 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3993 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003994 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003995 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003996 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003997 int size = uidRules.size();
3998 int[] uids = new int[size];
3999 int[] rules = new int[size];
4000 for(int index = size - 1; index >= 0; --index) {
4001 uids[index] = uidRules.keyAt(index);
4002 rules[index] = uidRules.valueAt(index);
4003 }
4004 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004005 } catch (IllegalStateException e) {
4006 Log.wtf(TAG, "problem setting firewall uid rules", e);
4007 } catch (RemoteException e) {
4008 // ignored; service lives in system_server
4009 }
4010 }
4011
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004012 /**
4013 * Add or remove a uid to the firewall blacklist for all network ifaces.
4014 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004015 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004016 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4017 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4018 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004019 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004020 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004021 if (chain == FIREWALL_CHAIN_DOZABLE) {
4022 mUidFirewallDozableRules.put(uid, rule);
4023 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4024 mUidFirewallStandbyRules.put(uid, rule);
4025 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4026 mUidFirewallPowerSaveRules.put(uid, rule);
4027 }
4028
4029 try {
4030 mNetworkManager.setFirewallUidRule(chain, uid, rule);
4031 } catch (IllegalStateException e) {
4032 Log.wtf(TAG, "problem setting firewall uid rules", e);
4033 } catch (RemoteException e) {
4034 // ignored; service lives in system_server
4035 }
4036 } finally {
4037 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004038 }
4039 }
4040
4041 /**
4042 * Add or remove a uid to the firewall blacklist for all network ifaces.
4043 */
Felipe Lemef0823852016-06-08 13:43:08 -07004044 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004045 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4046 mFirewallChainStates.get(chain) == enable) {
4047 // All is the same, nothing to do.
4048 return;
4049 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004050 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004051 try {
4052 mNetworkManager.setFirewallChainEnabled(chain, enable);
4053 } catch (IllegalStateException e) {
4054 Log.wtf(TAG, "problem enable firewall chain", e);
4055 } catch (RemoteException e) {
4056 // ignored; service lives in system_server
4057 }
4058 }
4059
Felipe Leme03e95e22016-09-09 09:25:31 -07004060 /**
4061 * Resets all firewall rules associated with an UID.
4062 */
4063 private void resetUidFirewallRules(int uid) {
4064 try {
4065 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4066 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4067 mNetworkManager
4068 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4069 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4070 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4071 } catch (IllegalStateException e) {
4072 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4073 } catch (RemoteException e) {
4074 // ignored; service lives in system_server
4075 }
4076 }
4077
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004078 private long getTotalBytes(NetworkTemplate template, long start, long end) {
4079 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004080 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004081 } catch (RuntimeException e) {
4082 Slog.w(TAG, "problem reading network stats: " + e);
4083 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004084 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004085 // ignored; service lives in system_server
4086 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004087 }
4088 }
4089
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004090 private boolean isBandwidthControlEnabled() {
4091 final long token = Binder.clearCallingIdentity();
4092 try {
4093 return mNetworkManager.isBandwidthControlEnabled();
4094 } catch (RemoteException e) {
4095 // ignored; service lives in system_server
4096 return false;
4097 } finally {
4098 Binder.restoreCallingIdentity(token);
4099 }
4100 }
4101
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004102 /**
4103 * Try refreshing {@link #mTime} when stale.
4104 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07004105 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004106 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004107 mTime.forceRefresh();
4108 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004109 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004110
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004111 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004112 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
4113 }
4114
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004115 private static Intent buildAllowBackgroundDataIntent() {
4116 return new Intent(ACTION_ALLOW_BACKGROUND);
4117 }
4118
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004119 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4120 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
4121 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4122 return intent;
4123 }
4124
Wei Liu546cb772016-07-21 16:19:01 -07004125 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004126 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004127 intent.setComponent(ComponentName.unflattenFromString(
4128 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004129 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4130 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4131 return intent;
4132 }
4133
Wei Liu546cb772016-07-21 16:19:01 -07004134 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004135 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004136 intent.setComponent(ComponentName.unflattenFromString(
4137 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004138 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4139 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4140 return intent;
4141 }
4142
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004143 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004144 public void addIdleHandler(IdleHandler handler) {
4145 mHandler.getLooper().getQueue().addIdleHandler(handler);
4146 }
4147
jackqdyulei29c82ab2017-03-10 14:09:16 -08004148 @VisibleForTesting
4149 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4150 mRestrictBackgroundPowerState = result;
4151
4152 boolean restrictBackground = result.batterySaverEnabled;
4153 boolean shouldInvokeRestrictBackground;
4154 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4155 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4156
4157 if (result.globalBatterySaverEnabled) {
4158 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4159 // turn it on.
4160 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4161 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4162 localRestrictBgChangedInBsm = false;
4163 } else {
4164 // Try to restore the restrictBackground if it doesn't change in bsm
4165 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4166 restrictBackground = mRestrictBackgroundBeforeBsm;
4167 }
4168
4169 if (shouldInvokeRestrictBackground) {
4170 setRestrictBackground(restrictBackground);
4171 }
4172
4173 // Change it at last so setRestrictBackground() won't affect this variable
4174 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4175 }
4176
Jeff Sharkey1b861272011-05-22 00:34:52 -07004177 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4178 final int size = source.size();
4179 for (int i = 0; i < size; i++) {
4180 target.put(source.keyAt(i), true);
4181 }
4182 }
4183
Stuart Scottf1fb3972015-04-02 18:00:02 -07004184 @Override
4185 public void factoryReset(String subscriber) {
4186 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4187
Stuart Scotte3e314d2015-04-20 14:07:45 -07004188 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4189 return;
4190 }
4191
Stuart Scottf1fb3972015-04-02 18:00:02 -07004192 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004193 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004194 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4195 for (NetworkPolicy policy : policies) {
4196 if (policy.template.equals(template)) {
4197 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4198 policy.inferred = false;
4199 policy.clearSnooze();
4200 }
4201 }
4202 setNetworkPolicies(policies);
4203
4204 // Turn restrict background data off
4205 setRestrictBackground(false);
4206
Stuart Scotte3e314d2015-04-20 14:07:45 -07004207 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4208 // Remove app's "restrict background data" flag
4209 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4210 setUidPolicy(uid, POLICY_NONE);
4211 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004212 }
4213 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004214
Felipe Lemed17fda42016-04-29 11:12:45 -07004215 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4216
4217 @Override
4218 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004219 synchronized (mUidRulesFirstLock) {
4220 boolean changed = removeUserStateUL(userId, false);
4221 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004222 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004223 synchronized (mNetworkPoliciesSecondLock) {
4224 writePolicyAL();
4225 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004226 }
4227 }
4228 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004229
4230 /**
4231 * @return true if the given uid is restricted from doing networking on metered networks.
4232 */
4233 @Override
4234 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4235 final int uidRules;
4236 final boolean isBackgroundRestricted;
4237 synchronized (mUidRulesFirstLock) {
4238 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4239 isBackgroundRestricted = mRestrictBackground;
4240 }
4241 return isBackgroundRestricted
4242 && !hasRule(uidRules, RULE_ALLOW_METERED)
4243 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4244 }
4245
4246 /**
4247 * @return true if networking is blocked on the given interface for the given uid according
4248 * to current networking policies.
4249 */
4250 @Override
4251 public boolean isUidNetworkingBlocked(int uid, String ifname) {
4252 final int uidRules;
4253 final boolean isBackgroundRestricted;
4254 final boolean isNetworkMetered;
4255 synchronized (mUidRulesFirstLock) {
4256 uidRules = mUidRules.get(uid, RULE_NONE);
4257 isBackgroundRestricted = mRestrictBackground;
4258 synchronized (mNetworkPoliciesSecondLock) {
4259 isNetworkMetered = mMeteredIfaces.contains(ifname);
4260 }
4261 }
4262 if (hasRule(uidRules, RULE_REJECT_ALL)) {
4263 if (LOGV) logUidStatus(uid, "blocked by power restrictions");
4264 return true;
4265 }
4266 if (!isNetworkMetered) {
4267 if (LOGV) logUidStatus(uid, "allowed on unmetered network");
4268 return false;
4269 }
4270 if (hasRule(uidRules, RULE_REJECT_METERED)) {
4271 if (LOGV) logUidStatus(uid, "blacklisted on metered network");
4272 return true;
4273 }
4274 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4275 if (LOGV) logUidStatus(uid, "whitelisted on metered network");
4276 return false;
4277 }
4278 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4279 if (LOGV) logUidStatus(uid, "temporary whitelisted on metered network");
4280 return false;
4281 }
4282 if (isBackgroundRestricted) {
4283 if (LOGV) logUidStatus(uid, "blocked when background is restricted");
4284 return true;
4285 }
4286 if (LOGV) logUidStatus(uid, "allowed by default");
4287 return false;
4288 }
4289 }
4290
4291 private static boolean hasRule(int uidRules, int rule) {
4292 return (uidRules & rule) != 0;
4293 }
4294
4295 private static void logUidStatus(int uid, String descr) {
4296 Slog.d(TAG, String.format("uid %d is %s", uid, descr));
Felipe Lemed17fda42016-04-29 11:12:45 -07004297 }
Sudheer Shankae7361852017-03-07 11:51:46 -08004298
4299 /**
4300 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
4301 * (uid, procStateSeq) pairs.
4302 */
4303 @VisibleForTesting
4304 public static final class ProcStateSeqHistory {
4305 private static final int INVALID_UID = -1;
4306
4307 /**
4308 * Denotes maximum number of items this history can hold.
4309 */
4310 private final int mMaxCapacity;
4311 /**
4312 * Used for storing the uid information.
4313 */
4314 private final int[] mUids;
4315 /**
4316 * Used for storing the sequence numbers associated with {@link #mUids}.
4317 */
4318 private final long[] mProcStateSeqs;
4319 /**
4320 * Points to the next available slot for writing (uid, procStateSeq) pair.
4321 */
4322 private int mHistoryNext;
4323
4324 public ProcStateSeqHistory(int maxCapacity) {
4325 mMaxCapacity = maxCapacity;
4326 mUids = new int[mMaxCapacity];
4327 Arrays.fill(mUids, INVALID_UID);
4328 mProcStateSeqs = new long[mMaxCapacity];
4329 }
4330
4331 @GuardedBy("mUidRulesFirstLock")
4332 public void addProcStateSeqUL(int uid, long procStateSeq) {
4333 mUids[mHistoryNext] = uid;
4334 mProcStateSeqs[mHistoryNext] = procStateSeq;
4335 mHistoryNext = increaseNext(mHistoryNext, 1);
4336 }
4337
4338 @GuardedBy("mUidRulesFirstLock")
4339 public void dumpUL(IndentingPrintWriter fout) {
4340 if (mUids[0] == INVALID_UID) {
4341 fout.println("NONE");
4342 return;
4343 }
4344 int index = mHistoryNext;
4345 do {
4346 index = increaseNext(index, -1);
4347 if (mUids[index] == INVALID_UID) {
4348 break;
4349 }
4350 fout.println(getString(mUids[index], mProcStateSeqs[index]));
4351 } while (index != mHistoryNext);
4352 }
4353
4354 public static String getString(int uid, long procStateSeq) {
Sudheer Shankadb9aaf032017-06-19 19:05:31 -07004355 return "UID=" + uid + " Seq=" + procStateSeq;
Sudheer Shankae7361852017-03-07 11:51:46 -08004356 }
4357
4358 private int increaseNext(int next, int increment) {
4359 next += increment;
4360 if (next >= mMaxCapacity) {
4361 next = 0;
4362 } else if (next < 0) {
4363 next = mMaxCapacity - 1;
4364 }
4365 return next;
4366 }
4367 }
Chris Wren193ae6b2017-03-31 15:17:11 -04004368
4369 private class NotificationId {
4370 private final String mTag;
4371 private final int mId;
4372
4373 NotificationId(NetworkPolicy policy, int type) {
4374 mTag = buildNotificationTag(policy, type);
4375 mId = type;
4376 }
4377
4378 @Override
4379 public boolean equals(Object o) {
4380 if (this == o) return true;
4381 if (!(o instanceof NotificationId)) return false;
4382 NotificationId that = (NotificationId) o;
4383 return Objects.equals(mTag, that.mTag);
4384 }
4385
4386 @Override
4387 public int hashCode() {
4388 return Objects.hash(mTag);
4389 }
4390
4391 /**
4392 * Build unique tag that identifies an active {@link NetworkPolicy}
4393 * notification of a specific type, like {@link #TYPE_LIMIT}.
4394 */
4395 private String buildNotificationTag(NetworkPolicy policy, int type) {
4396 return TAG + ":" + policy.template.hashCode() + ":" + type;
4397 }
4398
4399 public String getTag() {
4400 return mTag;
4401 }
4402
4403 public int getId() {
4404 return mId;
4405 }
4406 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004407}