blob: c75e287949bc1272b3fe923587327542630d71e6 [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 Sharkey1b861272011-05-22 00:34:52 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070022import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080032import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060035import static android.net.ConnectivityManager.TYPE_MOBILE;
36import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070037import static android.net.ConnectivityManager.isNetworkTypeMobile;
38import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070039import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070040import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070041import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070042import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080044import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070045import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
46import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070047import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070048import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070049import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070050import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070051import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070052import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeydc988062015-09-14 10:09:47 -070053import static android.net.NetworkPolicyManager.RULE_UNKNOWN;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070054import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070055import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
56import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070057import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
58import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070059import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080060import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070061import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
62import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
63import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
64import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
65import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
66import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
67import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070068import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080069
Jeff Sharkey854b2b12012-04-13 16:03:40 -070070import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070071import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070072import static com.android.internal.util.XmlUtils.readBooleanAttribute;
73import static com.android.internal.util.XmlUtils.readIntAttribute;
74import static com.android.internal.util.XmlUtils.readLongAttribute;
75import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
76import static com.android.internal.util.XmlUtils.writeIntAttribute;
77import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070078import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070079import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060080
Jeff Sharkey21c9c452011-06-07 12:26:43 -070081import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080082import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070083import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070084
Dianne Hackborn88e98df2015-03-23 13:29:14 -070085import android.Manifest;
Dianne Hackborn497175b2014-07-01 12:56:08 -070086import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070087import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070088import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070089import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070090import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070091import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070092import android.app.Notification;
93import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -070094import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -070095import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070096import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070097import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070098import android.content.Intent;
99import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700100import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700101import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700102import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700103import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700104import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700105import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700106import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700107import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700108import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700109import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700110import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700111import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700112import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700113import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700114import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700115import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700116import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700117import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700118import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700119import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700120import android.net.wifi.WifiConfiguration;
121import android.net.wifi.WifiInfo;
122import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700123import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700124import android.os.Environment;
125import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700126import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700127import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700128import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700129import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700130import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700131import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700132import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700133import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700134import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700135import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600136import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700137import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700138import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700139import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700140import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800141import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700142import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700143import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700144import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700145import android.util.ArrayMap;
146import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700147import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700148import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700149import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700150import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700151import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700152import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700153import android.util.SparseBooleanArray;
154import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700155import android.util.TrustedTime;
156import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700157
Jeff Sharkey497e4432011-06-14 17:27:29 -0700158import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800159import com.android.internal.annotations.VisibleForTesting;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800160import com.android.internal.content.PackageMonitor;
Jeff Sharkey32566012014-12-02 18:30:14 -0800161import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700162import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700163import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700164import com.android.server.DeviceIdleController;
165import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700166import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800167import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600168
169import libcore.io.IoUtils;
170
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700171import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700172
173import org.xmlpull.v1.XmlPullParser;
174import org.xmlpull.v1.XmlPullParserException;
175import org.xmlpull.v1.XmlSerializer;
176
177import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700178import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700179import java.io.FileInputStream;
180import java.io.FileNotFoundException;
181import java.io.FileOutputStream;
182import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700183import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100184import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700185import java.util.ArrayList;
186import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700187import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700188
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700189/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700190 * Service that maintains low-level network policy rules, using
191 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700192 * <p>
193 * Derives active rules by combining a given policy with other system status,
194 * and delivers to listeners, such as {@link ConnectivityManager}, for
195 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700196 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700197public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800198 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700199 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700200 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700201
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700202 private static final int VERSION_INIT = 1;
203 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700204 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800205 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800206 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800207 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700208 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700209 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700210 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700211 private static final int VERSION_SWITCH_UID = 10;
212 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700213
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800214 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700215 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800216 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700217 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800218 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700219 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700220
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700221 private static final String TAG_POLICY_LIST = "policy-list";
222 private static final String TAG_NETWORK_POLICY = "network-policy";
223 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700224 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800225 private static final String TAG_WHITELIST = "whitelist";
226 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800227 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700228
229 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700230 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700231 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
232 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700233 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700234 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800235 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700236 private static final String ATTR_WARNING_BYTES = "warningBytes";
237 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700238 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800239 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
240 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800241 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700242 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700243 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700244 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700245 private static final String ATTR_POLICY = "policy";
246
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800247 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800248 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800249 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800250 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700251
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700252 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
253
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700254 private static final int MSG_RULES_CHANGED = 1;
255 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800256 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800257 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700258 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700259 private static final int MSG_SCREEN_ON_CHANGED = 8;
Felipe Leme9778f762016-01-27 14:46:39 -0800260 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700261
Jeff Sharkey75279902011-05-24 18:39:45 -0700262 private final Context mContext;
263 private final IActivityManager mActivityManager;
264 private final IPowerManager mPowerManager;
265 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700266 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700267 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700268 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700269 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700270
271 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700272 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700273 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700274 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700275
Dianne Hackborn497175b2014-07-01 12:56:08 -0700276 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700277
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700278 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700279 volatile boolean mScreenOn;
280 volatile boolean mRestrictBackground;
281 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700282 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700283
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700284 private final boolean mSuppressDefaultPolicy;
285
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700286 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800287 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700288 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800289 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700290
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700291 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700292 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700293 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800294 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700295
Jeff Sharkeydc988062015-09-14 10:09:47 -0700296 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
297 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800298 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700299
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700300 /** Set of states for the child firewall chains. True if the chain is active. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700301 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
302
Jeff Sharkey32566012014-12-02 18:30:14 -0800303 /**
304 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700305 * in power save mode, except device idle (doze) still applies.
306 * TODO: An int array might be sufficient
307 */
308 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
309
310 /**
311 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800312 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700313 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800314 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700315 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700316
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700317 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
318
Felipe Lemeb85a6372016-01-14 16:16:16 -0800319 /**
320 * UIDs that have been white-listed to avoid restricted background.
321 */
322 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
323
Felipe Lemea9505cc2016-02-26 10:28:41 -0800324 /**
325 * UIDs that have been initially white-listed by system to avoid restricted background.
326 */
327 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
328 new SparseBooleanArray();
329
330 /**
331 * UIDs that have been initially white-listed by system to avoid restricted background,
332 * but later revoked by user.
333 */
334 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
335 new SparseBooleanArray();
336
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700337 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800338 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700339 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800340 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700341
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700342 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700343 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700344
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700345 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800346 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700347
Jeff Sharkey32566012014-12-02 18:30:14 -0800348 private final RemoteCallbackList<INetworkPolicyListener>
349 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700350
Dianne Hackborn497175b2014-07-01 12:56:08 -0700351 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700352
353 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700354
Svet Ganov16a16892015-04-16 10:32:04 -0700355 private final AppOpsManager mAppOps;
356
Felipe Lemeb85a6372016-01-14 16:16:16 -0800357 private final MyPackageMonitor mPackageMonitor;
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800358 private final IPackageManager mIPm;
359
Felipe Lemeb85a6372016-01-14 16:16:16 -0800360
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700361 // TODO: keep whitelist of system-critical services that should never have
362 // rules enforced, such as system, phone, and radio UIDs.
363
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700364 // TODO: migrate notifications to SystemUI
365
Jeff Sharkey75279902011-05-24 18:39:45 -0700366 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700367 IPowerManager powerManager, INetworkStatsService networkStats,
368 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700369 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700370 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700371 }
372
373 private static File getSystemDir() {
374 return new File(Environment.getDataDirectory(), "system");
375 }
376
377 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700378 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700379 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
380 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700381 mContext = checkNotNull(context, "missing context");
382 mActivityManager = checkNotNull(activityManager, "missing activityManager");
383 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700384 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700385 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700386 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700387 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700388 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700389 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800390 mIPm = AppGlobals.getPackageManager();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700391
Amith Yamasani450a16b2013-09-18 16:28:50 -0700392 HandlerThread thread = new HandlerThread(TAG);
393 thread.start();
394 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700395
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700396 mSuppressDefaultPolicy = suppressDefaultPolicy;
397
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700398 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700399
400 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800401
402 mPackageMonitor = new MyPackageMonitor();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700403 }
404
405 public void bindConnectivityManager(IConnectivityManager connManager) {
406 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700407 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700408
Jeff Sharkey497e4432011-06-14 17:27:29 -0700409 public void bindNotificationManager(INotificationManager notifManager) {
410 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
411 }
412
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700413 void updatePowerSaveWhitelistLocked() {
414 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700415 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
416 mPowerSaveWhitelistExceptIdleAppIds.clear();
417 if (whitelist != null) {
418 for (int uid : whitelist) {
419 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
420 }
421 }
422 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700423 mPowerSaveWhitelistAppIds.clear();
424 if (whitelist != null) {
425 for (int uid : whitelist) {
426 mPowerSaveWhitelistAppIds.put(uid, true);
427 }
428 }
429 } catch (RemoteException e) {
430 }
431 }
432
Felipe Lemea9505cc2016-02-26 10:28:41 -0800433 /**
434 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
435 * revoke the whitelist.
436 *
437 * @return whether any uid has been added to {@link #mRestrictBackgroundWhitelistUids}.
438 */
439 boolean addDefaultRestrictBackgroundWhitelistUids() {
440 final SystemConfig sysConfig = SystemConfig.getInstance();
441 final PackageManager pm = mContext.getPackageManager();
442 final List<UserInfo> users = mUserManager.getUsers();
443 final int numberUsers = users.size();
444
445 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
446 boolean changed = false;
447 for (int i = 0; i < allowDataUsage.size(); i++) {
448 final String pkg = allowDataUsage.valueAt(i);
449 if (LOGD)
450 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg);
451 final ApplicationInfo app;
452 try {
453 app = pm.getApplicationInfo(pkg, PackageManager.MATCH_SYSTEM_ONLY);
454 } catch (PackageManager.NameNotFoundException e) {
455 // Should not happen
456 Slog.wtf(TAG, "No ApplicationInfo for package " + pkg);
457 continue;
458 }
459 if (!app.isPrivilegedApp()) {
460 Slog.w(TAG, "getAllowInDataUsageSave() returned non-privileged app: " + pkg);
461 continue;
462 }
463 for (int j = 0; j < numberUsers; j++) {
464 final UserInfo user = users.get(i);
465 final int uid = UserHandle.getUid(user.id, app.uid);
466 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
467 if (LOGD) Slog.d(TAG, "revoked whistelist status for uid " + uid + ": "
468 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
469 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
470 Slog.i(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
471 + user.id + ") to restrict background whitelist");
472 mRestrictBackgroundWhitelistUids.append(uid, true);
473 changed = true;
474 }
475 }
476 }
477 return changed;
478 }
479
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700480 void updatePowerSaveTempWhitelistLocked() {
481 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700482 // Clear the states of the current whitelist
483 final int N = mPowerSaveTempWhitelistAppIds.size();
484 for (int i = 0; i < N; i++) {
485 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
486 }
487 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700488 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700489 if (whitelist != null) {
490 for (int uid : whitelist) {
491 mPowerSaveTempWhitelistAppIds.put(uid, true);
492 }
493 }
494 } catch (RemoteException e) {
495 }
496 }
497
Amith Yamasani06f08062015-06-12 13:23:33 -0700498 /**
499 * Remove unnecessary entries in the temp whitelist
500 */
501 void purgePowerSaveTempWhitelistLocked() {
502 final int N = mPowerSaveTempWhitelistAppIds.size();
503 for (int i = N - 1; i >= 0; i--) {
504 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
505 mPowerSaveTempWhitelistAppIds.removeAt(i);
506 }
507 }
508 }
509
Jeff Sharkeya4620792011-05-20 15:29:23 -0700510 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700511 if (!isBandwidthControlEnabled()) {
512 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
513 return;
514 }
515
Amith Yamasani15e472352015-04-24 19:06:07 -0700516 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
517
Felipe Lemeb85a6372016-01-14 16:16:16 -0800518 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
519
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700520 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700521 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700522 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
523 mPowerManagerInternal.registerLowPowerModeObserver(
524 new PowerManagerInternal.LowPowerModeListener() {
525 @Override
526 public void onLowPowerModeChanged(boolean enabled) {
Felipe Leme011b98f2016-02-10 17:28:31 -0800527 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700528 synchronized (mRulesLock) {
529 if (mRestrictPower != enabled) {
530 mRestrictPower = enabled;
Felipe Leme011b98f2016-02-10 17:28:31 -0800531 updateRulesForRestrictPowerLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700532 updateRulesForGlobalChangeLocked(true);
533 }
534 }
535 }
536 });
537 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700538 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700539
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700540 // read policy from disk
541 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700542
Felipe Lemea9505cc2016-02-26 10:28:41 -0800543 if (addDefaultRestrictBackgroundWhitelistUids()) {
544 writePolicyLocked();
545 }
546
Jeff Sharkeydc988062015-09-14 10:09:47 -0700547 updateRulesForGlobalChangeLocked(false);
548 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700549 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700550
Jeff Sharkeya4620792011-05-20 15:29:23 -0700551 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700552
Jeff Sharkeya4620792011-05-20 15:29:23 -0700553 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700554 mActivityManager.registerUidObserver(mUidObserver,
555 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700556 mNetworkManager.registerObserver(mAlertObserver);
557 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700558 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700559 }
560
Jeff Sharkeya4620792011-05-20 15:29:23 -0700561 // TODO: traverse existing processes to know foreground state, or have
562 // activitymanager dispatch current state when new observer attached.
563
564 final IntentFilter screenFilter = new IntentFilter();
565 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
566 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700567 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700568
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700569 // listen for changes to power save whitelist
570 final IntentFilter whitelistFilter = new IntentFilter(
571 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
572 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
573
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700574 DeviceIdleController.LocalService deviceIdleService
575 = LocalServices.getService(DeviceIdleController.LocalService.class);
576 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
577
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700578 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900579 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700580 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
581
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700582 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700583 final IntentFilter packageFilter = new IntentFilter();
584 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700585 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700586 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700587
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700588 // listen for UID changes to update policy
589 mContext.registerReceiver(
590 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
591
592 // listen for user changes to update policy
593 final IntentFilter userFilter = new IntentFilter();
594 userFilter.addAction(ACTION_USER_ADDED);
595 userFilter.addAction(ACTION_USER_REMOVED);
596 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
597
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700598 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700599 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
600 mContext.registerReceiver(
601 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
602
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700603 // listen for restrict background changes from notifications
604 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
605 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
606
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800607 // listen for snooze warning from notifications
608 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
609 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
610 MANAGE_NETWORK_POLICY, mHandler);
611
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700612 // listen for configured wifi networks to be removed
613 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700614 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700615
616 // listen for wifi state changes to catch metered hint
617 final IntentFilter wifiStateFilter = new IntentFilter(
618 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700619 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700620
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700621 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700622
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700623 }
624
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700625 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700626 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700627 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700628 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700629 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700630 }
631
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700632 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700633 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700634 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700635 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700636 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700637
638 @Override public void onUidActive(int uid) throws RemoteException {
639 }
640
641 @Override public void onUidIdle(int uid) throws RemoteException {
642 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700643 };
644
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700645 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700646 @Override
647 public void onReceive(Context context, Intent intent) {
648 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
649 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700650 updatePowerSaveWhitelistLocked();
651 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700652 }
653 }
654 };
655
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700656 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
657 @Override
658 public void run() {
659 synchronized (mRulesLock) {
660 updatePowerSaveTempWhitelistLocked();
661 updateRulesForTempWhitelistChangeLocked();
662 purgePowerSaveTempWhitelistLocked();
663 }
664 }
665 };
666
667 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700668 @Override
669 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800670 // screen-related broadcasts are protected by system, no need
671 // for permissions check.
672 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700673 }
674 };
675
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700676 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700677 @Override
678 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700679 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700680
681 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700682 final int uid = intent.getIntExtra(EXTRA_UID, -1);
683 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700684
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700685 if (ACTION_PACKAGE_ADDED.equals(action)) {
686 // update rules for UID, since it might be subject to
687 // global background data policy
688 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
689 synchronized (mRulesLock) {
Felipe Lemef28983d2016-03-25 12:18:23 -0700690 updateRestrictionRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700691 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700692 }
693 }
694 };
695
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700696 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700697 @Override
698 public void onReceive(Context context, Intent intent) {
699 // on background handler thread, and UID_REMOVED is protected
700
701 final int uid = intent.getIntExtra(EXTRA_UID, -1);
702 if (uid == -1) return;
703
704 // remove any policy and update rules to clean up
705 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
706 synchronized (mRulesLock) {
707 mUidPolicy.delete(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -0700708 updateRuleForRestrictBackgroundLocked(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700709 writePolicyLocked();
710 }
711 }
712 };
713
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700714 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700715 @Override
716 public void onReceive(Context context, Intent intent) {
717 // on background handler thread, and USER_ADDED and USER_REMOVED
718 // broadcasts are protected
719
720 final String action = intent.getAction();
721 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
722 if (userId == -1) return;
723
Amith Yamasani15e472352015-04-24 19:06:07 -0700724 switch (action) {
725 case ACTION_USER_REMOVED:
726 case ACTION_USER_ADDED:
727 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800728 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700729 // USER_REMOVED, and one last sanity check during USER_ADDED
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800730 removeUserStateLocked(userId);
Amith Yamasani15e472352015-04-24 19:06:07 -0700731 // Update global restrict for new user
732 updateRulesForGlobalChangeLocked(true);
733 }
734 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700735 }
736 }
737 };
738
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700739 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700740 * Receiver that watches for {@link INetworkStatsService} updates, which we
741 * use to check against {@link NetworkPolicy#warningBytes}.
742 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700743 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700744 @Override
745 public void onReceive(Context context, Intent intent) {
746 // on background handler thread, and verified
747 // READ_NETWORK_USAGE_HISTORY permission above.
748
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800749 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700750 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700751 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700752 updateNotificationsLocked();
753 }
754 }
755 };
756
757 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700758 * Receiver that watches for {@link Notification} control of
759 * {@link #mRestrictBackground}.
760 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700761 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700762 @Override
763 public void onReceive(Context context, Intent intent) {
764 // on background handler thread, and verified MANAGE_NETWORK_POLICY
765 // permission above.
766
767 setRestrictBackground(false);
768 }
769 };
770
771 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800772 * Receiver that watches for {@link Notification} control of
773 * {@link NetworkPolicy#lastWarningSnooze}.
774 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700775 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800776 @Override
777 public void onReceive(Context context, Intent intent) {
778 // on background handler thread, and verified MANAGE_NETWORK_POLICY
779 // permission above.
780
781 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
782 performSnooze(template, TYPE_WARNING);
783 }
784 };
785
786 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700787 * Receiver that watches for {@link WifiConfiguration} to be changed.
788 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700789 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700790 @Override
791 public void onReceive(Context context, Intent intent) {
792 // on background handler thread, and verified CONNECTIVITY_INTERNAL
793 // permission above.
794
795 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
796 if (reason == CHANGE_REASON_REMOVED) {
797 final WifiConfiguration config = intent.getParcelableExtra(
798 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700799 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800800 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700801 synchronized (mRulesLock) {
802 if (mNetworkPolicy.containsKey(template)) {
803 mNetworkPolicy.remove(template);
804 writePolicyLocked();
805 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700806 }
807 }
808 }
809 }
810 };
811
812 /**
813 * Receiver that watches {@link WifiInfo} state changes to infer metered
814 * state. Ignores hints when policy is user-defined.
815 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700816 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700817 @Override
818 public void onReceive(Context context, Intent intent) {
819 // on background handler thread, and verified CONNECTIVITY_INTERNAL
820 // permission above.
821
822 // ignore when not connected
823 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
824 if (!netInfo.isConnected()) return;
825
826 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
827 final boolean meteredHint = info.getMeteredHint();
828
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800829 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700830 synchronized (mRulesLock) {
831 NetworkPolicy policy = mNetworkPolicy.get(template);
832 if (policy == null && meteredHint) {
833 // policy doesn't exist, and AP is hinting that it's
834 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800835 policy = newWifiPolicy(template, meteredHint);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700836 addNetworkPolicyLocked(policy);
837
838 } else if (policy != null && policy.inferred) {
839 // policy exists, and was inferred: update its current
840 // metered state.
841 policy.metered = meteredHint;
842
843 // since this is inferred for each wifi session, just update
844 // rules without persisting.
845 updateNetworkRulesLocked();
846 }
847 }
848 }
849 };
850
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800851 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
852 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
853 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
854 metered, true);
855 }
856
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700857 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700858 * Observer that watches for {@link INetworkManagementService} alerts.
859 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700860 final private INetworkManagementEventObserver mAlertObserver
861 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700862 @Override
863 public void limitReached(String limitName, String iface) {
864 // only someone like NMS should be calling us
865 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
866
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800867 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
868 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700869 }
870 }
871 };
872
873 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700874 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
875 * to show visible notifications as needed.
876 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700877 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700878 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
879
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700880 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700881 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700882 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700883
884 // TODO: when switching to kernel notifications, compute next future
885 // cycle boundary to recompute notifications.
886
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700887 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800888 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700889 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
890 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700891 // ignore policies that aren't relevant to user
892 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700893 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700894
Jeff Sharkey497e4432011-06-14 17:27:29 -0700895 final long start = computeLastCycleBoundary(currentTime, policy);
896 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700897 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700898
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700899 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800900 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700901 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
902 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700903 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
904 notifyOverLimitLocked(policy.template);
905 }
906
Jeff Sharkey497e4432011-06-14 17:27:29 -0700907 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700908 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700909
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800910 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700911 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700912 }
913 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700914 }
915
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700916 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700917 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
918 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700919 if (!mActiveNotifs.contains(tag)) {
920 cancelNotification(tag);
921 }
922 }
923 }
924
925 /**
926 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700927 * current device state, such as when
928 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
929 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700930 */
931 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800932 if (template.isMatchRuleMobile()) {
933 final TelephonyManager tele = TelephonyManager.from(mContext);
934 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700935
Jeff Sharkey32566012014-12-02 18:30:14 -0800936 // Mobile template is relevant when any active subscriber matches
937 final int[] subIds = sub.getActiveSubscriptionIdList();
938 for (int subId : subIds) {
939 final String subscriberId = tele.getSubscriberId(subId);
940 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
941 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
942 if (template.matches(probeIdent)) {
943 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700944 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800945 }
946 return false;
947 } else {
948 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700949 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700950 }
951
952 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700953 * Notify that given {@link NetworkTemplate} is over
954 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
955 */
956 private void notifyOverLimitLocked(NetworkTemplate template) {
957 if (!mOverLimitNotified.contains(template)) {
958 mContext.startActivity(buildNetworkOverLimitIntent(template));
959 mOverLimitNotified.add(template);
960 }
961 }
962
963 private void notifyUnderLimitLocked(NetworkTemplate template) {
964 mOverLimitNotified.remove(template);
965 }
966
967 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700968 * Build unique tag that identifies an active {@link NetworkPolicy}
969 * notification of a specific type, like {@link #TYPE_LIMIT}.
970 */
971 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700972 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700973 }
974
975 /**
976 * Show notification for combined {@link NetworkPolicy} and specific type,
977 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
978 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700979 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700980 final String tag = buildNotificationTag(policy, type);
981 final Notification.Builder builder = new Notification.Builder(mContext);
982 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800983 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700984 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200985 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700986
987 final Resources res = mContext.getResources();
988 switch (type) {
989 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700990 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700991 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700992
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700993 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700994 builder.setTicker(title);
995 builder.setContentTitle(title);
996 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700997
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800998 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
999 builder.setDeleteIntent(PendingIntent.getBroadcast(
1000 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1001
1002 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001003 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001004 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1005
Jeff Sharkey497e4432011-06-14 17:27:29 -07001006 break;
1007 }
1008 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001009 final CharSequence body = res.getText(R.string.data_usage_limit_body);
1010
1011 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001012 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001013 switch (policy.template.getMatchRule()) {
1014 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001015 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001016 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001017 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001018 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001019 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001020 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001021 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001022 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001023 case MATCH_WIFI:
1024 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001025 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001026 break;
1027 default:
1028 title = null;
1029 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001030 }
1031
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001032 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001033 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001034 builder.setTicker(title);
1035 builder.setContentTitle(title);
1036 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001037
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001038 final Intent intent = buildNetworkOverLimitIntent(policy.template);
1039 builder.setContentIntent(PendingIntent.getActivity(
1040 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1041 break;
1042 }
1043 case TYPE_LIMIT_SNOOZED: {
1044 final long overBytes = totalBytes - policy.limitBytes;
1045 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
1046 Formatter.formatFileSize(mContext, overBytes));
1047
1048 final CharSequence title;
1049 switch (policy.template.getMatchRule()) {
1050 case MATCH_MOBILE_3G_LOWER:
1051 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1052 break;
1053 case MATCH_MOBILE_4G:
1054 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1055 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001056 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001057 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1058 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001059 case MATCH_WIFI:
1060 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1061 break;
1062 default:
1063 title = null;
1064 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001065 }
1066
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001067 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001068 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001069 builder.setTicker(title);
1070 builder.setContentTitle(title);
1071 builder.setContentText(body);
1072
1073 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001074 builder.setContentIntent(PendingIntent.getActivity(
1075 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001076 break;
1077 }
1078 }
1079
1080 // TODO: move to NotificationManager once we can mock it
1081 try {
1082 final String packageName = mContext.getPackageName();
1083 final int[] idReceived = new int[1];
1084 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001085 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001086 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001087 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001088 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001089 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001090 }
1091 }
1092
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001093 private void cancelNotification(String tag) {
1094 // TODO: move to NotificationManager once we can mock it
1095 try {
1096 final String packageName = mContext.getPackageName();
1097 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001098 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001099 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001100 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001101 }
1102 }
1103
1104 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001105 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001106 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001107 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001108 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001109 @Override
1110 public void onReceive(Context context, Intent intent) {
1111 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1112 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001113
1114 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001115 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001116 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001117 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001118 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001119 updateNetworkRulesLocked();
1120 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001121 }
1122 }
1123 };
1124
1125 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001126 * Proactively control network data connections when they exceed
1127 * {@link NetworkPolicy#limitBytes}.
1128 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001129 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001130 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1131
1132 // TODO: reset any policy-disabled networks when any policy is removed
1133 // completely, which is currently rare case.
1134
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001135 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001136 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1137 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001138 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001139 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001140 setNetworkTemplateEnabled(policy.template, true);
1141 continue;
1142 }
1143
1144 final long start = computeLastCycleBoundary(currentTime, policy);
1145 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001146 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001147
1148 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001149 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1150 && policy.lastLimitSnooze < start;
1151 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001152
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001153 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001154 }
1155 }
1156
1157 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001158 * Proactively disable networks that match the given
1159 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001160 */
1161 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001162 // TODO: reach into ConnectivityManager to proactively disable bringing
1163 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001164 }
1165
1166 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001167 * Examine all connected {@link NetworkState}, looking for
1168 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1169 * remaining quota based on usage cycle and historical stats.
1170 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001171 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001172 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001173
1174 final NetworkState[] states;
1175 try {
1176 states = mConnManager.getAllNetworkState();
1177 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001178 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001179 return;
1180 }
1181
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001182 // First, generate identities of all connected networks so we can
1183 // quickly compare them against all defined policies below.
1184 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001185 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001186 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001187 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001188 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001189
1190 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001191 if (baseIface != null) {
1192 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001193 }
1194
1195 // Stacked interfaces are considered to have same identity as
1196 // their parent network.
1197 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1198 for (LinkProperties stackedLink : stackedLinks) {
1199 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001200 if (stackedIface != null) {
1201 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001202 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001203 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001204 }
1205 }
1206
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001207 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001208 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001209 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001210 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001211 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001212
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001213 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001214 for (int j = connIdents.size() - 1; j >= 0; j--) {
1215 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1216 if (policy.template.matches(ident.second)) {
1217 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001218 }
1219 }
1220
1221 if (ifaceList.size() > 0) {
1222 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001223 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001224 }
1225 }
1226
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001227 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001228 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001229
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001230 // apply each policy that we found ifaces for; compute remaining data
1231 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001232 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001233 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1234 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1235 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001236
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001237 final long start;
1238 final long totalBytes;
1239 if (policy.hasCycle()) {
1240 start = computeLastCycleBoundary(currentTime, policy);
1241 totalBytes = getTotalBytes(policy.template, start, currentTime);
1242 } else {
1243 start = Long.MAX_VALUE;
1244 totalBytes = 0;
1245 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001246
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001247 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001248 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001249 }
1250
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001251 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001252 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001253 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001254 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001255 if (!hasLimit) {
1256 // metered network, but no policy limit; we still need to
1257 // restrict apps, so push really high quota.
1258 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001259 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001260 // snoozing past quota, but we still need to restrict apps,
1261 // so push really high quota.
1262 quotaBytes = Long.MAX_VALUE;
1263 } else {
1264 // remaining "quota" bytes are based on total usage in
1265 // current cycle. kernel doesn't like 0-byte rules, so we
1266 // set 1-byte quota and disable the radio later.
1267 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1268 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001269
1270 if (ifaces.length > 1) {
1271 // TODO: switch to shared quota once NMS supports
1272 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001273 }
1274
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001275 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001276 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001277 setInterfaceQuota(iface, quotaBytes);
1278 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001279 }
1280 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001281
1282 // keep track of lowest warning or limit of active policies
1283 if (hasWarning && policy.warningBytes < lowestRule) {
1284 lowestRule = policy.warningBytes;
1285 }
1286 if (hasLimit && policy.limitBytes < lowestRule) {
1287 lowestRule = policy.limitBytes;
1288 }
1289 }
1290
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001291 for (int i = connIfaces.size()-1; i >= 0; i--) {
1292 String iface = connIfaces.valueAt(i);
1293 removeInterfaceQuota(iface);
1294 setInterfaceQuota(iface, Long.MAX_VALUE);
1295 newMeteredIfaces.add(iface);
1296 }
1297
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001298 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001299
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001300 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001301 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1302 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001303 if (!newMeteredIfaces.contains(iface)) {
1304 removeInterfaceQuota(iface);
1305 }
1306 }
1307 mMeteredIfaces = newMeteredIfaces;
1308
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001309 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001310 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001311 }
1312
1313 /**
1314 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1315 * have at least a default mobile policy defined.
1316 */
1317 private void ensureActiveMobilePolicyLocked() {
1318 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001319 if (mSuppressDefaultPolicy) return;
1320
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001321 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001322 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001323
Jeff Sharkey32566012014-12-02 18:30:14 -08001324 final int[] subIds = sub.getActiveSubscriptionIdList();
1325 for (int subId : subIds) {
1326 final String subscriberId = tele.getSubscriberId(subId);
1327 ensureActiveMobilePolicyLocked(subscriberId);
1328 }
1329 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001330
Jeff Sharkey32566012014-12-02 18:30:14 -08001331 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1332 // Poke around to see if we already have a policy
1333 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1334 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1335 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1336 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1337 if (template.matches(probeIdent)) {
1338 if (LOGD) {
1339 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1340 + NetworkIdentity.scrubSubscriberId(subscriberId));
1341 }
1342 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001343 }
1344 }
1345
Jeff Sharkey32566012014-12-02 18:30:14 -08001346 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1347 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001348
Jeff Sharkey32566012014-12-02 18:30:14 -08001349 // Build default mobile policy, and assume usage cycle starts today
1350 final long warningBytes = mContext.getResources().getInteger(
1351 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001352
Jeff Sharkey32566012014-12-02 18:30:14 -08001353 final Time time = new Time();
1354 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001355
Jeff Sharkey32566012014-12-02 18:30:14 -08001356 final int cycleDay = time.monthDay;
1357 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001358
Jeff Sharkey32566012014-12-02 18:30:14 -08001359 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1360 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1361 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1362 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001363 }
1364
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001365 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001366 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001367
1368 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001369 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001370 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001371
1372 FileInputStream fis = null;
1373 try {
1374 fis = mPolicyFile.openRead();
1375 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001376 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001377
1378 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001379 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001380 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001381 while ((type = in.next()) != END_DOCUMENT) {
1382 final String tag = in.getName();
1383 if (type == START_TAG) {
1384 if (TAG_POLICY_LIST.equals(tag)) {
1385 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001386 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1387 mRestrictBackground = readBooleanAttribute(
1388 in, ATTR_RESTRICT_BACKGROUND);
1389 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001390 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001391 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001392
1393 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1394 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1395 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001396 final String networkId;
1397 if (version >= VERSION_ADDED_NETWORK_ID) {
1398 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1399 } else {
1400 networkId = null;
1401 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001402 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001403 final String cycleTimezone;
1404 if (version >= VERSION_ADDED_TIMEZONE) {
1405 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1406 } else {
1407 cycleTimezone = Time.TIMEZONE_UTC;
1408 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001409 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1410 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001411 final long lastLimitSnooze;
1412 if (version >= VERSION_SPLIT_SNOOZE) {
1413 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1414 } else if (version >= VERSION_ADDED_SNOOZE) {
1415 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001416 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001417 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001418 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001419 final boolean metered;
1420 if (version >= VERSION_ADDED_METERED) {
1421 metered = readBooleanAttribute(in, ATTR_METERED);
1422 } else {
1423 switch (networkTemplate) {
1424 case MATCH_MOBILE_3G_LOWER:
1425 case MATCH_MOBILE_4G:
1426 case MATCH_MOBILE_ALL:
1427 metered = true;
1428 break;
1429 default:
1430 metered = false;
1431 }
1432 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001433 final long lastWarningSnooze;
1434 if (version >= VERSION_SPLIT_SNOOZE) {
1435 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1436 } else {
1437 lastWarningSnooze = SNOOZE_NEVER;
1438 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001439 final boolean inferred;
1440 if (version >= VERSION_ADDED_INFERRED) {
1441 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1442 } else {
1443 inferred = false;
1444 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001445
Jeff Sharkey32566012014-12-02 18:30:14 -08001446 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1447 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001448 if (template.isPersistable()) {
1449 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1450 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1451 lastLimitSnooze, metered, inferred));
1452 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001453
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001454 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001455 final int uid = readIntAttribute(in, ATTR_UID);
1456 final int policy = readIntAttribute(in, ATTR_POLICY);
1457
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001458 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001459 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001460 } else {
1461 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1462 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001463 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001464 final int appId = readIntAttribute(in, ATTR_APP_ID);
1465 final int policy = readIntAttribute(in, ATTR_POLICY);
1466
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001467 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001468 // app policy is deprecated so this is only used in pre system user split.
1469 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001470 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001471 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001472 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001473 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001474 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001475 } else if (TAG_WHITELIST.equals(tag)) {
1476 insideWhitelist = true;
1477 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1478 final int uid = readIntAttribute(in, ATTR_UID);
1479 mRestrictBackgroundWhitelistUids.put(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001480 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1481 final int uid = readIntAttribute(in, ATTR_UID);
1482 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001483 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001484 } else if (type == END_TAG) {
1485 if (TAG_WHITELIST.equals(tag)) {
1486 insideWhitelist = false;
1487 }
1488
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001489 }
1490 }
1491
1492 } catch (FileNotFoundException e) {
1493 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001494 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001495 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001496 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001497 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001498 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001499 } finally {
1500 IoUtils.closeQuietly(fis);
1501 }
1502 }
1503
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001504 /**
1505 * Upgrade legacy background data flags, notifying listeners of one last
1506 * change to always-true.
1507 */
1508 private void upgradeLegacyBackgroundData() {
1509 mRestrictBackground = Settings.Secure.getInt(
1510 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1511
1512 // kick off one last broadcast if restricted
1513 if (mRestrictBackground) {
1514 final Intent broadcast = new Intent(
1515 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001516 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001517 }
1518 }
1519
Dianne Hackborn497175b2014-07-01 12:56:08 -07001520 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001521 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001522
1523 FileOutputStream fos = null;
1524 try {
1525 fos = mPolicyFile.startWrite();
1526
1527 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001528 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001529 out.startDocument(null, true);
1530
1531 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001532 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001533 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001534
1535 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001536 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1537 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001538 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001539 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001540
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001541 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001542 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1543 final String subscriberId = template.getSubscriberId();
1544 if (subscriberId != null) {
1545 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001546 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001547 final String networkId = template.getNetworkId();
1548 if (networkId != null) {
1549 out.attribute(null, ATTR_NETWORK_ID, networkId);
1550 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001551 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001552 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001553 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1554 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001555 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1556 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001557 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001558 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001559 out.endTag(null, TAG_NETWORK_POLICY);
1560 }
1561
1562 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001563 for (int i = 0; i < mUidPolicy.size(); i++) {
1564 final int uid = mUidPolicy.keyAt(i);
1565 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001566
Jeff Sharkey497e4432011-06-14 17:27:29 -07001567 // skip writing empty policies
1568 if (policy == POLICY_NONE) continue;
1569
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001570 out.startTag(null, TAG_UID_POLICY);
1571 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001572 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001573 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001574 }
1575
1576 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001577
1578 // write all whitelists
1579 out.startTag(null, TAG_WHITELIST);
1580
1581 // restrict background whitelist
Felipe Lemea9505cc2016-02-26 10:28:41 -08001582 int size = mRestrictBackgroundWhitelistUids.size();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001583 for (int i = 0; i < size; i++) {
1584 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1585 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1586 writeIntAttribute(out, ATTR_UID, uid);
1587 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1588 }
1589
Felipe Lemea9505cc2016-02-26 10:28:41 -08001590 // revoked restrict background whitelist
1591 size = mRestrictBackgroundWhitelistRevokedUids.size();
1592 for (int i = 0; i < size; i++) {
1593 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1594 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1595 writeIntAttribute(out, ATTR_UID, uid);
1596 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1597 }
1598
Felipe Lemeb85a6372016-01-14 16:16:16 -08001599 out.endTag(null, TAG_WHITELIST);
1600
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001601 out.endDocument();
1602
1603 mPolicyFile.finishWrite(fos);
1604 } catch (IOException e) {
1605 if (fos != null) {
1606 mPolicyFile.failWrite(fos);
1607 }
1608 }
1609 }
1610
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001611 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001612 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001613 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001614
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001615 if (!UserHandle.isApp(uid)) {
1616 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001617 }
1618
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001619 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001620 final long token = Binder.clearCallingIdentity();
1621 try {
1622 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1623 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001624 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001625 }
1626 } finally {
1627 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001628 }
1629 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001630 }
1631
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001632 @Override
1633 public void addUidPolicy(int uid, int policy) {
1634 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001635
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001636 if (!UserHandle.isApp(uid)) {
1637 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1638 }
1639
1640 synchronized (mRulesLock) {
1641 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1642 policy |= oldPolicy;
1643 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001644 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001645 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001646 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001647 }
1648
1649 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001650 public void removeUidPolicy(int uid, int policy) {
1651 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1652
1653 if (!UserHandle.isApp(uid)) {
1654 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1655 }
1656
1657 synchronized (mRulesLock) {
1658 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1659 policy = oldPolicy & ~policy;
1660 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001661 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001662 }
1663 }
1664 }
1665
Felipe Leme923845f2016-03-02 13:42:48 -08001666 private void setUidPolicyUncheckedLocked(int uid, int oldPolicy, int policy, boolean persist) {
1667 setUidPolicyUncheckedLocked(uid, policy, persist);
1668
1669 // Checks if app was added or removed to the blacklist.
1670 if ((oldPolicy == POLICY_NONE && policy == POLICY_REJECT_METERED_BACKGROUND)
1671 || (oldPolicy == POLICY_REJECT_METERED_BACKGROUND && policy == POLICY_NONE)) {
1672 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 0)
1673 .sendToTarget();
1674 }
1675 }
1676
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001677 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1678 mUidPolicy.put(uid, policy);
1679
1680 // uid policy changed, recompute rules and persist policy.
Felipe Lemef28983d2016-03-25 12:18:23 -07001681 updateRuleForRestrictBackgroundLocked(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001682 if (persist) {
1683 writePolicyLocked();
1684 }
1685 }
1686
1687 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001688 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001689 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1690
Jeff Sharkeya4620792011-05-20 15:29:23 -07001691 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001692 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001693 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001694 }
1695
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001696 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001697 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001698 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1699
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001700 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001701 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001702 for (int i = 0; i < mUidPolicy.size(); i++) {
1703 final int uid = mUidPolicy.keyAt(i);
1704 final int uidPolicy = mUidPolicy.valueAt(i);
1705 if (uidPolicy == policy) {
1706 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001707 }
1708 }
1709 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001710 return uids;
1711 }
1712
1713 /**
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001714 * Remove any persistable state associated with given {@link UserHandle}, persisting
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001715 * if any changes are made.
1716 */
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001717 void removeUserStateLocked(int userId) {
1718 if (LOGV) Slog.v(TAG, "removeUserStateLocked()");
1719 boolean writePolicy = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001720
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001721 // Remove entries from restricted background UID whitelist
1722 int[] wlUids = new int[0];
1723 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1724 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1725 if (UserHandle.getUserId(uid) == userId) {
1726 wlUids = appendInt(wlUids, uid);
1727 }
1728 }
1729
1730 if (wlUids.length > 0) {
1731 for (int uid : wlUids) {
1732 removeRestrictBackgroundWhitelistedUidLocked(uid, false);
1733 }
1734 writePolicy = true;
1735 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001736 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001737 int[] uids = new int[0];
1738 for (int i = 0; i < mUidPolicy.size(); i++) {
1739 final int uid = mUidPolicy.keyAt(i);
1740 if (UserHandle.getUserId(uid) == userId) {
1741 uids = appendInt(uids, uid);
1742 }
1743 }
1744
1745 if (uids.length > 0) {
1746 for (int uid : uids) {
1747 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001748 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001749 writePolicy = true;
1750 }
1751
Felipe Leme76010a32016-03-17 13:03:11 -07001752 updateRulesForGlobalChangeLocked(true);
1753
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001754 if (writePolicy) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001755 writePolicyLocked();
1756 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001757 }
1758
1759 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001760 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001761 // TODO: create permission for observing network policy
1762 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1763
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001764 mListeners.register(listener);
1765
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001766 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001767 }
1768
1769 @Override
1770 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001771 // TODO: create permission for observing network policy
1772 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1773
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001774 mListeners.unregister(listener);
1775 }
1776
Jeff Sharkey1b861272011-05-22 00:34:52 -07001777 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001778 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001779 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1780
Felipe Leme6a05eee2016-02-19 14:43:51 -08001781 final long token = Binder.clearCallingIdentity();
1782 try {
1783 maybeRefreshTrustedTime();
1784 synchronized (mRulesLock) {
1785 normalizePoliciesLocked(policies);
1786 updateNetworkEnabledLocked();
1787 updateNetworkRulesLocked();
1788 updateNotificationsLocked();
1789 writePolicyLocked();
1790 }
1791 } finally {
1792 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001793 }
1794 }
1795
Dianne Hackborn497175b2014-07-01 12:56:08 -07001796 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001797 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001798 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1799 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001800 }
1801
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001802 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001803 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001804 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001805 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001806 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1807 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1808 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001809 } catch (SecurityException e) {
1810 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001811
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001812 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1813 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1814 return new NetworkPolicy[0];
1815 }
Svet Ganov16a16892015-04-16 10:32:04 -07001816 }
1817
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001818 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001819 final int size = mNetworkPolicy.size();
1820 final NetworkPolicy[] policies = new NetworkPolicy[size];
1821 for (int i = 0; i < size; i++) {
1822 policies[i] = mNetworkPolicy.valueAt(i);
1823 }
1824 return policies;
1825 }
1826 }
1827
1828 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001829 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001830 }
1831
1832 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1833 final TelephonyManager tele = TelephonyManager.from(mContext);
1834 final String[] merged = tele.getMergedSubscriberIds();
1835
1836 mNetworkPolicy.clear();
1837 for (NetworkPolicy policy : policies) {
1838 // When two normalized templates conflict, prefer the most
1839 // restrictive policy
1840 policy.template = NetworkTemplate.normalize(policy.template, merged);
1841 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1842 if (existing == null || existing.compareTo(policy) > 0) {
1843 if (existing != null) {
1844 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1845 }
1846 mNetworkPolicy.put(policy.template, policy);
1847 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001848 }
1849 }
1850
1851 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001852 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001853 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001854
1855 final long token = Binder.clearCallingIdentity();
1856 try {
1857 performSnooze(template, TYPE_LIMIT);
1858 } finally {
1859 Binder.restoreCallingIdentity(token);
1860 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001861 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001862
Dianne Hackborn497175b2014-07-01 12:56:08 -07001863 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001864 maybeRefreshTrustedTime();
1865 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001866 synchronized (mRulesLock) {
1867 // find and snooze local policy that matches
1868 final NetworkPolicy policy = mNetworkPolicy.get(template);
1869 if (policy == null) {
1870 throw new IllegalArgumentException("unable to find policy for " + template);
1871 }
1872
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001873 switch (type) {
1874 case TYPE_WARNING:
1875 policy.lastWarningSnooze = currentTime;
1876 break;
1877 case TYPE_LIMIT:
1878 policy.lastLimitSnooze = currentTime;
1879 break;
1880 default:
1881 throw new IllegalArgumentException("unexpected type");
1882 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001883
Jeff Sharkey32566012014-12-02 18:30:14 -08001884 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001885 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001886 updateNetworkRulesLocked();
1887 updateNotificationsLocked();
1888 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001889 }
1890 }
1891
1892 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001893 public void setRestrictBackground(boolean restrictBackground) {
1894 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08001895 final long token = Binder.clearCallingIdentity();
1896 try {
1897 maybeRefreshTrustedTime();
1898 synchronized (mRulesLock) {
1899 mRestrictBackground = restrictBackground;
Felipe Lemef28983d2016-03-25 12:18:23 -07001900 updateRulesForRestrictBackgroundLocked();
Felipe Leme6a05eee2016-02-19 14:43:51 -08001901 updateNotificationsLocked();
1902 writePolicyLocked();
1903 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001904
Felipe Leme6a05eee2016-02-19 14:43:51 -08001905 } finally {
1906 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07001907 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001908
1909 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1910 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001911 }
1912
1913 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08001914 public void addRestrictBackgroundWhitelistedUid(int uid) {
1915 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08001916 if (!isUidValidForRules(uid)) return;
1917 final boolean changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001918 synchronized (mRulesLock) {
Felipe Leme47585ba2016-02-09 16:56:32 -08001919 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
1920 if (oldStatus) {
1921 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
1922 return;
1923 }
1924 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08001925 mRestrictBackgroundWhitelistUids.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001926 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
1927 && mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
1928 if (LOGD) Slog.d(TAG, "Removing uid " + uid
1929 + " from revoked restrict background whitelist");
1930 mRestrictBackgroundWhitelistRevokedUids.delete(uid);
1931 }
Felipe Leme47585ba2016-02-09 16:56:32 -08001932 changed = mRestrictBackground && !oldStatus;
1933 if (changed && hasInternetPermissions(uid)) {
1934 setUidNetworkRules(uid, false);
1935 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001936 writePolicyLocked();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001937 }
Felipe Leme47585ba2016-02-09 16:56:32 -08001938 if (changed) {
1939 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 0)
1940 .sendToTarget();
1941 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001942 }
1943
1944 @Override
1945 public void removeRestrictBackgroundWhitelistedUid(int uid) {
1946 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08001947 if (!isUidValidForRules(uid)) return;
1948 final boolean changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001949 synchronized (mRulesLock) {
Felipe Leme47585ba2016-02-09 16:56:32 -08001950 changed = removeRestrictBackgroundWhitelistedUidLocked(uid, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001951 }
Felipe Leme47585ba2016-02-09 16:56:32 -08001952 if (changed) {
1953 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 0)
1954 .sendToTarget();
1955 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001956 }
1957
Felipe Leme47585ba2016-02-09 16:56:32 -08001958 private boolean removeRestrictBackgroundWhitelistedUidLocked(int uid, boolean updateNow) {
1959 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
1960 if (!oldStatus) {
1961 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
1962 return false;
1963 }
1964 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
1965 final boolean changed = mRestrictBackground && oldStatus;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001966 mRestrictBackgroundWhitelistUids.delete(uid);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001967 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
1968 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
1969 if (LOGD) Slog.d(TAG, "Adding uid " + uid
1970 + " to revoked restrict background whitelist");
1971 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
1972 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08001973 if (updateNow) {
Felipe Leme47585ba2016-02-09 16:56:32 -08001974 if (changed && hasInternetPermissions(uid)) {
1975 setUidNetworkRules(uid, true);
1976 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001977 writePolicyLocked();
1978 }
Felipe Leme47585ba2016-02-09 16:56:32 -08001979 return changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001980 }
1981
1982 @Override
1983 public int[] getRestrictBackgroundWhitelistedUids() {
1984 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1985 synchronized (mRulesLock) {
1986 final int size = mRestrictBackgroundWhitelistUids.size();
1987 final int[] whitelist = new int[size];
1988 for (int i = 0; i < size; i++) {
1989 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
1990 }
1991 if (LOGV) {
1992 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
1993 + mRestrictBackgroundWhitelistUids);
1994 }
1995 return whitelist;
1996 }
1997 }
1998
1999 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002000 public int getRestrictBackgroundByCaller() {
2001 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2002 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002003
Felipe Leme1b103232016-01-22 09:44:57 -08002004 synchronized (mRulesLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002005 // Must clear identity because getUidPolicy() is restricted to system.
2006 final long token = Binder.clearCallingIdentity();
2007 final int policy;
2008 try {
2009 policy = getUidPolicy(uid);
2010 } finally {
2011 Binder.restoreCallingIdentity(token);
2012 }
2013 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2014 // App is blacklisted.
2015 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2016 }
Felipe Leme1b103232016-01-22 09:44:57 -08002017 if (!mRestrictBackground) {
2018 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2019 }
2020 return mRestrictBackgroundWhitelistUids.get(uid)
2021 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2022 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2023 }
2024 }
2025
2026 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002027 public boolean getRestrictBackground() {
2028 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2029
2030 synchronized (mRulesLock) {
2031 return mRestrictBackground;
2032 }
2033 }
2034
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002035 @Override
2036 public void setDeviceIdleMode(boolean enabled) {
2037 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2038
2039 synchronized (mRulesLock) {
2040 if (mDeviceIdleMode != enabled) {
2041 mDeviceIdleMode = enabled;
2042 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002043 // Device idle change means we need to rebuild rules for all
2044 // known apps, so do a global refresh.
2045 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002046 }
2047 if (enabled) {
2048 EventLogTags.writeDeviceIdleOnPhase("net");
2049 } else {
2050 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002051 }
2052 }
2053 }
2054 }
2055
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002056 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002057 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2058 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002059 if (policy.template.matches(ident)) {
2060 return policy;
2061 }
2062 }
2063 return null;
2064 }
2065
2066 @Override
2067 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2068 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2069
2070 // only returns usage summary, so we don't require caller to have
2071 // READ_NETWORK_USAGE_HISTORY.
2072 final long token = Binder.clearCallingIdentity();
2073 try {
2074 return getNetworkQuotaInfoUnchecked(state);
2075 } finally {
2076 Binder.restoreCallingIdentity(token);
2077 }
2078 }
2079
2080 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2081 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2082
2083 final NetworkPolicy policy;
2084 synchronized (mRulesLock) {
2085 policy = findPolicyForNetworkLocked(ident);
2086 }
2087
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002088 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002089 // missing policy means we can't derive useful quota info
2090 return null;
2091 }
2092
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002093 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002094
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002095 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002096 final long start = computeLastCycleBoundary(currentTime, policy);
2097 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002098 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002099
2100 // report soft and hard limits under policy
2101 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2102 : NetworkQuotaInfo.NO_LIMIT;
2103 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2104 : NetworkQuotaInfo.NO_LIMIT;
2105
2106 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2107 }
2108
Jeff Sharkey46645002011-07-27 21:11:21 -07002109 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002110 public boolean isNetworkMetered(NetworkState state) {
2111 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2112
Jeff Sharkeyf166f482012-04-30 15:59:21 -07002113 // roaming networks are always considered metered
2114 if (ident.getRoaming()) {
2115 return true;
2116 }
2117
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002118 final NetworkPolicy policy;
2119 synchronized (mRulesLock) {
2120 policy = findPolicyForNetworkLocked(ident);
2121 }
2122
2123 if (policy != null) {
2124 return policy.metered;
2125 } else {
Wei Liub8eaf452016-01-25 10:32:27 -08002126 if (state.networkInfo == null) {
2127 return false;
2128 }
2129
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002130 final int type = state.networkInfo.getType();
2131 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
2132 return true;
2133 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002134 return false;
2135 }
2136 }
2137
2138 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002139 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002140 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002141
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002142 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2143
Dianne Hackborn497175b2014-07-01 12:56:08 -07002144 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002145 for (String arg : args) {
2146 argSet.add(arg);
2147 }
2148
Jeff Sharkey1b861272011-05-22 00:34:52 -07002149 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002150 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002151 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2152 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002153 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002154
Jeff Sharkey32566012014-12-02 18:30:14 -08002155 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002156 updateNetworkEnabledLocked();
2157 updateNetworkRulesLocked();
2158 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002159 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002160
2161 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002162 return;
2163 }
2164
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002165 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07002166 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002167 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002168 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002169 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002170 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002171 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2172 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002173 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002174 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002175
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07002176 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2177
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002178 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002179 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002180 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002181 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002182 final int uid = mUidPolicy.keyAt(i);
2183 final int policy = mUidPolicy.valueAt(i);
2184 fout.print("UID=");
2185 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002186 fout.print(" policy=");
Jeff Sharkeydc988062015-09-14 10:09:47 -07002187 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002188 fout.println();
2189 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002190 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002191
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002192 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2193 if (size > 0) {
2194 fout.println("Power save whitelist (except idle) app ids:");
2195 fout.increaseIndent();
2196 for (int i = 0; i < size; i++) {
2197 fout.print("UID=");
2198 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2199 fout.print(": ");
2200 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2201 fout.println();
2202 }
2203 fout.decreaseIndent();
2204 }
2205
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002206 size = mPowerSaveWhitelistAppIds.size();
2207 if (size > 0) {
2208 fout.println("Power save whitelist app ids:");
2209 fout.increaseIndent();
2210 for (int i = 0; i < size; i++) {
2211 fout.print("UID=");
2212 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2213 fout.print(": ");
2214 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2215 fout.println();
2216 }
2217 fout.decreaseIndent();
2218 }
2219
Felipe Lemeb85a6372016-01-14 16:16:16 -08002220 size = mRestrictBackgroundWhitelistUids.size();
2221 if (size > 0) {
2222 fout.println("Restrict background whitelist uids:");
2223 fout.increaseIndent();
2224 for (int i = 0; i < size; i++) {
2225 fout.print("UID=");
2226 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2227 fout.println();
2228 }
2229 fout.decreaseIndent();
2230 }
2231
Felipe Lemea9505cc2016-02-26 10:28:41 -08002232 size = mDefaultRestrictBackgroundWhitelistUids.size();
2233 if (size > 0) {
2234 fout.println("Default restrict background whitelist uids:");
2235 fout.increaseIndent();
2236 for (int i = 0; i < size; i++) {
2237 fout.print("UID=");
2238 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2239 fout.println();
2240 }
2241 fout.decreaseIndent();
2242 }
2243
2244 size = mRestrictBackgroundWhitelistRevokedUids.size();
2245 if (size > 0) {
2246 fout.println("Default restrict background whitelist uids revoked by users:");
2247 fout.increaseIndent();
2248 for (int i = 0; i < size; i++) {
2249 fout.print("UID=");
2250 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2251 fout.println();
2252 }
2253 fout.decreaseIndent();
2254 }
2255
Jeff Sharkey1b861272011-05-22 00:34:52 -07002256 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07002257 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002258 collectKeys(mUidRules, knownUids);
2259
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002260 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002261 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002262 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002263 for (int i = 0; i < size; i++) {
2264 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002265 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07002266 fout.print(uid);
2267
Jeff Sharkeydc988062015-09-14 10:09:47 -07002268 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002269 fout.print(" state=");
2270 fout.print(state);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002271 fout.print(state <= ActivityManager.PROCESS_STATE_TOP ? " (fg)" : " (bg)");
Dianne Hackborn497175b2014-07-01 12:56:08 -07002272
Jeff Sharkeydc988062015-09-14 10:09:47 -07002273 final int rule = mUidRules.get(uid, RULE_UNKNOWN);
2274 fout.print(" rule=");
Felipe Lemef28983d2016-03-25 12:18:23 -07002275 fout.print(ruleToString(rule));
Jeff Sharkey1b861272011-05-22 00:34:52 -07002276
2277 fout.println();
2278 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002279 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002280 }
2281 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002282
Felipe Lemef28983d2016-03-25 12:18:23 -07002283 private String ruleToString(int rule) {
2284 return DebugUtils.valueToString(NetworkPolicyManager.class, "RULE_", rule);
2285 }
2286
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002287 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002288 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2289 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002290 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002291 this, in, out, err, args, resultReceiver);
2292 }
2293
2294 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002295 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002296 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2297
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002298 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002299 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002300 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002301 }
2302
Felipe Lemef28983d2016-03-25 12:18:23 -07002303 private boolean isUidForegroundLocked(int uid) {
2304 return isUidStateForegroundLocked(
2305 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2306 }
2307
2308 private boolean isUidStateForegroundLocked(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002309 // only really in foreground when screen is also on
Felipe Lemef28983d2016-03-25 12:18:23 -07002310 return mScreenOn && state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002311 }
2312
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002313 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002314 * Process state of UID changed; if needed, will trigger
Felipe Leme76010a32016-03-17 13:03:11 -07002315 * {@link #updateRestrictDataRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002316 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002317 private void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002318 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2319 if (oldUidState != uidState) {
2320 // state changed, push updated rules
2321 mUidState.put(uid, uidState);
Felipe Lemef28983d2016-03-25 12:18:23 -07002322 updateRestrictBackgroundRulesOnUidStatusChangedLocked(uid, oldUidState, uidState);
Felipe Leme011b98f2016-02-10 17:28:31 -08002323 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2324 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2325 if (mDeviceIdleMode) {
2326 updateRuleForDeviceIdleLocked(uid);
2327 }
2328 if (mRestrictPower) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002329 updateRuleForRestrictPowerLocked(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002330 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002331 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002332 updateNetworkStats(uid, isUidStateForegroundLocked(uidState));
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002333 }
2334 }
2335
Felipe Lemef28983d2016-03-25 12:18:23 -07002336 private void removeUidStateLocked(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002337 final int index = mUidState.indexOfKey(uid);
2338 if (index >= 0) {
2339 final int oldUidState = mUidState.valueAt(index);
2340 mUidState.removeAt(index);
2341 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002342 updateRestrictBackgroundRulesOnUidStatusChangedLocked(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002343 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002344 if (mDeviceIdleMode) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002345 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002346 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002347 if (mRestrictPower) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002348 updateRuleForRestrictPowerLocked(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002349 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002350 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002351 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002352 }
2353 }
2354
Felipe Lemef28983d2016-03-25 12:18:23 -07002355 // adjust stats accounting based on foreground status
2356 private void updateNetworkStats(int uid, boolean uidForeground) {
2357 try {
2358 mNetworkStats.setUidForeground(uid, uidForeground);
2359 } catch (RemoteException e) {
2360 // ignored; service lives in system_server
2361 }
2362 }
2363
2364 private void updateRestrictBackgroundRulesOnUidStatusChangedLocked(int uid, int oldUidState,
2365 int newUidState) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002366 final boolean oldForeground = oldUidState <= ActivityManager.PROCESS_STATE_TOP;
2367 final boolean newForeground = newUidState <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002368 if (oldForeground != newForeground) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002369 updateRuleForRestrictBackgroundLocked(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002370 }
2371 }
2372
Jeff Sharkeya4620792011-05-20 15:29:23 -07002373 private void updateScreenOn() {
2374 synchronized (mRulesLock) {
2375 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002376 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002377 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002378 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002379 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002380 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002381 }
2382 }
2383
2384 /**
2385 * Update rules that might be changed by {@link #mScreenOn} value.
2386 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002387 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002388 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002389 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002390 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002391 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002392 final int uid = mUidState.keyAt(i);
Felipe Lemef28983d2016-03-25 12:18:23 -07002393 updateRestrictionRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002394 }
2395 }
2396 }
2397
Felipe Leme011b98f2016-02-10 17:28:31 -08002398 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002399 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2400 }
2401
Felipe Leme011b98f2016-02-10 17:28:31 -08002402 void updateRulesForRestrictPowerLocked() {
2403 updateRulesForWhitelistedPowerSaveLocked(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2404 mUidFirewallPowerSaveRules);
2405 }
2406
Felipe Lemef28983d2016-03-25 12:18:23 -07002407 void updateRuleForRestrictPowerLocked(int uid) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002408 updateRulesForWhitelistedPowerSaveLocked(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
2409 }
2410
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002411 void updateRulesForDeviceIdleLocked() {
Felipe Leme011b98f2016-02-10 17:28:31 -08002412 updateRulesForWhitelistedPowerSaveLocked(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2413 mUidFirewallDozableRules);
2414 }
2415
2416 void updateRuleForDeviceIdleLocked(int uid) {
2417 updateRulesForWhitelistedPowerSaveLocked(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
2418 }
2419
Felipe Lemef28983d2016-03-25 12:18:23 -07002420 // NOTE: since both fw_dozable and fw_powersave uses the same map
2421 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Leme011b98f2016-02-10 17:28:31 -08002422 private void updateRulesForWhitelistedPowerSaveLocked(boolean enabled, int chain,
2423 SparseIntArray rules) {
2424 if (enabled) {
2425 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002426 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002427 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002428 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002429 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002430 for (int ui = users.size() - 1; ui >= 0; ui--) {
2431 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002432 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002433 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2434 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2435 int uid = UserHandle.getUid(user.id, appId);
2436 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2437 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002438 }
2439 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2440 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2441 int uid = UserHandle.getUid(user.id, appId);
2442 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2443 }
2444 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002445 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002446 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002447 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2448 }
2449 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002450 setUidFirewallRules(chain, uidRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002451 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002452
Felipe Leme011b98f2016-02-10 17:28:31 -08002453 enableFirewallChainLocked(chain, enabled);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002454 }
2455
Felipe Lemef28983d2016-03-25 12:18:23 -07002456 // NOTE: since both fw_dozable and fw_powersave uses the same map
2457 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Leme011b98f2016-02-10 17:28:31 -08002458 private void updateRulesForWhitelistedPowerSaveLocked(int uid, boolean enabled, int chain) {
2459 if (enabled) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002460 int appId = UserHandle.getAppId(uid);
2461 if (mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId)
Felipe Leme011b98f2016-02-10 17:28:31 -08002462 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2463 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002464 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002465 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002466 }
2467 }
2468 }
2469
2470 void updateRulesForAppIdleLocked() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002471 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2472 uidRules.clear();
2473
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002474 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002475 final List<UserInfo> users = mUserManager.getUsers();
2476 for (int ui = users.size() - 1; ui >= 0; ui--) {
2477 UserInfo user = users.get(ui);
2478 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2479 for (int uid : idleUids) {
2480 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002481 // quick check: if this uid doesn't have INTERNET permission, it
2482 // doesn't have network access anyway, so it is a waste to mess
2483 // with it here.
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002484 if (hasInternetPermissions(uid)) {
2485 uidRules.put(uid, FIREWALL_RULE_DENY);
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002486 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002487 }
2488 }
2489 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002490
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002491 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2492 }
2493
2494 void updateRuleForAppIdleLocked(int uid) {
2495 if (!isUidValidForRules(uid)) return;
2496
2497 int appId = UserHandle.getAppId(uid);
2498 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)) {
2499 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2500 } else {
2501 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2502 }
2503 }
2504
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002505 void updateRulesForAppIdleParoleLocked() {
2506 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2507 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002508 }
2509
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002510 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002511 * Update rules that might be changed by {@link #mRestrictBackground},
2512 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002513 */
Felipe Leme76010a32016-03-17 13:03:11 -07002514 private void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002515 long start;
2516 if (LOGD) start = System.currentTimeMillis();
2517
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002518 updateRulesForDeviceIdleLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002519 updateRulesForAppIdleLocked();
Felipe Leme011b98f2016-02-10 17:28:31 -08002520 updateRulesForRestrictPowerLocked();
Felipe Lemef28983d2016-03-25 12:18:23 -07002521 updateRulesForRestrictBackgroundLocked();
Felipe Leme76010a32016-03-17 13:03:11 -07002522
2523 // If the set of restricted networks may have changed, re-evaluate those.
2524 if (restrictedNetworksChanged) {
2525 normalizePoliciesLocked();
2526 updateNetworkRulesLocked();
2527 }
2528 if (LOGD) {
2529 final long delta = System.currentTimeMillis() - start;
2530 Slog.d(TAG, "updateRulesForGlobalChangeLocked(" + restrictedNetworksChanged + ") took "
2531 + delta + "ms");
2532 }
2533 }
2534
Felipe Lemef28983d2016-03-25 12:18:23 -07002535 private void updateRulesForRestrictBackgroundLocked() {
Felipe Leme76010a32016-03-17 13:03:11 -07002536 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002537
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002538 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002539 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002540 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002541 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS
2542 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2543 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002544
Felipe Leme03e689d2016-03-02 16:17:38 -08002545 final int usersSize = users.size();
2546 final int appsSize = apps.size();
2547 for (int i = 0; i < usersSize; i++) {
2548 final UserInfo user = users.get(i);
2549 for (int j = 0; j < appsSize; j++) {
2550 final ApplicationInfo app = apps.get(j);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002551 final int uid = UserHandle.getUid(user.id, app.uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002552 updateRuleForRestrictBackgroundLocked(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002553 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002554 }
2555
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002556 // limit data usage for some internal system services
Felipe Lemef28983d2016-03-25 12:18:23 -07002557 updateRuleForRestrictBackgroundLocked(android.os.Process.MEDIA_UID);
2558 updateRuleForRestrictBackgroundLocked(android.os.Process.DRM_UID);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002559 }
2560
Felipe Leme76010a32016-03-17 13:03:11 -07002561 private void updateRulesForTempWhitelistChangeLocked() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002562 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002563 for (int i = 0; i < users.size(); i++) {
2564 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002565 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002566 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002567 int uid = UserHandle.getUid(user.id, appId);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002568 updateRuleForAppIdleLocked(uid);
2569 updateRuleForDeviceIdleLocked(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002570 updateRuleForRestrictPowerLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002571 }
2572 }
2573 }
2574
Felipe Lemef28983d2016-03-25 12:18:23 -07002575 private boolean isUidValidForRules(int uid) {
2576 // allow rules on specific system services, and any apps (that have network access)
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002577 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Lemef28983d2016-03-25 12:18:23 -07002578 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002579 return true;
2580 }
2581
2582 return false;
2583 }
2584
Amith Yamasani15e472352015-04-24 19:06:07 -07002585 private boolean isUidIdle(int uid) {
2586 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2587 final int userId = UserHandle.getUserId(uid);
2588
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002589 if (!ArrayUtils.isEmpty(packages)) {
2590 for (String packageName : packages) {
2591 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2592 return false;
2593 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002594 }
2595 }
2596 return true;
2597 }
2598
2599 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002600 * Checks if an uid has INTERNET permissions.
2601 * <p>
2602 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002603 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002604 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002605 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002606 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002607 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002608 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002609 }
2610 } catch (RemoteException e) {
2611 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002612 return true;
2613 }
2614
2615 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002616 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002617 *
Felipe Lemef28983d2016-03-25 12:18:23 -07002618 * <p>There are currently 2 types of restriction rules:
2619 * <ul>
2620 * <li>Battery Saver Mode (also referred as power save).
2621 * <li>Data Saver Mode (formerly known as restrict background data).
2622 * </ul>
Felipe Leme47585ba2016-02-09 16:56:32 -08002623 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002624 private void updateRestrictionRulesForUidLocked(int uid) {
2625 updateRuleForRestrictPowerLocked(uid);
2626 updateRuleForRestrictBackgroundLocked(uid);
2627 }
2628
2629 private void updateRuleForRestrictBackgroundLocked(int uid) {
2630 if (!isUidValidForRules(uid)) return;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002631
Dianne Hackborn497175b2014-07-01 12:56:08 -07002632 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2633 final boolean uidForeground = isUidForegroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002634
Jeff Sharkeydc988062015-09-14 10:09:47 -07002635 // Derive active rules based on policy and active state
Felipe Leme76010a32016-03-17 13:03:11 -07002636 int newRule = RULE_ALLOW_ALL;
2637
2638 if (!uidForeground) {
2639 // If the app is not in foreground, reject access if:
2640 // - app is blacklisted by policy or
2641 // - data saver mode is and app is not whitelisted
2642 if (((uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0)
2643 || (mRestrictBackground && !mRestrictBackgroundWhitelistUids.get(uid))) {
2644 newRule = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002645 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002646 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002647
Felipe Leme76010a32016-03-17 13:03:11 -07002648 final int oldRule = mUidRules.get(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002649 if (LOGV) {
2650 Log.v(TAG, "updateRulesForRestrictBackgroundLocked(" + uid + "): oldRule = "
2651 + ruleToString(oldRule) + ", newRule = " + ruleToString(newRule));
2652 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002653
Felipe Leme76010a32016-03-17 13:03:11 -07002654 if (newRule == RULE_ALLOW_ALL) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002655 mUidRules.delete(uid);
2656 } else {
Felipe Leme76010a32016-03-17 13:03:11 -07002657 mUidRules.put(uid, newRule);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002658 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002659
Felipe Leme76010a32016-03-17 13:03:11 -07002660 if (oldRule != newRule) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002661 final boolean rejectMetered = (newRule == RULE_REJECT_METERED);
2662 setUidNetworkRules(uid, rejectMetered);
2663
2664 // dispatch changed rule to existing listeners
Felipe Leme76010a32016-03-17 13:03:11 -07002665 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newRule).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07002666 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002667
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002668 }
2669
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002670 private class AppIdleStateChangeListener
2671 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2672
2673 @Override
2674 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2675 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002676 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
2677 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002678 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002679 updateRuleForAppIdleLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002680 }
2681 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002682 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002683 }
2684
2685 @Override
2686 public void onParoleStateChanged(boolean isParoleOn) {
2687 synchronized (mRulesLock) {
2688 updateRulesForAppIdleParoleLocked();
2689 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002690 }
2691 }
2692
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002693 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002694 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002695 public boolean handleMessage(Message msg) {
2696 switch (msg.what) {
2697 case MSG_RULES_CHANGED: {
2698 final int uid = msg.arg1;
2699 final int uidRules = msg.arg2;
2700 final int length = mListeners.beginBroadcast();
2701 for (int i = 0; i < length; i++) {
2702 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2703 if (listener != null) {
2704 try {
2705 listener.onUidRulesChanged(uid, uidRules);
2706 } catch (RemoteException e) {
2707 }
2708 }
2709 }
2710 mListeners.finishBroadcast();
2711 return true;
2712 }
2713 case MSG_METERED_IFACES_CHANGED: {
2714 final String[] meteredIfaces = (String[]) msg.obj;
2715 final int length = mListeners.beginBroadcast();
2716 for (int i = 0; i < length; i++) {
2717 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2718 if (listener != null) {
2719 try {
2720 listener.onMeteredIfacesChanged(meteredIfaces);
2721 } catch (RemoteException e) {
2722 }
2723 }
2724 }
2725 mListeners.finishBroadcast();
2726 return true;
2727 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002728 case MSG_LIMIT_REACHED: {
2729 final String iface = (String) msg.obj;
2730
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002731 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002732 synchronized (mRulesLock) {
2733 if (mMeteredIfaces.contains(iface)) {
2734 try {
2735 // force stats update to make sure we have
2736 // numbers that caused alert to trigger.
2737 mNetworkStats.forceUpdate();
2738 } catch (RemoteException e) {
2739 // ignored; service lives in system_server
2740 }
2741
2742 updateNetworkEnabledLocked();
2743 updateNotificationsLocked();
2744 }
2745 }
2746 return true;
2747 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002748 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2749 final boolean restrictBackground = msg.arg1 != 0;
2750 final int length = mListeners.beginBroadcast();
2751 for (int i = 0; i < length; i++) {
2752 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2753 if (listener != null) {
2754 try {
2755 listener.onRestrictBackgroundChanged(restrictBackground);
2756 } catch (RemoteException e) {
2757 }
2758 }
2759 }
2760 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08002761 final Intent intent =
2762 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
2763 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2764 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2765 return true;
2766 }
2767 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
2768 final int uid = msg.arg1;
2769 final PackageManager pm = mContext.getPackageManager();
2770 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme86e5a012016-02-16 16:26:05 -08002771 if (packages != null) {
2772 final int userId = UserHandle.getUserId(uid);
2773 for (String packageName : packages) {
2774 final Intent intent = new Intent(
2775 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
2776 intent.setPackage(packageName);
2777 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2778 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
2779 }
2780 } else {
2781 Slog.w(TAG, "no packages for uid " + uid);
Felipe Leme9778f762016-01-27 14:46:39 -08002782 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002783 return true;
2784 }
2785 case MSG_ADVISE_PERSIST_THRESHOLD: {
2786 final long lowestRule = (Long) msg.obj;
2787 try {
2788 // make sure stats are recorded frequently enough; we aim
2789 // for 2MB threshold for 2GB/month rules.
2790 final long persistThreshold = lowestRule / 1000;
2791 mNetworkStats.advisePersistThreshold(persistThreshold);
2792 } catch (RemoteException e) {
2793 // ignored; service lives in system_server
2794 }
2795 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002796 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002797 case MSG_SCREEN_ON_CHANGED: {
2798 updateScreenOn();
2799 return true;
2800 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002801 default: {
2802 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002803 }
2804 }
2805 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002806 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002807
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002808 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002809 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002810 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002811 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002812 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002813 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002814 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002815 }
2816 }
2817
2818 private void removeInterfaceQuota(String iface) {
2819 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002820 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002821 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002822 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002823 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002824 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002825 }
2826 }
2827
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002828 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2829 try {
Felipe Leme65be3022016-03-22 14:53:13 -07002830 mNetworkManager.setUidMeteredNetworkBlacklist(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002831 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002832 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002833 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002834 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002835 }
2836 }
2837
Amith Yamasani15e472352015-04-24 19:06:07 -07002838 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002839 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
2840 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
2841 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07002842 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002843 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002844 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002845 int size = uidRules.size();
2846 int[] uids = new int[size];
2847 int[] rules = new int[size];
2848 for(int index = size - 1; index >= 0; --index) {
2849 uids[index] = uidRules.keyAt(index);
2850 rules[index] = uidRules.valueAt(index);
2851 }
2852 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002853 } catch (IllegalStateException e) {
2854 Log.wtf(TAG, "problem setting firewall uid rules", e);
2855 } catch (RemoteException e) {
2856 // ignored; service lives in system_server
2857 }
2858 }
2859
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002860 /**
2861 * Add or remove a uid to the firewall blacklist for all network ifaces.
2862 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002863 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002864 if (chain == FIREWALL_CHAIN_DOZABLE) {
2865 mUidFirewallDozableRules.put(uid, rule);
2866 } else if (chain == FIREWALL_CHAIN_STANDBY) {
2867 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08002868 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
2869 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07002870 }
2871
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002872 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002873 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002874 } catch (IllegalStateException e) {
2875 Log.wtf(TAG, "problem setting firewall uid rules", e);
2876 } catch (RemoteException e) {
2877 // ignored; service lives in system_server
2878 }
2879 }
2880
2881 /**
2882 * Add or remove a uid to the firewall blacklist for all network ifaces.
2883 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002884 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002885 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
2886 mFirewallChainStates.get(chain) == enable) {
2887 // All is the same, nothing to do.
2888 return;
2889 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002890 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002891 try {
2892 mNetworkManager.setFirewallChainEnabled(chain, enable);
2893 } catch (IllegalStateException e) {
2894 Log.wtf(TAG, "problem enable firewall chain", e);
2895 } catch (RemoteException e) {
2896 // ignored; service lives in system_server
2897 }
2898 }
2899
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002900 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2901 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002902 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002903 } catch (RuntimeException e) {
2904 Slog.w(TAG, "problem reading network stats: " + e);
2905 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002906 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002907 // ignored; service lives in system_server
2908 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002909 }
2910 }
2911
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002912 private boolean isBandwidthControlEnabled() {
2913 final long token = Binder.clearCallingIdentity();
2914 try {
2915 return mNetworkManager.isBandwidthControlEnabled();
2916 } catch (RemoteException e) {
2917 // ignored; service lives in system_server
2918 return false;
2919 } finally {
2920 Binder.restoreCallingIdentity(token);
2921 }
2922 }
2923
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002924 /**
2925 * Try refreshing {@link #mTime} when stale.
2926 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002927 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002928 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002929 mTime.forceRefresh();
2930 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002931 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002932
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002933 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002934 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2935 }
2936
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002937 private static Intent buildAllowBackgroundDataIntent() {
2938 return new Intent(ACTION_ALLOW_BACKGROUND);
2939 }
2940
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002941 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2942 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2943 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2944 return intent;
2945 }
2946
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002947 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2948 final Intent intent = new Intent();
2949 intent.setComponent(new ComponentName(
2950 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2951 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2952 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2953 return intent;
2954 }
2955
2956 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2957 final Intent intent = new Intent();
2958 intent.setComponent(new ComponentName(
2959 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2960 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2961 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2962 return intent;
2963 }
2964
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002965 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002966 public void addIdleHandler(IdleHandler handler) {
2967 mHandler.getLooper().getQueue().addIdleHandler(handler);
2968 }
2969
Jeff Sharkey1b861272011-05-22 00:34:52 -07002970 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2971 final int size = source.size();
2972 for (int i = 0; i < size; i++) {
2973 target.put(source.keyAt(i), true);
2974 }
2975 }
2976
Stuart Scottf1fb3972015-04-02 18:00:02 -07002977 @Override
2978 public void factoryReset(String subscriber) {
2979 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2980
Stuart Scotte3e314d2015-04-20 14:07:45 -07002981 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
2982 return;
2983 }
2984
Stuart Scottf1fb3972015-04-02 18:00:02 -07002985 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07002986 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07002987 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
2988 for (NetworkPolicy policy : policies) {
2989 if (policy.template.equals(template)) {
2990 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2991 policy.inferred = false;
2992 policy.clearSnooze();
2993 }
2994 }
2995 setNetworkPolicies(policies);
2996
2997 // Turn restrict background data off
2998 setRestrictBackground(false);
2999
Stuart Scotte3e314d2015-04-20 14:07:45 -07003000 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3001 // Remove app's "restrict background data" flag
3002 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3003 setUidPolicy(uid, POLICY_NONE);
3004 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003005 }
3006 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003007
3008 private class MyPackageMonitor extends PackageMonitor {
3009
3010 @Override
3011 public void onPackageRemoved(String packageName, int uid) {
3012 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
3013 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -08003014 removeRestrictBackgroundWhitelistedUidLocked(uid, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08003015 }
3016 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003017 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003018}