blob: 09b7a18af40fd4531e8fd0c0120df1c2078782ac [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;
Felipe Lemea9505cc2016-02-26 10:28:41 -080031
Erik Klinef851d6d2015-04-20 16:03:48 +090032import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070033import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070034import static android.net.ConnectivityManager.TYPE_WIMAX;
Felipe Leme1b103232016-01-22 09:44:57 -080035import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
36import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
37import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070038import static android.net.ConnectivityManager.isNetworkTypeMobile;
39import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070040import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070041import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070042import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070043import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070044import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
45import 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;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -070049import static android.net.NetworkPolicyManager.POLICY_ALLOW_BACKGROUND_BATTERY_SAVE;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070050import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070051import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeydc988062015-09-14 10:09:47 -070053import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070054import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeydc988062015-09-14 10:09:47 -070055import static android.net.NetworkPolicyManager.RULE_UNKNOWN;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070056import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070057import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
58import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070059import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
60import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070061import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080062import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070063import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
64import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
65import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
66import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
67import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
68import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
69import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070070import static android.text.format.DateUtils.DAY_IN_MILLIS;
Jeff Sharkey854b2b12012-04-13 16:03:40 -070071import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070072import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070073import static com.android.internal.util.XmlUtils.readBooleanAttribute;
74import static com.android.internal.util.XmlUtils.readIntAttribute;
75import static com.android.internal.util.XmlUtils.readLongAttribute;
76import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
77import static com.android.internal.util.XmlUtils.writeIntAttribute;
78import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070079import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070080import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
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;
Felipe Leme50a235e2016-01-15 18:37:06 -0800131import android.os.ResultReceiver;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700132import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700133import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700134import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700135import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700136import android.os.RemoteException;
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 Sharkey32566012014-12-02 18:30:14 -0800158import libcore.io.IoUtils;
159
Jeff Sharkey497e4432011-06-14 17:27:29 -0700160import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800161import com.android.internal.annotations.VisibleForTesting;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800162import com.android.internal.content.PackageMonitor;
Jeff Sharkey32566012014-12-02 18:30:14 -0800163import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700164import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700165import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700166import com.android.server.DeviceIdleController;
167import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700168import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800169import com.android.server.SystemConfig;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700170import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700171
172import org.xmlpull.v1.XmlPullParser;
173import org.xmlpull.v1.XmlPullParserException;
174import org.xmlpull.v1.XmlSerializer;
175
176import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700177import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700178import java.io.FileInputStream;
179import java.io.FileNotFoundException;
180import java.io.FileOutputStream;
181import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700182import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100183import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700184import java.util.ArrayList;
185import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700186import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700187
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700188/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700189 * Service that maintains low-level network policy rules, using
190 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700191 * <p>
192 * Derives active rules by combining a given policy with other system status,
193 * and delivers to listeners, such as {@link ConnectivityManager}, for
194 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700195 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700196public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800197 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700198 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700199 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700200
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700201 private static final int VERSION_INIT = 1;
202 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700203 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800204 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800205 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800206 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700207 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700208 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700209 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700210 private static final int VERSION_SWITCH_UID = 10;
211 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700212
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800213 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700214 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800215 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700216 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800217 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700218 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700219
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700220 private static final String TAG_POLICY_LIST = "policy-list";
221 private static final String TAG_NETWORK_POLICY = "network-policy";
222 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700223 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800224 private static final String TAG_WHITELIST = "whitelist";
225 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800226 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700227
228 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700229 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700230 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
231 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700232 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700233 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800234 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700235 private static final String ATTR_WARNING_BYTES = "warningBytes";
236 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700237 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800238 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
239 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800240 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700241 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700242 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700243 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700244 private static final String ATTR_POLICY = "policy";
245
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800246 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800247 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800248 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800249 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700250
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700251 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
252
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700253 private static final int MSG_RULES_CHANGED = 1;
254 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800255 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800256 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700257 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700258 private static final int MSG_SCREEN_ON_CHANGED = 8;
Felipe Leme9778f762016-01-27 14:46:39 -0800259 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700260
Jeff Sharkey75279902011-05-24 18:39:45 -0700261 private final Context mContext;
262 private final IActivityManager mActivityManager;
263 private final IPowerManager mPowerManager;
264 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700265 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700266 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700267 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700268 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700269
270 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700271 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700272 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700273 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700274
Dianne Hackborn497175b2014-07-01 12:56:08 -0700275 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700276
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700277 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700278 volatile boolean mScreenOn;
279 volatile boolean mRestrictBackground;
280 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700281 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700282
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700283 private final boolean mSuppressDefaultPolicy;
284
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700285 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800286 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700287 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800288 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700289
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700290 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700291 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700292 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800293 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700294
Jeff Sharkeydc988062015-09-14 10:09:47 -0700295 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
296 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
297
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700298 /** Set of states for the child firewall chains. True if the chain is active. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700299 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
300
Jeff Sharkey32566012014-12-02 18:30:14 -0800301 /**
302 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700303 * in power save mode, except device idle (doze) still applies.
304 * TODO: An int array might be sufficient
305 */
306 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
307
308 /**
309 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800310 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700311 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800312 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700313 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700314
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700315 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
316
Felipe Lemeb85a6372016-01-14 16:16:16 -0800317 /**
318 * UIDs that have been white-listed to avoid restricted background.
319 */
320 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
321
Felipe Lemea9505cc2016-02-26 10:28:41 -0800322 /**
323 * UIDs that have been initially white-listed by system to avoid restricted background.
324 */
325 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
326 new SparseBooleanArray();
327
328 /**
329 * UIDs that have been initially white-listed by system to avoid restricted background,
330 * but later revoked by user.
331 */
332 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
333 new SparseBooleanArray();
334
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700335 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800336 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700337 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800338 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700339
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700340 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700341 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700342
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700343 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800344 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700345
Jeff Sharkey32566012014-12-02 18:30:14 -0800346 private final RemoteCallbackList<INetworkPolicyListener>
347 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700348
Dianne Hackborn497175b2014-07-01 12:56:08 -0700349 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700350
351 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700352
Svet Ganov16a16892015-04-16 10:32:04 -0700353 private final AppOpsManager mAppOps;
354
Felipe Lemeb85a6372016-01-14 16:16:16 -0800355 private final MyPackageMonitor mPackageMonitor;
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800356 private final IPackageManager mIPm;
357
Felipe Lemeb85a6372016-01-14 16:16:16 -0800358
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700359 // TODO: keep whitelist of system-critical services that should never have
360 // rules enforced, such as system, phone, and radio UIDs.
361
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700362 // TODO: migrate notifications to SystemUI
363
Jeff Sharkey75279902011-05-24 18:39:45 -0700364 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700365 IPowerManager powerManager, INetworkStatsService networkStats,
366 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700367 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700368 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700369 }
370
371 private static File getSystemDir() {
372 return new File(Environment.getDataDirectory(), "system");
373 }
374
375 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700376 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700377 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
378 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700379 mContext = checkNotNull(context, "missing context");
380 mActivityManager = checkNotNull(activityManager, "missing activityManager");
381 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700382 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700383 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700384 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700385 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700386 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700387 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800388 mIPm = AppGlobals.getPackageManager();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700389
Amith Yamasani450a16b2013-09-18 16:28:50 -0700390 HandlerThread thread = new HandlerThread(TAG);
391 thread.start();
392 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700393
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700394 mSuppressDefaultPolicy = suppressDefaultPolicy;
395
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700396 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700397
398 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800399
400 mPackageMonitor = new MyPackageMonitor();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700401 }
402
403 public void bindConnectivityManager(IConnectivityManager connManager) {
404 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700405 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700406
Jeff Sharkey497e4432011-06-14 17:27:29 -0700407 public void bindNotificationManager(INotificationManager notifManager) {
408 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
409 }
410
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700411 void updatePowerSaveWhitelistLocked() {
412 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700413 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
414 mPowerSaveWhitelistExceptIdleAppIds.clear();
415 if (whitelist != null) {
416 for (int uid : whitelist) {
417 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
418 }
419 }
420 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700421 mPowerSaveWhitelistAppIds.clear();
422 if (whitelist != null) {
423 for (int uid : whitelist) {
424 mPowerSaveWhitelistAppIds.put(uid, true);
425 }
426 }
427 } catch (RemoteException e) {
428 }
429 }
430
Felipe Lemea9505cc2016-02-26 10:28:41 -0800431 /**
432 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
433 * revoke the whitelist.
434 *
435 * @return whether any uid has been added to {@link #mRestrictBackgroundWhitelistUids}.
436 */
437 boolean addDefaultRestrictBackgroundWhitelistUids() {
438 final SystemConfig sysConfig = SystemConfig.getInstance();
439 final PackageManager pm = mContext.getPackageManager();
440 final List<UserInfo> users = mUserManager.getUsers();
441 final int numberUsers = users.size();
442
443 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
444 boolean changed = false;
445 for (int i = 0; i < allowDataUsage.size(); i++) {
446 final String pkg = allowDataUsage.valueAt(i);
447 if (LOGD)
448 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg);
449 final ApplicationInfo app;
450 try {
451 app = pm.getApplicationInfo(pkg, PackageManager.MATCH_SYSTEM_ONLY);
452 } catch (PackageManager.NameNotFoundException e) {
453 // Should not happen
454 Slog.wtf(TAG, "No ApplicationInfo for package " + pkg);
455 continue;
456 }
457 if (!app.isPrivilegedApp()) {
458 Slog.w(TAG, "getAllowInDataUsageSave() returned non-privileged app: " + pkg);
459 continue;
460 }
461 for (int j = 0; j < numberUsers; j++) {
462 final UserInfo user = users.get(i);
463 final int uid = UserHandle.getUid(user.id, app.uid);
464 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
465 if (LOGD) Slog.d(TAG, "revoked whistelist status for uid " + uid + ": "
466 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
467 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
468 Slog.i(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
469 + user.id + ") to restrict background whitelist");
470 mRestrictBackgroundWhitelistUids.append(uid, true);
471 changed = true;
472 }
473 }
474 }
475 return changed;
476 }
477
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700478 void updatePowerSaveTempWhitelistLocked() {
479 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700480 // Clear the states of the current whitelist
481 final int N = mPowerSaveTempWhitelistAppIds.size();
482 for (int i = 0; i < N; i++) {
483 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
484 }
485 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700486 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700487 if (whitelist != null) {
488 for (int uid : whitelist) {
489 mPowerSaveTempWhitelistAppIds.put(uid, true);
490 }
491 }
492 } catch (RemoteException e) {
493 }
494 }
495
Amith Yamasani06f08062015-06-12 13:23:33 -0700496 /**
497 * Remove unnecessary entries in the temp whitelist
498 */
499 void purgePowerSaveTempWhitelistLocked() {
500 final int N = mPowerSaveTempWhitelistAppIds.size();
501 for (int i = N - 1; i >= 0; i--) {
502 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
503 mPowerSaveTempWhitelistAppIds.removeAt(i);
504 }
505 }
506 }
507
Jeff Sharkeya4620792011-05-20 15:29:23 -0700508 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700509 if (!isBandwidthControlEnabled()) {
510 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
511 return;
512 }
513
Amith Yamasani15e472352015-04-24 19:06:07 -0700514 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
515
Felipe Lemeb85a6372016-01-14 16:16:16 -0800516 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
517
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700518 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700519 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700520 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
521 mPowerManagerInternal.registerLowPowerModeObserver(
522 new PowerManagerInternal.LowPowerModeListener() {
523 @Override
524 public void onLowPowerModeChanged(boolean enabled) {
525 synchronized (mRulesLock) {
526 if (mRestrictPower != enabled) {
527 mRestrictPower = enabled;
528 updateRulesForGlobalChangeLocked(true);
529 }
530 }
531 }
532 });
533 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700534 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700535
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700536 // read policy from disk
537 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700538
Felipe Lemea9505cc2016-02-26 10:28:41 -0800539 if (addDefaultRestrictBackgroundWhitelistUids()) {
540 writePolicyLocked();
541 }
542
Jeff Sharkeydc988062015-09-14 10:09:47 -0700543 updateRulesForGlobalChangeLocked(false);
544 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700545 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700546
Jeff Sharkeya4620792011-05-20 15:29:23 -0700547 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700548
Jeff Sharkeya4620792011-05-20 15:29:23 -0700549 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700550 mActivityManager.registerUidObserver(mUidObserver,
551 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700552 mNetworkManager.registerObserver(mAlertObserver);
553 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700554 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700555 }
556
Jeff Sharkeya4620792011-05-20 15:29:23 -0700557 // TODO: traverse existing processes to know foreground state, or have
558 // activitymanager dispatch current state when new observer attached.
559
560 final IntentFilter screenFilter = new IntentFilter();
561 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
562 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700563 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700564
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700565 // listen for changes to power save whitelist
566 final IntentFilter whitelistFilter = new IntentFilter(
567 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
568 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
569
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700570 DeviceIdleController.LocalService deviceIdleService
571 = LocalServices.getService(DeviceIdleController.LocalService.class);
572 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
573
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700574 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900575 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700576 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
577
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700578 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700579 final IntentFilter packageFilter = new IntentFilter();
580 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700581 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700582 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700583
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700584 // listen for UID changes to update policy
585 mContext.registerReceiver(
586 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
587
588 // listen for user changes to update policy
589 final IntentFilter userFilter = new IntentFilter();
590 userFilter.addAction(ACTION_USER_ADDED);
591 userFilter.addAction(ACTION_USER_REMOVED);
592 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
593
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700594 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700595 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
596 mContext.registerReceiver(
597 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
598
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700599 // listen for restrict background changes from notifications
600 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
601 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
602
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800603 // listen for snooze warning from notifications
604 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
605 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
606 MANAGE_NETWORK_POLICY, mHandler);
607
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700608 // listen for configured wifi networks to be removed
609 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700610 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700611
612 // listen for wifi state changes to catch metered hint
613 final IntentFilter wifiStateFilter = new IntentFilter(
614 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700615 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700616
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700617 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700618
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700619 }
620
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700621 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700622 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700623 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700624 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700625 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700626 }
627
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700628 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700629 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700630 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700631 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700632 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700633
634 @Override public void onUidActive(int uid) throws RemoteException {
635 }
636
637 @Override public void onUidIdle(int uid) throws RemoteException {
638 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700639 };
640
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700641 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700642 @Override
643 public void onReceive(Context context, Intent intent) {
644 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
645 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700646 updatePowerSaveWhitelistLocked();
647 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700648 }
649 }
650 };
651
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700652 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
653 @Override
654 public void run() {
655 synchronized (mRulesLock) {
656 updatePowerSaveTempWhitelistLocked();
657 updateRulesForTempWhitelistChangeLocked();
658 purgePowerSaveTempWhitelistLocked();
659 }
660 }
661 };
662
663 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700664 @Override
665 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800666 // screen-related broadcasts are protected by system, no need
667 // for permissions check.
668 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700669 }
670 };
671
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700672 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700673 @Override
674 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700675 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700676
677 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700678 final int uid = intent.getIntExtra(EXTRA_UID, -1);
679 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700680
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700681 if (ACTION_PACKAGE_ADDED.equals(action)) {
682 // update rules for UID, since it might be subject to
683 // global background data policy
684 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
685 synchronized (mRulesLock) {
686 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700687 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700688 }
689 }
690 };
691
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700692 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700693 @Override
694 public void onReceive(Context context, Intent intent) {
695 // on background handler thread, and UID_REMOVED is protected
696
697 final int uid = intent.getIntExtra(EXTRA_UID, -1);
698 if (uid == -1) return;
699
700 // remove any policy and update rules to clean up
701 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
702 synchronized (mRulesLock) {
703 mUidPolicy.delete(uid);
704 updateRulesForUidLocked(uid);
705 writePolicyLocked();
706 }
707 }
708 };
709
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700710 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700711 @Override
712 public void onReceive(Context context, Intent intent) {
713 // on background handler thread, and USER_ADDED and USER_REMOVED
714 // broadcasts are protected
715
716 final String action = intent.getAction();
717 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
718 if (userId == -1) return;
719
Amith Yamasani15e472352015-04-24 19:06:07 -0700720 switch (action) {
721 case ACTION_USER_REMOVED:
722 case ACTION_USER_ADDED:
723 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800724 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700725 // USER_REMOVED, and one last sanity check during USER_ADDED
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800726 removeUserStateLocked(userId);
Amith Yamasani15e472352015-04-24 19:06:07 -0700727 // Update global restrict for new user
728 updateRulesForGlobalChangeLocked(true);
729 }
730 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700731 }
732 }
733 };
734
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700735 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700736 * Receiver that watches for {@link INetworkStatsService} updates, which we
737 * use to check against {@link NetworkPolicy#warningBytes}.
738 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700739 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700740 @Override
741 public void onReceive(Context context, Intent intent) {
742 // on background handler thread, and verified
743 // READ_NETWORK_USAGE_HISTORY permission above.
744
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800745 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700746 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700747 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700748 updateNotificationsLocked();
749 }
750 }
751 };
752
753 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700754 * Receiver that watches for {@link Notification} control of
755 * {@link #mRestrictBackground}.
756 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700757 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700758 @Override
759 public void onReceive(Context context, Intent intent) {
760 // on background handler thread, and verified MANAGE_NETWORK_POLICY
761 // permission above.
762
763 setRestrictBackground(false);
764 }
765 };
766
767 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800768 * Receiver that watches for {@link Notification} control of
769 * {@link NetworkPolicy#lastWarningSnooze}.
770 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700771 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800772 @Override
773 public void onReceive(Context context, Intent intent) {
774 // on background handler thread, and verified MANAGE_NETWORK_POLICY
775 // permission above.
776
777 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
778 performSnooze(template, TYPE_WARNING);
779 }
780 };
781
782 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700783 * Receiver that watches for {@link WifiConfiguration} to be changed.
784 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700785 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700786 @Override
787 public void onReceive(Context context, Intent intent) {
788 // on background handler thread, and verified CONNECTIVITY_INTERNAL
789 // permission above.
790
791 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
792 if (reason == CHANGE_REASON_REMOVED) {
793 final WifiConfiguration config = intent.getParcelableExtra(
794 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700795 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800796 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700797 synchronized (mRulesLock) {
798 if (mNetworkPolicy.containsKey(template)) {
799 mNetworkPolicy.remove(template);
800 writePolicyLocked();
801 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700802 }
803 }
804 }
805 }
806 };
807
808 /**
809 * Receiver that watches {@link WifiInfo} state changes to infer metered
810 * state. Ignores hints when policy is user-defined.
811 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700812 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700813 @Override
814 public void onReceive(Context context, Intent intent) {
815 // on background handler thread, and verified CONNECTIVITY_INTERNAL
816 // permission above.
817
818 // ignore when not connected
819 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
820 if (!netInfo.isConnected()) return;
821
822 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
823 final boolean meteredHint = info.getMeteredHint();
824
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800825 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700826 synchronized (mRulesLock) {
827 NetworkPolicy policy = mNetworkPolicy.get(template);
828 if (policy == null && meteredHint) {
829 // policy doesn't exist, and AP is hinting that it's
830 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800831 policy = newWifiPolicy(template, meteredHint);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700832 addNetworkPolicyLocked(policy);
833
834 } else if (policy != null && policy.inferred) {
835 // policy exists, and was inferred: update its current
836 // metered state.
837 policy.metered = meteredHint;
838
839 // since this is inferred for each wifi session, just update
840 // rules without persisting.
841 updateNetworkRulesLocked();
842 }
843 }
844 }
845 };
846
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800847 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
848 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
849 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
850 metered, true);
851 }
852
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700853 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700854 * Observer that watches for {@link INetworkManagementService} alerts.
855 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700856 final private INetworkManagementEventObserver mAlertObserver
857 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700858 @Override
859 public void limitReached(String limitName, String iface) {
860 // only someone like NMS should be calling us
861 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
862
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800863 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
864 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700865 }
866 }
867 };
868
869 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700870 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
871 * to show visible notifications as needed.
872 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700873 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700874 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
875
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700876 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700877 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700878 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700879
880 // TODO: when switching to kernel notifications, compute next future
881 // cycle boundary to recompute notifications.
882
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700883 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800884 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700885 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
886 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700887 // ignore policies that aren't relevant to user
888 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700889 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700890
Jeff Sharkey497e4432011-06-14 17:27:29 -0700891 final long start = computeLastCycleBoundary(currentTime, policy);
892 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700893 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700894
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700895 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800896 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700897 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
898 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700899 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
900 notifyOverLimitLocked(policy.template);
901 }
902
Jeff Sharkey497e4432011-06-14 17:27:29 -0700903 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700904 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700905
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800906 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700907 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700908 }
909 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700910 }
911
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700912 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700913 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
914 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700915 if (!mActiveNotifs.contains(tag)) {
916 cancelNotification(tag);
917 }
918 }
919 }
920
921 /**
922 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700923 * current device state, such as when
924 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
925 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700926 */
927 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800928 if (template.isMatchRuleMobile()) {
929 final TelephonyManager tele = TelephonyManager.from(mContext);
930 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700931
Jeff Sharkey32566012014-12-02 18:30:14 -0800932 // Mobile template is relevant when any active subscriber matches
933 final int[] subIds = sub.getActiveSubscriptionIdList();
934 for (int subId : subIds) {
935 final String subscriberId = tele.getSubscriberId(subId);
936 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
937 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
938 if (template.matches(probeIdent)) {
939 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700940 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800941 }
942 return false;
943 } else {
944 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700945 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700946 }
947
948 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700949 * Notify that given {@link NetworkTemplate} is over
950 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
951 */
952 private void notifyOverLimitLocked(NetworkTemplate template) {
953 if (!mOverLimitNotified.contains(template)) {
954 mContext.startActivity(buildNetworkOverLimitIntent(template));
955 mOverLimitNotified.add(template);
956 }
957 }
958
959 private void notifyUnderLimitLocked(NetworkTemplate template) {
960 mOverLimitNotified.remove(template);
961 }
962
963 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700964 * Build unique tag that identifies an active {@link NetworkPolicy}
965 * notification of a specific type, like {@link #TYPE_LIMIT}.
966 */
967 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700968 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700969 }
970
971 /**
972 * Show notification for combined {@link NetworkPolicy} and specific type,
973 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
974 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700975 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700976 final String tag = buildNotificationTag(policy, type);
977 final Notification.Builder builder = new Notification.Builder(mContext);
978 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800979 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700980 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200981 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700982
983 final Resources res = mContext.getResources();
984 switch (type) {
985 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700986 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700987 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700988
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700989 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700990 builder.setTicker(title);
991 builder.setContentTitle(title);
992 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700993
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800994 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
995 builder.setDeleteIntent(PendingIntent.getBroadcast(
996 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
997
998 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700999 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001000 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1001
Jeff Sharkey497e4432011-06-14 17:27:29 -07001002 break;
1003 }
1004 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001005 final CharSequence body = res.getText(R.string.data_usage_limit_body);
1006
1007 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001008 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001009 switch (policy.template.getMatchRule()) {
1010 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001011 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001012 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001013 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001014 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001015 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001016 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001017 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001018 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001019 case MATCH_WIFI:
1020 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001021 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001022 break;
1023 default:
1024 title = null;
1025 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001026 }
1027
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001028 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001029 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001030 builder.setTicker(title);
1031 builder.setContentTitle(title);
1032 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001033
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001034 final Intent intent = buildNetworkOverLimitIntent(policy.template);
1035 builder.setContentIntent(PendingIntent.getActivity(
1036 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1037 break;
1038 }
1039 case TYPE_LIMIT_SNOOZED: {
1040 final long overBytes = totalBytes - policy.limitBytes;
1041 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
1042 Formatter.formatFileSize(mContext, overBytes));
1043
1044 final CharSequence title;
1045 switch (policy.template.getMatchRule()) {
1046 case MATCH_MOBILE_3G_LOWER:
1047 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1048 break;
1049 case MATCH_MOBILE_4G:
1050 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1051 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001052 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001053 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1054 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001055 case MATCH_WIFI:
1056 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1057 break;
1058 default:
1059 title = null;
1060 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001061 }
1062
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001063 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001064 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001065 builder.setTicker(title);
1066 builder.setContentTitle(title);
1067 builder.setContentText(body);
1068
1069 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001070 builder.setContentIntent(PendingIntent.getActivity(
1071 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001072 break;
1073 }
1074 }
1075
1076 // TODO: move to NotificationManager once we can mock it
1077 try {
1078 final String packageName = mContext.getPackageName();
1079 final int[] idReceived = new int[1];
1080 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001081 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001082 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001083 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001084 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001085 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001086 }
1087 }
1088
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001089 private void cancelNotification(String tag) {
1090 // TODO: move to NotificationManager once we can mock it
1091 try {
1092 final String packageName = mContext.getPackageName();
1093 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001094 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001095 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001096 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001097 }
1098 }
1099
1100 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001101 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001102 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001103 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001104 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001105 @Override
1106 public void onReceive(Context context, Intent intent) {
1107 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1108 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001109
1110 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001111 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001112 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001113 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001114 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001115 updateNetworkRulesLocked();
1116 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001117 }
1118 }
1119 };
1120
1121 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001122 * Proactively control network data connections when they exceed
1123 * {@link NetworkPolicy#limitBytes}.
1124 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001125 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001126 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1127
1128 // TODO: reset any policy-disabled networks when any policy is removed
1129 // completely, which is currently rare case.
1130
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001131 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001132 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1133 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001134 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001135 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001136 setNetworkTemplateEnabled(policy.template, true);
1137 continue;
1138 }
1139
1140 final long start = computeLastCycleBoundary(currentTime, policy);
1141 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001142 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001143
1144 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001145 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1146 && policy.lastLimitSnooze < start;
1147 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001148
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001149 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001150 }
1151 }
1152
1153 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001154 * Proactively disable networks that match the given
1155 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001156 */
1157 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001158 // TODO: reach into ConnectivityManager to proactively disable bringing
1159 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001160 }
1161
1162 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001163 * Examine all connected {@link NetworkState}, looking for
1164 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1165 * remaining quota based on usage cycle and historical stats.
1166 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001167 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001168 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001169
1170 final NetworkState[] states;
1171 try {
1172 states = mConnManager.getAllNetworkState();
1173 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001174 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001175 return;
1176 }
1177
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001178 // If we are in restrict power mode, we want to treat all interfaces
1179 // as metered, to restrict access to the network by uid. However, we
1180 // will not have a bandwidth limit. Also only do this if restrict
Felipe Lemeb85a6372016-01-14 16:16:16 -08001181 // background data use is *not* enabled, since that takes precedence
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001182 // use over those networks can have a cost associated with it).
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001183 final boolean powerSave = mRestrictPower && !mRestrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001184
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001185 // First, generate identities of all connected networks so we can
1186 // quickly compare them against all defined policies below.
1187 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001188 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001189 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001190 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001191 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001192
1193 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001194 if (baseIface != null) {
1195 connIdents.add(Pair.create(baseIface, ident));
1196 if (powerSave) {
1197 connIfaces.add(baseIface);
1198 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001199 }
1200
1201 // Stacked interfaces are considered to have same identity as
1202 // their parent network.
1203 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1204 for (LinkProperties stackedLink : stackedLinks) {
1205 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001206 if (stackedIface != null) {
1207 connIdents.add(Pair.create(stackedIface, ident));
1208 if (powerSave) {
1209 connIfaces.add(stackedIface);
1210 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001211 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001212 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001213 }
1214 }
1215
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001216 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001217 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001218 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001219 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001220 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001221
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001222 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001223 for (int j = connIdents.size() - 1; j >= 0; j--) {
1224 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1225 if (policy.template.matches(ident.second)) {
1226 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001227 }
1228 }
1229
1230 if (ifaceList.size() > 0) {
1231 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001232 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001233 }
1234 }
1235
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001236 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001237 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001238
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001239 // apply each policy that we found ifaces for; compute remaining data
1240 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001241 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001242 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1243 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1244 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001245
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001246 final long start;
1247 final long totalBytes;
1248 if (policy.hasCycle()) {
1249 start = computeLastCycleBoundary(currentTime, policy);
1250 totalBytes = getTotalBytes(policy.template, start, currentTime);
1251 } else {
1252 start = Long.MAX_VALUE;
1253 totalBytes = 0;
1254 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001255
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001256 if (LOGD) {
1257 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001258 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001259 }
1260
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001261 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001262 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001263 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001264 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001265 if (!hasLimit) {
1266 // metered network, but no policy limit; we still need to
1267 // restrict apps, so push really high quota.
1268 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001269 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001270 // snoozing past quota, but we still need to restrict apps,
1271 // so push really high quota.
1272 quotaBytes = Long.MAX_VALUE;
1273 } else {
1274 // remaining "quota" bytes are based on total usage in
1275 // current cycle. kernel doesn't like 0-byte rules, so we
1276 // set 1-byte quota and disable the radio later.
1277 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1278 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001279
1280 if (ifaces.length > 1) {
1281 // TODO: switch to shared quota once NMS supports
1282 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001283 }
1284
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001285 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001286 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001287 setInterfaceQuota(iface, quotaBytes);
1288 newMeteredIfaces.add(iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001289 if (powerSave) {
1290 connIfaces.remove(iface);
1291 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001292 }
1293 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001294
1295 // keep track of lowest warning or limit of active policies
1296 if (hasWarning && policy.warningBytes < lowestRule) {
1297 lowestRule = policy.warningBytes;
1298 }
1299 if (hasLimit && policy.limitBytes < lowestRule) {
1300 lowestRule = policy.limitBytes;
1301 }
1302 }
1303
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001304 for (int i = connIfaces.size()-1; i >= 0; i--) {
1305 String iface = connIfaces.valueAt(i);
1306 removeInterfaceQuota(iface);
1307 setInterfaceQuota(iface, Long.MAX_VALUE);
1308 newMeteredIfaces.add(iface);
1309 }
1310
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001311 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001312
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001313 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001314 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1315 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001316 if (!newMeteredIfaces.contains(iface)) {
1317 removeInterfaceQuota(iface);
1318 }
1319 }
1320 mMeteredIfaces = newMeteredIfaces;
1321
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001322 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001323 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001324 }
1325
1326 /**
1327 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1328 * have at least a default mobile policy defined.
1329 */
1330 private void ensureActiveMobilePolicyLocked() {
1331 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001332 if (mSuppressDefaultPolicy) return;
1333
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001334 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001335 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001336
Jeff Sharkey32566012014-12-02 18:30:14 -08001337 final int[] subIds = sub.getActiveSubscriptionIdList();
1338 for (int subId : subIds) {
1339 final String subscriberId = tele.getSubscriberId(subId);
1340 ensureActiveMobilePolicyLocked(subscriberId);
1341 }
1342 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001343
Jeff Sharkey32566012014-12-02 18:30:14 -08001344 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1345 // Poke around to see if we already have a policy
1346 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1347 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1348 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1349 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1350 if (template.matches(probeIdent)) {
1351 if (LOGD) {
1352 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1353 + NetworkIdentity.scrubSubscriberId(subscriberId));
1354 }
1355 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001356 }
1357 }
1358
Jeff Sharkey32566012014-12-02 18:30:14 -08001359 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1360 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001361
Jeff Sharkey32566012014-12-02 18:30:14 -08001362 // Build default mobile policy, and assume usage cycle starts today
1363 final long warningBytes = mContext.getResources().getInteger(
1364 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001365
Jeff Sharkey32566012014-12-02 18:30:14 -08001366 final Time time = new Time();
1367 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001368
Jeff Sharkey32566012014-12-02 18:30:14 -08001369 final int cycleDay = time.monthDay;
1370 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001371
Jeff Sharkey32566012014-12-02 18:30:14 -08001372 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1373 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1374 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1375 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001376 }
1377
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001378 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001379 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001380
1381 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001382 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001383 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001384
1385 FileInputStream fis = null;
1386 try {
1387 fis = mPolicyFile.openRead();
1388 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001389 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001390
1391 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001392 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001393 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001394 while ((type = in.next()) != END_DOCUMENT) {
1395 final String tag = in.getName();
1396 if (type == START_TAG) {
1397 if (TAG_POLICY_LIST.equals(tag)) {
1398 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001399 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1400 mRestrictBackground = readBooleanAttribute(
1401 in, ATTR_RESTRICT_BACKGROUND);
1402 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001403 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001404 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001405
1406 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1407 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1408 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001409 final String networkId;
1410 if (version >= VERSION_ADDED_NETWORK_ID) {
1411 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1412 } else {
1413 networkId = null;
1414 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001415 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001416 final String cycleTimezone;
1417 if (version >= VERSION_ADDED_TIMEZONE) {
1418 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1419 } else {
1420 cycleTimezone = Time.TIMEZONE_UTC;
1421 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001422 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1423 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001424 final long lastLimitSnooze;
1425 if (version >= VERSION_SPLIT_SNOOZE) {
1426 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1427 } else if (version >= VERSION_ADDED_SNOOZE) {
1428 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001429 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001430 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001431 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001432 final boolean metered;
1433 if (version >= VERSION_ADDED_METERED) {
1434 metered = readBooleanAttribute(in, ATTR_METERED);
1435 } else {
1436 switch (networkTemplate) {
1437 case MATCH_MOBILE_3G_LOWER:
1438 case MATCH_MOBILE_4G:
1439 case MATCH_MOBILE_ALL:
1440 metered = true;
1441 break;
1442 default:
1443 metered = false;
1444 }
1445 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001446 final long lastWarningSnooze;
1447 if (version >= VERSION_SPLIT_SNOOZE) {
1448 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1449 } else {
1450 lastWarningSnooze = SNOOZE_NEVER;
1451 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001452 final boolean inferred;
1453 if (version >= VERSION_ADDED_INFERRED) {
1454 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1455 } else {
1456 inferred = false;
1457 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001458
Jeff Sharkey32566012014-12-02 18:30:14 -08001459 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1460 subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001461 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001462 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001463 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001464
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001465 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001466 final int uid = readIntAttribute(in, ATTR_UID);
1467 final int policy = readIntAttribute(in, ATTR_POLICY);
1468
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001469 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001470 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001471 } else {
1472 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1473 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001474 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001475 final int appId = readIntAttribute(in, ATTR_APP_ID);
1476 final int policy = readIntAttribute(in, ATTR_POLICY);
1477
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001478 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001479 // app policy is deprecated so this is only used in pre system user split.
1480 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001481 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001482 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001483 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001484 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001485 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001486 } else if (TAG_WHITELIST.equals(tag)) {
1487 insideWhitelist = true;
1488 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1489 final int uid = readIntAttribute(in, ATTR_UID);
1490 mRestrictBackgroundWhitelistUids.put(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001491 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1492 final int uid = readIntAttribute(in, ATTR_UID);
1493 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001494 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001495 } else if (type == END_TAG) {
1496 if (TAG_WHITELIST.equals(tag)) {
1497 insideWhitelist = false;
1498 }
1499
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001500 }
1501 }
1502
1503 } catch (FileNotFoundException e) {
1504 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001505 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001506 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001507 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001508 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001509 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001510 } finally {
1511 IoUtils.closeQuietly(fis);
1512 }
1513 }
1514
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001515 /**
1516 * Upgrade legacy background data flags, notifying listeners of one last
1517 * change to always-true.
1518 */
1519 private void upgradeLegacyBackgroundData() {
1520 mRestrictBackground = Settings.Secure.getInt(
1521 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1522
1523 // kick off one last broadcast if restricted
1524 if (mRestrictBackground) {
1525 final Intent broadcast = new Intent(
1526 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001527 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001528 }
1529 }
1530
Dianne Hackborn497175b2014-07-01 12:56:08 -07001531 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001532 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001533
1534 FileOutputStream fos = null;
1535 try {
1536 fos = mPolicyFile.startWrite();
1537
1538 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001539 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001540 out.startDocument(null, true);
1541
1542 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001543 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001544 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001545
1546 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001547 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1548 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001549 final NetworkTemplate template = policy.template;
1550
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001551 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001552 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1553 final String subscriberId = template.getSubscriberId();
1554 if (subscriberId != null) {
1555 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001556 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001557 final String networkId = template.getNetworkId();
1558 if (networkId != null) {
1559 out.attribute(null, ATTR_NETWORK_ID, networkId);
1560 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001561 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001562 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001563 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1564 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001565 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1566 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001567 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001568 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001569 out.endTag(null, TAG_NETWORK_POLICY);
1570 }
1571
1572 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001573 for (int i = 0; i < mUidPolicy.size(); i++) {
1574 final int uid = mUidPolicy.keyAt(i);
1575 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001576
Jeff Sharkey497e4432011-06-14 17:27:29 -07001577 // skip writing empty policies
1578 if (policy == POLICY_NONE) continue;
1579
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001580 out.startTag(null, TAG_UID_POLICY);
1581 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001582 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001583 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001584 }
1585
1586 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001587
1588 // write all whitelists
1589 out.startTag(null, TAG_WHITELIST);
1590
1591 // restrict background whitelist
Felipe Lemea9505cc2016-02-26 10:28:41 -08001592 int size = mRestrictBackgroundWhitelistUids.size();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001593 for (int i = 0; i < size; i++) {
1594 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1595 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1596 writeIntAttribute(out, ATTR_UID, uid);
1597 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1598 }
1599
Felipe Lemea9505cc2016-02-26 10:28:41 -08001600 // revoked restrict background whitelist
1601 size = mRestrictBackgroundWhitelistRevokedUids.size();
1602 for (int i = 0; i < size; i++) {
1603 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1604 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1605 writeIntAttribute(out, ATTR_UID, uid);
1606 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1607 }
1608
Felipe Lemeb85a6372016-01-14 16:16:16 -08001609 out.endTag(null, TAG_WHITELIST);
1610
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001611 out.endDocument();
1612
1613 mPolicyFile.finishWrite(fos);
1614 } catch (IOException e) {
1615 if (fos != null) {
1616 mPolicyFile.failWrite(fos);
1617 }
1618 }
1619 }
1620
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001621 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001622 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001623 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001624
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001625 if (!UserHandle.isApp(uid)) {
1626 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001627 }
1628
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001629 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001630 final long token = Binder.clearCallingIdentity();
1631 try {
1632 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1633 if (oldPolicy != policy) {
1634 setUidPolicyUncheckedLocked(uid, policy, true);
1635 }
1636 } finally {
1637 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001638 }
1639 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001640 }
1641
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001642 @Override
1643 public void addUidPolicy(int uid, int policy) {
1644 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001645
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001646 if (!UserHandle.isApp(uid)) {
1647 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1648 }
1649
1650 synchronized (mRulesLock) {
1651 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1652 policy |= oldPolicy;
1653 if (oldPolicy != policy) {
1654 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001655 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001656 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001657 }
1658
1659 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001660 public void removeUidPolicy(int uid, int policy) {
1661 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1662
1663 if (!UserHandle.isApp(uid)) {
1664 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1665 }
1666
1667 synchronized (mRulesLock) {
1668 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1669 policy = oldPolicy & ~policy;
1670 if (oldPolicy != policy) {
1671 setUidPolicyUncheckedLocked(uid, policy, true);
1672 }
1673 }
1674 }
1675
1676 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1677 mUidPolicy.put(uid, policy);
1678
1679 // uid policy changed, recompute rules and persist policy.
1680 updateRulesForUidLocked(uid);
1681 if (persist) {
1682 writePolicyLocked();
1683 }
1684 }
1685
1686 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001687 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001688 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1689
Jeff Sharkeya4620792011-05-20 15:29:23 -07001690 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001691 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001692 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001693 }
1694
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001695 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001696 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001697 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1698
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001699 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001700 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001701 for (int i = 0; i < mUidPolicy.size(); i++) {
1702 final int uid = mUidPolicy.keyAt(i);
1703 final int uidPolicy = mUidPolicy.valueAt(i);
1704 if (uidPolicy == policy) {
1705 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001706 }
1707 }
1708 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001709 return uids;
1710 }
1711
1712 /**
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001713 * Remove any persistable state associated with given {@link UserHandle}, persisting
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001714 * if any changes are made.
1715 */
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001716 void removeUserStateLocked(int userId) {
1717 if (LOGV) Slog.v(TAG, "removeUserStateLocked()");
1718 boolean writePolicy = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001719
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001720 // Remove entries from restricted background UID whitelist
1721 int[] wlUids = new int[0];
1722 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1723 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1724 if (UserHandle.getUserId(uid) == userId) {
1725 wlUids = appendInt(wlUids, uid);
1726 }
1727 }
1728
1729 if (wlUids.length > 0) {
1730 for (int uid : wlUids) {
1731 removeRestrictBackgroundWhitelistedUidLocked(uid, false);
1732 }
1733 writePolicy = true;
1734 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08001735 updateRulesForGlobalChangeLocked(true);
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001736
1737 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001738 int[] uids = new int[0];
1739 for (int i = 0; i < mUidPolicy.size(); i++) {
1740 final int uid = mUidPolicy.keyAt(i);
1741 if (UserHandle.getUserId(uid) == userId) {
1742 uids = appendInt(uids, uid);
1743 }
1744 }
1745
1746 if (uids.length > 0) {
1747 for (int uid : uids) {
1748 mUidPolicy.delete(uid);
1749 updateRulesForUidLocked(uid);
1750 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001751 writePolicy = true;
1752 }
1753
1754 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;
1900 updateRulesForGlobalChangeLocked(true);
1901 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();
2003 synchronized (mRulesLock) {
2004 if (!mRestrictBackground) {
2005 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2006 }
2007 return mRestrictBackgroundWhitelistUids.get(uid)
2008 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2009 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2010 }
2011 }
2012
2013 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002014 public boolean getRestrictBackground() {
2015 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2016
2017 synchronized (mRulesLock) {
2018 return mRestrictBackground;
2019 }
2020 }
2021
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002022 @Override
2023 public void setDeviceIdleMode(boolean enabled) {
2024 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2025
2026 synchronized (mRulesLock) {
2027 if (mDeviceIdleMode != enabled) {
2028 mDeviceIdleMode = enabled;
2029 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002030 // Device idle change means we need to rebuild rules for all
2031 // known apps, so do a global refresh.
2032 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002033 }
2034 if (enabled) {
2035 EventLogTags.writeDeviceIdleOnPhase("net");
2036 } else {
2037 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002038 }
2039 }
2040 }
2041 }
2042
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002043 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002044 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2045 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002046 if (policy.template.matches(ident)) {
2047 return policy;
2048 }
2049 }
2050 return null;
2051 }
2052
2053 @Override
2054 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2055 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2056
2057 // only returns usage summary, so we don't require caller to have
2058 // READ_NETWORK_USAGE_HISTORY.
2059 final long token = Binder.clearCallingIdentity();
2060 try {
2061 return getNetworkQuotaInfoUnchecked(state);
2062 } finally {
2063 Binder.restoreCallingIdentity(token);
2064 }
2065 }
2066
2067 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2068 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2069
2070 final NetworkPolicy policy;
2071 synchronized (mRulesLock) {
2072 policy = findPolicyForNetworkLocked(ident);
2073 }
2074
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002075 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002076 // missing policy means we can't derive useful quota info
2077 return null;
2078 }
2079
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002080 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002081
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002082 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002083 final long start = computeLastCycleBoundary(currentTime, policy);
2084 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002085 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002086
2087 // report soft and hard limits under policy
2088 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2089 : NetworkQuotaInfo.NO_LIMIT;
2090 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2091 : NetworkQuotaInfo.NO_LIMIT;
2092
2093 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2094 }
2095
Jeff Sharkey46645002011-07-27 21:11:21 -07002096 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002097 public boolean isNetworkMetered(NetworkState state) {
2098 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2099
Jeff Sharkeyf166f482012-04-30 15:59:21 -07002100 // roaming networks are always considered metered
2101 if (ident.getRoaming()) {
2102 return true;
2103 }
2104
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002105 final NetworkPolicy policy;
2106 synchronized (mRulesLock) {
2107 policy = findPolicyForNetworkLocked(ident);
2108 }
2109
2110 if (policy != null) {
2111 return policy.metered;
2112 } else {
Wei Liub8eaf452016-01-25 10:32:27 -08002113 if (state.networkInfo == null) {
2114 return false;
2115 }
2116
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002117 final int type = state.networkInfo.getType();
2118 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
2119 return true;
2120 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002121 return false;
2122 }
2123 }
2124
2125 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002126 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002127 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002128
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002129 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2130
Dianne Hackborn497175b2014-07-01 12:56:08 -07002131 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002132 for (String arg : args) {
2133 argSet.add(arg);
2134 }
2135
Jeff Sharkey1b861272011-05-22 00:34:52 -07002136 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002137 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002138 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2139 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002140 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002141
Jeff Sharkey32566012014-12-02 18:30:14 -08002142 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002143 updateNetworkEnabledLocked();
2144 updateNetworkRulesLocked();
2145 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002146 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002147
2148 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002149 return;
2150 }
2151
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002152 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07002153 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002154 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002155 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002156 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002157 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002158 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2159 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002160 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002161 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002162
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07002163 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2164
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002165 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002166 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002167 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002168 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002169 final int uid = mUidPolicy.keyAt(i);
2170 final int policy = mUidPolicy.valueAt(i);
2171 fout.print("UID=");
2172 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002173 fout.print(" policy=");
Jeff Sharkeydc988062015-09-14 10:09:47 -07002174 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002175 fout.println();
2176 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002177 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002178
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002179 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2180 if (size > 0) {
2181 fout.println("Power save whitelist (except idle) app ids:");
2182 fout.increaseIndent();
2183 for (int i = 0; i < size; i++) {
2184 fout.print("UID=");
2185 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2186 fout.print(": ");
2187 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2188 fout.println();
2189 }
2190 fout.decreaseIndent();
2191 }
2192
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002193 size = mPowerSaveWhitelistAppIds.size();
2194 if (size > 0) {
2195 fout.println("Power save whitelist app ids:");
2196 fout.increaseIndent();
2197 for (int i = 0; i < size; i++) {
2198 fout.print("UID=");
2199 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2200 fout.print(": ");
2201 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2202 fout.println();
2203 }
2204 fout.decreaseIndent();
2205 }
2206
Felipe Lemeb85a6372016-01-14 16:16:16 -08002207 size = mRestrictBackgroundWhitelistUids.size();
2208 if (size > 0) {
2209 fout.println("Restrict background whitelist uids:");
2210 fout.increaseIndent();
2211 for (int i = 0; i < size; i++) {
2212 fout.print("UID=");
2213 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2214 fout.println();
2215 }
2216 fout.decreaseIndent();
2217 }
2218
Felipe Lemea9505cc2016-02-26 10:28:41 -08002219 size = mDefaultRestrictBackgroundWhitelistUids.size();
2220 if (size > 0) {
2221 fout.println("Default restrict background whitelist uids:");
2222 fout.increaseIndent();
2223 for (int i = 0; i < size; i++) {
2224 fout.print("UID=");
2225 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2226 fout.println();
2227 }
2228 fout.decreaseIndent();
2229 }
2230
2231 size = mRestrictBackgroundWhitelistRevokedUids.size();
2232 if (size > 0) {
2233 fout.println("Default restrict background whitelist uids revoked by users:");
2234 fout.increaseIndent();
2235 for (int i = 0; i < size; i++) {
2236 fout.print("UID=");
2237 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2238 fout.println();
2239 }
2240 fout.decreaseIndent();
2241 }
2242
Jeff Sharkey1b861272011-05-22 00:34:52 -07002243 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07002244 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002245 collectKeys(mUidRules, knownUids);
2246
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002247 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002248 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002249 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002250 for (int i = 0; i < size; i++) {
2251 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002252 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07002253 fout.print(uid);
2254
Jeff Sharkeydc988062015-09-14 10:09:47 -07002255 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002256 fout.print(" state=");
2257 fout.print(state);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002258 fout.print(state <= ActivityManager.PROCESS_STATE_TOP ? " (fg)" : " (bg)");
Dianne Hackborn497175b2014-07-01 12:56:08 -07002259
Jeff Sharkeydc988062015-09-14 10:09:47 -07002260 final int rule = mUidRules.get(uid, RULE_UNKNOWN);
2261 fout.print(" rule=");
2262 fout.print(DebugUtils.valueToString(NetworkPolicyManager.class, "RULE_", rule));
Jeff Sharkey1b861272011-05-22 00:34:52 -07002263
2264 fout.println();
2265 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002266 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002267 }
2268 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002269
2270 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002271 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2272 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002273 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002274 this, in, out, err, args, resultReceiver);
2275 }
2276
2277 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002278 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002279 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2280
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002281 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002282 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002283 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002284 }
2285
Dianne Hackborn497175b2014-07-01 12:56:08 -07002286 boolean isUidForegroundLocked(int uid) {
2287 // only really in foreground when screen is also on
2288 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002289 <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002290 }
2291
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002292 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002293 * Process state of UID changed; if needed, will trigger
2294 * {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002295 */
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002296 void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002297 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2298 if (oldUidState != uidState) {
2299 // state changed, push updated rules
2300 mUidState.put(uid, uidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002301 updateRulesForUidStateChangeLocked(uid, oldUidState, uidState);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002302 if (mDeviceIdleMode && isProcStateAllowedWhileIdle(oldUidState)
2303 != isProcStateAllowedWhileIdle(uidState)) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002304 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002305 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002306 }
2307 }
2308
2309 void removeUidStateLocked(int uid) {
2310 final int index = mUidState.indexOfKey(uid);
2311 if (index >= 0) {
2312 final int oldUidState = mUidState.valueAt(index);
2313 mUidState.removeAt(index);
2314 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
2315 updateRulesForUidStateChangeLocked(uid, oldUidState,
2316 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002317 if (mDeviceIdleMode) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002318 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002319 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002320 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002321 }
2322 }
2323
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002324 void updateRulesForUidStateChangeLocked(int uid, int oldUidState, int newUidState) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002325 final boolean oldForeground = oldUidState <= ActivityManager.PROCESS_STATE_TOP;
2326 final boolean newForeground = newUidState <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002327 if (oldForeground != newForeground) {
2328 updateRulesForUidLocked(uid);
2329 }
2330 }
2331
Jeff Sharkeya4620792011-05-20 15:29:23 -07002332 private void updateScreenOn() {
2333 synchronized (mRulesLock) {
2334 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002335 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002336 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002337 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002338 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002339 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002340 }
2341 }
2342
2343 /**
2344 * Update rules that might be changed by {@link #mScreenOn} value.
2345 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002346 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002347 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002348 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002349 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002350 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002351 final int uid = mUidState.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002352 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002353 }
2354 }
2355 }
2356
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002357 static boolean isProcStateAllowedWhileIdle(int procState) {
2358 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2359 }
2360
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002361 void updateRulesForDeviceIdleLocked() {
2362 if (mDeviceIdleMode) {
2363 // sync the whitelists before enable dozable chain. We don't care about the rules if
2364 // we are disabling the chain.
Jeff Sharkeydc988062015-09-14 10:09:47 -07002365 final SparseIntArray uidRules = mUidFirewallDozableRules;
2366 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002367 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002368 for (int ui = users.size() - 1; ui >= 0; ui--) {
2369 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002370 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002371 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2372 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2373 int uid = UserHandle.getUid(user.id, appId);
2374 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2375 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002376 }
2377 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2378 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2379 int uid = UserHandle.getUid(user.id, appId);
2380 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2381 }
2382 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002383 for (int i = mUidState.size() - 1; i >= 0; i--) {
2384 if (isProcStateAllowedWhileIdle(mUidState.valueAt(i))) {
2385 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2386 }
2387 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002388 setUidFirewallRules(FIREWALL_CHAIN_DOZABLE, uidRules);
2389 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002390
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002391 enableFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, mDeviceIdleMode);
2392 }
2393
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002394 void updateRuleForDeviceIdleLocked(int uid) {
2395 if (mDeviceIdleMode) {
2396 int appId = UserHandle.getAppId(uid);
2397 if (mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId)
2398 || isProcStateAllowedWhileIdle(mUidState.get(uid))) {
2399 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_ALLOW);
2400 } else {
2401 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
2402 }
2403 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002404
2405 updateRulesForUidLocked(uid);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002406 }
2407
2408 void updateRulesForAppIdleLocked() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002409 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2410 uidRules.clear();
2411
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002412 // Fully update the app idle firewall chain.
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002413 final IPackageManager ipm = AppGlobals.getPackageManager();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002414 final List<UserInfo> users = mUserManager.getUsers();
2415 for (int ui = users.size() - 1; ui >= 0; ui--) {
2416 UserInfo user = users.get(ui);
2417 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2418 for (int uid : idleUids) {
2419 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002420 // quick check: if this uid doesn't have INTERNET permission, it
2421 // doesn't have network access anyway, so it is a waste to mess
2422 // with it here.
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002423 if (hasInternetPermissions(uid)) {
2424 uidRules.put(uid, FIREWALL_RULE_DENY);
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002425 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002426 }
2427 }
2428 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002429
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002430 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2431 }
2432
2433 void updateRuleForAppIdleLocked(int uid) {
2434 if (!isUidValidForRules(uid)) return;
2435
2436 int appId = UserHandle.getAppId(uid);
2437 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)) {
2438 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2439 } else {
2440 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2441 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002442
2443 updateRulesForUidLocked(uid);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002444 }
2445
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002446 void updateRulesForAppIdleParoleLocked() {
2447 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2448 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Jeff Sharkeydc988062015-09-14 10:09:47 -07002449 updateRulesForUidsLocked(mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002450 }
2451
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002452 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002453 * Update rules that might be changed by {@link #mRestrictBackground},
2454 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002455 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002456 void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002457 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002458
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002459 updateRulesForDeviceIdleLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002460 updateRulesForAppIdleLocked();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002461
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002462 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002463 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002464 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey2a9e3f82015-12-18 10:57:58 -07002465 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS
2466 | PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002467
2468 for (UserInfo user : users) {
2469 for (ApplicationInfo app : apps) {
2470 final int uid = UserHandle.getUid(user.id, app.uid);
2471 updateRulesForUidLocked(uid);
2472 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002473 }
2474
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002475 // limit data usage for some internal system services
2476 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
2477 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002478
2479 // If the set of restricted networks may have changed, re-evaluate those.
2480 if (restrictedNetworksChanged) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002481 normalizePoliciesLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002482 updateNetworkRulesLocked();
2483 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002484 }
2485
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002486 void updateRulesForTempWhitelistChangeLocked() {
2487 final List<UserInfo> users = mUserManager.getUsers();
2488 for (UserInfo user : users) {
2489 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
2490 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2491 int uid = UserHandle.getUid(user.id, appId);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002492 updateRuleForAppIdleLocked(uid);
2493 updateRuleForDeviceIdleLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002494 }
2495 }
2496 }
2497
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002498 private static boolean isUidValidForRules(int uid) {
2499 // allow rules on specific system services, and any apps
2500 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002501 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002502 return true;
2503 }
2504
2505 return false;
2506 }
2507
Amith Yamasani15e472352015-04-24 19:06:07 -07002508 private boolean isUidIdle(int uid) {
2509 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2510 final int userId = UserHandle.getUserId(uid);
2511
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002512 if (!ArrayUtils.isEmpty(packages)) {
2513 for (String packageName : packages) {
2514 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2515 return false;
2516 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002517 }
2518 }
2519 return true;
2520 }
2521
Jeff Sharkeydc988062015-09-14 10:09:47 -07002522 void updateRulesForUidsLocked(SparseIntArray uids) {
2523 for (int i = 0; i < uids.size(); i++) {
2524 updateRulesForUidLocked(uids.keyAt(i));
2525 }
2526 }
2527
Amith Yamasani15e472352015-04-24 19:06:07 -07002528 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002529 * Checks if an uid has INTERNET permissions.
2530 * <p>
2531 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002532 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002533 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002534 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002535 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002536 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002537 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002538 }
2539 } catch (RemoteException e) {
2540 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002541 return true;
2542 }
2543
2544 /**
2545 * Applies network rules to bandwidth and firewall controllers based on uid policy.
2546 * @param uid The uid for which to apply the latest policy
2547 */
2548 void updateRulesForUidLocked(int uid) {
2549 if (!isUidValidForRules(uid) || !hasInternetPermissions(uid)) return;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002550
Dianne Hackborn497175b2014-07-01 12:56:08 -07002551 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2552 final boolean uidForeground = isUidForegroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002553
Jeff Sharkeydc988062015-09-14 10:09:47 -07002554 // Derive active rules based on policy and active state
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002555 int appId = UserHandle.getAppId(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002556 int uidRules = RULE_ALLOW_ALL;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002557 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002558 // uid in background, and policy says to block metered data
2559 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002560 } else if (mRestrictBackground) {
2561 if (!uidForeground) {
Felipe Lemeb85a6372016-01-14 16:16:16 -08002562 // uid in background, global background disabled, and this uid is not on the white
2563 // list of those allowed background access while global background is disabled
2564 if (!mRestrictBackgroundWhitelistUids.get(uid)) {
2565 uidRules = RULE_REJECT_METERED;
2566 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002567 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002568 } else if (mRestrictPower) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002569 final boolean whitelisted = mPowerSaveWhitelistExceptIdleAppIds.get(appId)
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002570 || mPowerSaveTempWhitelistAppIds.get(appId);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002571 if (!whitelisted && !uidForeground
2572 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
2573 // uid is in background, restrict power use mode is on (so we want to
2574 // restrict all background network access), and this uid is not on the
2575 // white list of those allowed background access.
2576 uidRules = RULE_REJECT_METERED;
2577 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002578 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002579
Jeff Sharkeydc988062015-09-14 10:09:47 -07002580 // Check dozable state, which is whitelist
2581 if (mFirewallChainStates.get(FIREWALL_CHAIN_DOZABLE)
2582 && mUidFirewallDozableRules.get(uid, FIREWALL_RULE_DEFAULT) != FIREWALL_RULE_ALLOW) {
2583 uidRules = RULE_REJECT_ALL;
2584 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002585
Jeff Sharkeydc988062015-09-14 10:09:47 -07002586 // Check standby state, which is blacklist
2587 if (mFirewallChainStates.get(FIREWALL_CHAIN_STANDBY)
2588 && mUidFirewallStandbyRules.get(uid, FIREWALL_RULE_DEFAULT) == FIREWALL_RULE_DENY) {
2589 uidRules = RULE_REJECT_ALL;
2590 }
2591
2592 final int oldRules = mUidRules.get(uid);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002593 if (uidRules == RULE_ALLOW_ALL) {
2594 mUidRules.delete(uid);
2595 } else {
2596 mUidRules.put(uid, uidRules);
2597 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002598
Jeff Sharkeydc988062015-09-14 10:09:47 -07002599 final boolean rejectMetered = (uidRules == RULE_REJECT_METERED);
2600 setUidNetworkRules(uid, rejectMetered);
Amith Yamasani15e472352015-04-24 19:06:07 -07002601
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002602 // dispatch changed rule to existing listeners
Amith Yamasani15e472352015-04-24 19:06:07 -07002603 if (oldRules != uidRules) {
2604 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
2605 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002606
2607 try {
2608 // adjust stats accounting based on foreground status
2609 mNetworkStats.setUidForeground(uid, uidForeground);
2610 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002611 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002612 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002613 }
2614
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002615 private class AppIdleStateChangeListener
2616 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2617
2618 @Override
2619 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2620 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002621 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
2622 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002623 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002624 updateRuleForAppIdleLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002625 }
2626 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002627 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002628 }
2629
2630 @Override
2631 public void onParoleStateChanged(boolean isParoleOn) {
2632 synchronized (mRulesLock) {
2633 updateRulesForAppIdleParoleLocked();
2634 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002635 }
2636 }
2637
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002638 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002639 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002640 public boolean handleMessage(Message msg) {
2641 switch (msg.what) {
2642 case MSG_RULES_CHANGED: {
2643 final int uid = msg.arg1;
2644 final int uidRules = msg.arg2;
2645 final int length = mListeners.beginBroadcast();
2646 for (int i = 0; i < length; i++) {
2647 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2648 if (listener != null) {
2649 try {
2650 listener.onUidRulesChanged(uid, uidRules);
2651 } catch (RemoteException e) {
2652 }
2653 }
2654 }
2655 mListeners.finishBroadcast();
2656 return true;
2657 }
2658 case MSG_METERED_IFACES_CHANGED: {
2659 final String[] meteredIfaces = (String[]) msg.obj;
2660 final int length = mListeners.beginBroadcast();
2661 for (int i = 0; i < length; i++) {
2662 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2663 if (listener != null) {
2664 try {
2665 listener.onMeteredIfacesChanged(meteredIfaces);
2666 } catch (RemoteException e) {
2667 }
2668 }
2669 }
2670 mListeners.finishBroadcast();
2671 return true;
2672 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002673 case MSG_LIMIT_REACHED: {
2674 final String iface = (String) msg.obj;
2675
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002676 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002677 synchronized (mRulesLock) {
2678 if (mMeteredIfaces.contains(iface)) {
2679 try {
2680 // force stats update to make sure we have
2681 // numbers that caused alert to trigger.
2682 mNetworkStats.forceUpdate();
2683 } catch (RemoteException e) {
2684 // ignored; service lives in system_server
2685 }
2686
2687 updateNetworkEnabledLocked();
2688 updateNotificationsLocked();
2689 }
2690 }
2691 return true;
2692 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002693 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2694 final boolean restrictBackground = msg.arg1 != 0;
2695 final int length = mListeners.beginBroadcast();
2696 for (int i = 0; i < length; i++) {
2697 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2698 if (listener != null) {
2699 try {
2700 listener.onRestrictBackgroundChanged(restrictBackground);
2701 } catch (RemoteException e) {
2702 }
2703 }
2704 }
2705 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08002706 final Intent intent =
2707 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
2708 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2709 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2710 return true;
2711 }
2712 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
2713 final int uid = msg.arg1;
2714 final PackageManager pm = mContext.getPackageManager();
2715 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme86e5a012016-02-16 16:26:05 -08002716 if (packages != null) {
2717 final int userId = UserHandle.getUserId(uid);
2718 for (String packageName : packages) {
2719 final Intent intent = new Intent(
2720 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
2721 intent.setPackage(packageName);
2722 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2723 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
2724 }
2725 } else {
2726 Slog.w(TAG, "no packages for uid " + uid);
Felipe Leme9778f762016-01-27 14:46:39 -08002727 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002728 return true;
2729 }
2730 case MSG_ADVISE_PERSIST_THRESHOLD: {
2731 final long lowestRule = (Long) msg.obj;
2732 try {
2733 // make sure stats are recorded frequently enough; we aim
2734 // for 2MB threshold for 2GB/month rules.
2735 final long persistThreshold = lowestRule / 1000;
2736 mNetworkStats.advisePersistThreshold(persistThreshold);
2737 } catch (RemoteException e) {
2738 // ignored; service lives in system_server
2739 }
2740 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002741 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002742 case MSG_SCREEN_ON_CHANGED: {
2743 updateScreenOn();
2744 return true;
2745 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002746 default: {
2747 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002748 }
2749 }
2750 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002751 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002752
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002753 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002754 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002755 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002756 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002757 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002758 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002759 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002760 }
2761 }
2762
2763 private void removeInterfaceQuota(String iface) {
2764 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002765 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002766 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002767 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002768 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002769 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002770 }
2771 }
2772
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002773 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2774 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002775 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002776 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002777 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002778 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002779 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002780 }
2781 }
2782
Amith Yamasani15e472352015-04-24 19:06:07 -07002783 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002784 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
2785 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
2786 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07002787 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002788 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002789 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002790 int size = uidRules.size();
2791 int[] uids = new int[size];
2792 int[] rules = new int[size];
2793 for(int index = size - 1; index >= 0; --index) {
2794 uids[index] = uidRules.keyAt(index);
2795 rules[index] = uidRules.valueAt(index);
2796 }
2797 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002798 } catch (IllegalStateException e) {
2799 Log.wtf(TAG, "problem setting firewall uid rules", e);
2800 } catch (RemoteException e) {
2801 // ignored; service lives in system_server
2802 }
2803 }
2804
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002805 /**
2806 * Add or remove a uid to the firewall blacklist for all network ifaces.
2807 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002808 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002809 if (chain == FIREWALL_CHAIN_DOZABLE) {
2810 mUidFirewallDozableRules.put(uid, rule);
2811 } else if (chain == FIREWALL_CHAIN_STANDBY) {
2812 mUidFirewallStandbyRules.put(uid, rule);
2813 }
2814
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002815 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002816 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002817 } catch (IllegalStateException e) {
2818 Log.wtf(TAG, "problem setting firewall uid rules", e);
2819 } catch (RemoteException e) {
2820 // ignored; service lives in system_server
2821 }
2822 }
2823
2824 /**
2825 * Add or remove a uid to the firewall blacklist for all network ifaces.
2826 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002827 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002828 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
2829 mFirewallChainStates.get(chain) == enable) {
2830 // All is the same, nothing to do.
2831 return;
2832 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002833 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002834 try {
2835 mNetworkManager.setFirewallChainEnabled(chain, enable);
2836 } catch (IllegalStateException e) {
2837 Log.wtf(TAG, "problem enable firewall chain", e);
2838 } catch (RemoteException e) {
2839 // ignored; service lives in system_server
2840 }
2841 }
2842
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002843 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2844 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002845 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002846 } catch (RuntimeException e) {
2847 Slog.w(TAG, "problem reading network stats: " + e);
2848 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002849 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002850 // ignored; service lives in system_server
2851 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002852 }
2853 }
2854
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002855 private boolean isBandwidthControlEnabled() {
2856 final long token = Binder.clearCallingIdentity();
2857 try {
2858 return mNetworkManager.isBandwidthControlEnabled();
2859 } catch (RemoteException e) {
2860 // ignored; service lives in system_server
2861 return false;
2862 } finally {
2863 Binder.restoreCallingIdentity(token);
2864 }
2865 }
2866
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002867 /**
2868 * Try refreshing {@link #mTime} when stale.
2869 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002870 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002871 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002872 mTime.forceRefresh();
2873 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002874 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002875
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002876 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002877 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2878 }
2879
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002880 private static Intent buildAllowBackgroundDataIntent() {
2881 return new Intent(ACTION_ALLOW_BACKGROUND);
2882 }
2883
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002884 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2885 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2886 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2887 return intent;
2888 }
2889
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002890 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2891 final Intent intent = new Intent();
2892 intent.setComponent(new ComponentName(
2893 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2894 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2895 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2896 return intent;
2897 }
2898
2899 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2900 final Intent intent = new Intent();
2901 intent.setComponent(new ComponentName(
2902 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2903 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2904 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2905 return intent;
2906 }
2907
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002908 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002909 public void addIdleHandler(IdleHandler handler) {
2910 mHandler.getLooper().getQueue().addIdleHandler(handler);
2911 }
2912
Jeff Sharkey1b861272011-05-22 00:34:52 -07002913 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2914 final int size = source.size();
2915 for (int i = 0; i < size; i++) {
2916 target.put(source.keyAt(i), true);
2917 }
2918 }
2919
Stuart Scottf1fb3972015-04-02 18:00:02 -07002920 @Override
2921 public void factoryReset(String subscriber) {
2922 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2923
Stuart Scotte3e314d2015-04-20 14:07:45 -07002924 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
2925 return;
2926 }
2927
Stuart Scottf1fb3972015-04-02 18:00:02 -07002928 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07002929 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07002930 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
2931 for (NetworkPolicy policy : policies) {
2932 if (policy.template.equals(template)) {
2933 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2934 policy.inferred = false;
2935 policy.clearSnooze();
2936 }
2937 }
2938 setNetworkPolicies(policies);
2939
2940 // Turn restrict background data off
2941 setRestrictBackground(false);
2942
Stuart Scotte3e314d2015-04-20 14:07:45 -07002943 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
2944 // Remove app's "restrict background data" flag
2945 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
2946 setUidPolicy(uid, POLICY_NONE);
2947 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07002948 }
2949 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002950
2951 private class MyPackageMonitor extends PackageMonitor {
2952
2953 @Override
2954 public void onPackageRemoved(String packageName, int uid) {
2955 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
2956 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002957 removeRestrictBackgroundWhitelistedUidLocked(uid, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002958 }
2959 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002960 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002961}