blob: 38ebc8003bc71a00be9297cf7642ebabf5d4c272 [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey1b861272011-05-22 00:34:52 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070022import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070032import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070033import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070034import static android.net.ConnectivityManager.isNetworkTypeMobile;
35import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070036import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070037import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070038import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070039import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070040import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
41import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
42import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070043import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070044import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -070045import static android.net.NetworkPolicyManager.POLICY_ALLOW_BACKGROUND_BATTERY_SAVE;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070046import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070047import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070048import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeydc988062015-09-14 10:09:47 -070049import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070050import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeydc988062015-09-14 10:09:47 -070051import static android.net.NetworkPolicyManager.RULE_UNKNOWN;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070052import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070053import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
54import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070055import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
56import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070057import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080058import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070059import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
60import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
61import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
62import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
63import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
64import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
65import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070066import static android.text.format.DateUtils.DAY_IN_MILLIS;
Jeff Sharkey854b2b12012-04-13 16:03:40 -070067import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070068import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070069import static com.android.internal.util.XmlUtils.readBooleanAttribute;
70import static com.android.internal.util.XmlUtils.readIntAttribute;
71import static com.android.internal.util.XmlUtils.readLongAttribute;
72import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
73import static com.android.internal.util.XmlUtils.writeIntAttribute;
74import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070075import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070076import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070077import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080078import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070079import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070080
Dianne Hackborn88e98df2015-03-23 13:29:14 -070081import android.Manifest;
Dianne Hackborn497175b2014-07-01 12:56:08 -070082import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070083import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070084import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070085import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070086import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070087import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070088import android.app.Notification;
89import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -070090import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -070091import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070092import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070093import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070094import android.content.Intent;
95import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070096import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070097import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070098import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -070099import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700100import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700101import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700102import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700103import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700104import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700105import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700106import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700107import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700108import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700109import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700110import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700111import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700112import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700113import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700114import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700115import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700116import android.net.wifi.WifiConfiguration;
117import android.net.wifi.WifiInfo;
118import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700119import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700120import android.os.Environment;
121import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700122import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700123import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700124import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700125import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700126import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700127import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700128import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700129import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700130import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700131import android.os.RemoteException;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700132import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700133import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700134import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700135import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800136import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700137import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700138import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700139import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700140import android.util.ArrayMap;
141import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700142import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700143import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700144import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700145import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700146import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700147import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700148import android.util.SparseBooleanArray;
149import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700150import android.util.TrustedTime;
151import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700152
Jeff Sharkey32566012014-12-02 18:30:14 -0800153import libcore.io.IoUtils;
154
Jeff Sharkey497e4432011-06-14 17:27:29 -0700155import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800156import com.android.internal.annotations.VisibleForTesting;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800157import com.android.internal.content.PackageMonitor;
Jeff Sharkey32566012014-12-02 18:30:14 -0800158import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700159import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700160import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700161import com.android.server.DeviceIdleController;
162import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700163import com.android.server.LocalServices;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700164import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700165
166import org.xmlpull.v1.XmlPullParser;
167import org.xmlpull.v1.XmlPullParserException;
168import org.xmlpull.v1.XmlSerializer;
169
170import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700171import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700172import java.io.FileInputStream;
173import java.io.FileNotFoundException;
174import java.io.FileOutputStream;
175import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700176import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100177import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700178import java.util.ArrayList;
179import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700180import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700181
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700182/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700183 * Service that maintains low-level network policy rules, using
184 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700185 * <p>
186 * Derives active rules by combining a given policy with other system status,
187 * and delivers to listeners, such as {@link ConnectivityManager}, for
188 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700189 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700190public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700191 private static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700192 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700193 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700194
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700195 private static final int VERSION_INIT = 1;
196 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700197 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800198 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800199 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800200 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700201 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700202 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700203 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700204 private static final int VERSION_SWITCH_UID = 10;
205 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700206
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800207 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700208 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800209 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700210 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800211 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700212 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700213
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700214 private static final String TAG_POLICY_LIST = "policy-list";
215 private static final String TAG_NETWORK_POLICY = "network-policy";
216 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700217 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800218 private static final String TAG_WHITELIST = "whitelist";
219 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700220
221 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700222 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700223 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
224 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700225 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700226 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800227 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700228 private static final String ATTR_WARNING_BYTES = "warningBytes";
229 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700230 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800231 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
232 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800233 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700234 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700235 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700236 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700237 private static final String ATTR_POLICY = "policy";
238
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700239 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
240
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800241 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800242 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800243 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800244 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700245
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700246 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
247
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700248 private static final int MSG_RULES_CHANGED = 1;
249 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800250 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800251 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700252 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700253 private static final int MSG_SCREEN_ON_CHANGED = 8;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700254
Jeff Sharkey75279902011-05-24 18:39:45 -0700255 private final Context mContext;
256 private final IActivityManager mActivityManager;
257 private final IPowerManager mPowerManager;
258 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700259 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700260 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700261 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700262 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700263
264 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700265 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700266 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700267 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700268
Dianne Hackborn497175b2014-07-01 12:56:08 -0700269 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700270
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700271 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700272 volatile boolean mScreenOn;
273 volatile boolean mRestrictBackground;
274 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700275 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700276
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700277 private final boolean mSuppressDefaultPolicy;
278
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700279 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800280 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700281 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800282 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700283
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700284 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700285 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700286 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800287 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700288
Jeff Sharkeydc988062015-09-14 10:09:47 -0700289 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
290 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
291
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700292 /** Set of states for the child firewall chains. True if the chain is active. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700293 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
294
Jeff Sharkey32566012014-12-02 18:30:14 -0800295 /**
296 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700297 * in power save mode, except device idle (doze) still applies.
298 * TODO: An int array might be sufficient
299 */
300 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
301
302 /**
303 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800304 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700305 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800306 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700307 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700308
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700309 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
310
Felipe Lemeb85a6372016-01-14 16:16:16 -0800311 /**
312 * UIDs that have been white-listed to avoid restricted background.
313 */
314 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
315
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700316 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800317 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700318 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800319 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700320
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700321 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700322 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700323
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700324 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800325 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700326
Jeff Sharkey32566012014-12-02 18:30:14 -0800327 private final RemoteCallbackList<INetworkPolicyListener>
328 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700329
Dianne Hackborn497175b2014-07-01 12:56:08 -0700330 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700331
332 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700333
Svet Ganov16a16892015-04-16 10:32:04 -0700334 private final AppOpsManager mAppOps;
335
Felipe Lemeb85a6372016-01-14 16:16:16 -0800336 private final MyPackageMonitor mPackageMonitor;
337
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700338 // TODO: keep whitelist of system-critical services that should never have
339 // rules enforced, such as system, phone, and radio UIDs.
340
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700341 // TODO: migrate notifications to SystemUI
342
Jeff Sharkey75279902011-05-24 18:39:45 -0700343 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700344 IPowerManager powerManager, INetworkStatsService networkStats,
345 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700346 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700347 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700348 }
349
350 private static File getSystemDir() {
351 return new File(Environment.getDataDirectory(), "system");
352 }
353
354 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700355 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700356 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
357 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700358 mContext = checkNotNull(context, "missing context");
359 mActivityManager = checkNotNull(activityManager, "missing activityManager");
360 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700361 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700362 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700363 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700364 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700365 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700366 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700367
Amith Yamasani450a16b2013-09-18 16:28:50 -0700368 HandlerThread thread = new HandlerThread(TAG);
369 thread.start();
370 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700371
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700372 mSuppressDefaultPolicy = suppressDefaultPolicy;
373
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700374 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700375
376 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800377
378 mPackageMonitor = new MyPackageMonitor();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700379 }
380
381 public void bindConnectivityManager(IConnectivityManager connManager) {
382 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700383 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700384
Jeff Sharkey497e4432011-06-14 17:27:29 -0700385 public void bindNotificationManager(INotificationManager notifManager) {
386 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
387 }
388
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700389 void updatePowerSaveWhitelistLocked() {
390 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700391 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
392 mPowerSaveWhitelistExceptIdleAppIds.clear();
393 if (whitelist != null) {
394 for (int uid : whitelist) {
395 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
396 }
397 }
398 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700399 mPowerSaveWhitelistAppIds.clear();
400 if (whitelist != null) {
401 for (int uid : whitelist) {
402 mPowerSaveWhitelistAppIds.put(uid, true);
403 }
404 }
405 } catch (RemoteException e) {
406 }
407 }
408
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700409 void updatePowerSaveTempWhitelistLocked() {
410 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700411 // Clear the states of the current whitelist
412 final int N = mPowerSaveTempWhitelistAppIds.size();
413 for (int i = 0; i < N; i++) {
414 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
415 }
416 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700417 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700418 if (whitelist != null) {
419 for (int uid : whitelist) {
420 mPowerSaveTempWhitelistAppIds.put(uid, true);
421 }
422 }
423 } catch (RemoteException e) {
424 }
425 }
426
Amith Yamasani06f08062015-06-12 13:23:33 -0700427 /**
428 * Remove unnecessary entries in the temp whitelist
429 */
430 void purgePowerSaveTempWhitelistLocked() {
431 final int N = mPowerSaveTempWhitelistAppIds.size();
432 for (int i = N - 1; i >= 0; i--) {
433 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
434 mPowerSaveTempWhitelistAppIds.removeAt(i);
435 }
436 }
437 }
438
Jeff Sharkeya4620792011-05-20 15:29:23 -0700439 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700440 if (!isBandwidthControlEnabled()) {
441 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
442 return;
443 }
444
Amith Yamasani15e472352015-04-24 19:06:07 -0700445 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
446
Felipe Lemeb85a6372016-01-14 16:16:16 -0800447 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
448
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700449 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700450 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700451 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
452 mPowerManagerInternal.registerLowPowerModeObserver(
453 new PowerManagerInternal.LowPowerModeListener() {
454 @Override
455 public void onLowPowerModeChanged(boolean enabled) {
456 synchronized (mRulesLock) {
457 if (mRestrictPower != enabled) {
458 mRestrictPower = enabled;
459 updateRulesForGlobalChangeLocked(true);
460 }
461 }
462 }
463 });
464 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700465 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700466
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700467 // read policy from disk
468 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700469
Jeff Sharkeydc988062015-09-14 10:09:47 -0700470 updateRulesForGlobalChangeLocked(false);
471 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700472 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700473
Jeff Sharkeya4620792011-05-20 15:29:23 -0700474 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700475
Jeff Sharkeya4620792011-05-20 15:29:23 -0700476 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700477 mActivityManager.registerUidObserver(mUidObserver,
478 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700479 mNetworkManager.registerObserver(mAlertObserver);
480 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700481 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700482 }
483
Jeff Sharkeya4620792011-05-20 15:29:23 -0700484 // TODO: traverse existing processes to know foreground state, or have
485 // activitymanager dispatch current state when new observer attached.
486
487 final IntentFilter screenFilter = new IntentFilter();
488 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
489 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700490 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700491
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700492 // listen for changes to power save whitelist
493 final IntentFilter whitelistFilter = new IntentFilter(
494 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
495 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
496
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700497 DeviceIdleController.LocalService deviceIdleService
498 = LocalServices.getService(DeviceIdleController.LocalService.class);
499 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
500
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700501 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900502 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700503 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
504
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700505 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700506 final IntentFilter packageFilter = new IntentFilter();
507 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700508 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700509 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700510
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700511 // listen for UID changes to update policy
512 mContext.registerReceiver(
513 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
514
515 // listen for user changes to update policy
516 final IntentFilter userFilter = new IntentFilter();
517 userFilter.addAction(ACTION_USER_ADDED);
518 userFilter.addAction(ACTION_USER_REMOVED);
519 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
520
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700521 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700522 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
523 mContext.registerReceiver(
524 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
525
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700526 // listen for restrict background changes from notifications
527 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
528 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
529
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800530 // listen for snooze warning from notifications
531 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
532 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
533 MANAGE_NETWORK_POLICY, mHandler);
534
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700535 // listen for configured wifi networks to be removed
536 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700537 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700538
539 // listen for wifi state changes to catch metered hint
540 final IntentFilter wifiStateFilter = new IntentFilter(
541 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700542 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700543
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700544 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700545
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700546 }
547
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700548 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700549 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700550 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700551 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700552 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700553 }
554
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700555 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700556 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700557 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700558 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700559 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700560
561 @Override public void onUidActive(int uid) throws RemoteException {
562 }
563
564 @Override public void onUidIdle(int uid) throws RemoteException {
565 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700566 };
567
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700568 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700569 @Override
570 public void onReceive(Context context, Intent intent) {
571 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
572 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700573 updatePowerSaveWhitelistLocked();
574 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700575 }
576 }
577 };
578
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700579 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
580 @Override
581 public void run() {
582 synchronized (mRulesLock) {
583 updatePowerSaveTempWhitelistLocked();
584 updateRulesForTempWhitelistChangeLocked();
585 purgePowerSaveTempWhitelistLocked();
586 }
587 }
588 };
589
590 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700591 @Override
592 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800593 // screen-related broadcasts are protected by system, no need
594 // for permissions check.
595 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700596 }
597 };
598
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700599 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700600 @Override
601 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700602 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700603
604 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700605 final int uid = intent.getIntExtra(EXTRA_UID, -1);
606 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700607
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700608 if (ACTION_PACKAGE_ADDED.equals(action)) {
609 // update rules for UID, since it might be subject to
610 // global background data policy
611 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
612 synchronized (mRulesLock) {
613 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700614 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700615 }
616 }
617 };
618
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700619 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700620 @Override
621 public void onReceive(Context context, Intent intent) {
622 // on background handler thread, and UID_REMOVED is protected
623
624 final int uid = intent.getIntExtra(EXTRA_UID, -1);
625 if (uid == -1) return;
626
627 // remove any policy and update rules to clean up
628 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
629 synchronized (mRulesLock) {
630 mUidPolicy.delete(uid);
631 updateRulesForUidLocked(uid);
632 writePolicyLocked();
633 }
634 }
635 };
636
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700637 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700638 @Override
639 public void onReceive(Context context, Intent intent) {
640 // on background handler thread, and USER_ADDED and USER_REMOVED
641 // broadcasts are protected
642
643 final String action = intent.getAction();
644 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
645 if (userId == -1) return;
646
Amith Yamasani15e472352015-04-24 19:06:07 -0700647 switch (action) {
648 case ACTION_USER_REMOVED:
649 case ACTION_USER_ADDED:
650 synchronized (mRulesLock) {
651 // Remove any policies for given user; both cleaning up after a
652 // USER_REMOVED, and one last sanity check during USER_ADDED
653 removePoliciesForUserLocked(userId);
654 // Update global restrict for new user
655 updateRulesForGlobalChangeLocked(true);
656 }
657 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700658 }
659 }
660 };
661
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700662 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700663 * Receiver that watches for {@link INetworkStatsService} updates, which we
664 * use to check against {@link NetworkPolicy#warningBytes}.
665 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700666 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700667 @Override
668 public void onReceive(Context context, Intent intent) {
669 // on background handler thread, and verified
670 // READ_NETWORK_USAGE_HISTORY permission above.
671
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800672 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700673 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700674 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700675 updateNotificationsLocked();
676 }
677 }
678 };
679
680 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700681 * Receiver that watches for {@link Notification} control of
682 * {@link #mRestrictBackground}.
683 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700684 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700685 @Override
686 public void onReceive(Context context, Intent intent) {
687 // on background handler thread, and verified MANAGE_NETWORK_POLICY
688 // permission above.
689
690 setRestrictBackground(false);
691 }
692 };
693
694 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800695 * Receiver that watches for {@link Notification} control of
696 * {@link NetworkPolicy#lastWarningSnooze}.
697 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700698 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800699 @Override
700 public void onReceive(Context context, Intent intent) {
701 // on background handler thread, and verified MANAGE_NETWORK_POLICY
702 // permission above.
703
704 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
705 performSnooze(template, TYPE_WARNING);
706 }
707 };
708
709 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700710 * Receiver that watches for {@link WifiConfiguration} to be changed.
711 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700712 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700713 @Override
714 public void onReceive(Context context, Intent intent) {
715 // on background handler thread, and verified CONNECTIVITY_INTERNAL
716 // permission above.
717
718 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
719 if (reason == CHANGE_REASON_REMOVED) {
720 final WifiConfiguration config = intent.getParcelableExtra(
721 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700722 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800723 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700724 synchronized (mRulesLock) {
725 if (mNetworkPolicy.containsKey(template)) {
726 mNetworkPolicy.remove(template);
727 writePolicyLocked();
728 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700729 }
730 }
731 }
732 }
733 };
734
735 /**
736 * Receiver that watches {@link WifiInfo} state changes to infer metered
737 * state. Ignores hints when policy is user-defined.
738 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700739 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700740 @Override
741 public void onReceive(Context context, Intent intent) {
742 // on background handler thread, and verified CONNECTIVITY_INTERNAL
743 // permission above.
744
745 // ignore when not connected
746 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
747 if (!netInfo.isConnected()) return;
748
749 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
750 final boolean meteredHint = info.getMeteredHint();
751
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800752 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700753 synchronized (mRulesLock) {
754 NetworkPolicy policy = mNetworkPolicy.get(template);
755 if (policy == null && meteredHint) {
756 // policy doesn't exist, and AP is hinting that it's
757 // metered: create an inferred policy.
758 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
759 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
760 meteredHint, true);
761 addNetworkPolicyLocked(policy);
762
763 } else if (policy != null && policy.inferred) {
764 // policy exists, and was inferred: update its current
765 // metered state.
766 policy.metered = meteredHint;
767
768 // since this is inferred for each wifi session, just update
769 // rules without persisting.
770 updateNetworkRulesLocked();
771 }
772 }
773 }
774 };
775
776 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700777 * Observer that watches for {@link INetworkManagementService} alerts.
778 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700779 final private INetworkManagementEventObserver mAlertObserver
780 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700781 @Override
782 public void limitReached(String limitName, String iface) {
783 // only someone like NMS should be calling us
784 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
785
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800786 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
787 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700788 }
789 }
790 };
791
792 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700793 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
794 * to show visible notifications as needed.
795 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700796 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700797 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
798
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700799 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700800 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700801 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700802
803 // TODO: when switching to kernel notifications, compute next future
804 // cycle boundary to recompute notifications.
805
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700806 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800807 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700808 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
809 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700810 // ignore policies that aren't relevant to user
811 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700812 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700813
Jeff Sharkey497e4432011-06-14 17:27:29 -0700814 final long start = computeLastCycleBoundary(currentTime, policy);
815 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700816 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700817
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700818 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800819 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700820 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
821 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700822 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
823 notifyOverLimitLocked(policy.template);
824 }
825
Jeff Sharkey497e4432011-06-14 17:27:29 -0700826 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700827 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700828
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800829 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700830 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700831 }
832 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700833 }
834
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700835 // ongoing notification when restricting background data
836 if (mRestrictBackground) {
837 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700838 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700839
840 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700841 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
842 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700843 if (!mActiveNotifs.contains(tag)) {
844 cancelNotification(tag);
845 }
846 }
847 }
848
849 /**
850 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700851 * current device state, such as when
852 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
853 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700854 */
855 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800856 if (template.isMatchRuleMobile()) {
857 final TelephonyManager tele = TelephonyManager.from(mContext);
858 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700859
Jeff Sharkey32566012014-12-02 18:30:14 -0800860 // Mobile template is relevant when any active subscriber matches
861 final int[] subIds = sub.getActiveSubscriptionIdList();
862 for (int subId : subIds) {
863 final String subscriberId = tele.getSubscriberId(subId);
864 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
865 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
866 if (template.matches(probeIdent)) {
867 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700868 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800869 }
870 return false;
871 } else {
872 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700873 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700874 }
875
876 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700877 * Notify that given {@link NetworkTemplate} is over
878 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
879 */
880 private void notifyOverLimitLocked(NetworkTemplate template) {
881 if (!mOverLimitNotified.contains(template)) {
882 mContext.startActivity(buildNetworkOverLimitIntent(template));
883 mOverLimitNotified.add(template);
884 }
885 }
886
887 private void notifyUnderLimitLocked(NetworkTemplate template) {
888 mOverLimitNotified.remove(template);
889 }
890
891 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700892 * Build unique tag that identifies an active {@link NetworkPolicy}
893 * notification of a specific type, like {@link #TYPE_LIMIT}.
894 */
895 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700896 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700897 }
898
899 /**
900 * Show notification for combined {@link NetworkPolicy} and specific type,
901 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
902 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700903 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700904 final String tag = buildNotificationTag(policy, type);
905 final Notification.Builder builder = new Notification.Builder(mContext);
906 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800907 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700908 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200909 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700910
911 final Resources res = mContext.getResources();
912 switch (type) {
913 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700914 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700915 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700916
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700917 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700918 builder.setTicker(title);
919 builder.setContentTitle(title);
920 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700921
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800922 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
923 builder.setDeleteIntent(PendingIntent.getBroadcast(
924 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
925
926 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700927 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800928 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
929
Jeff Sharkey497e4432011-06-14 17:27:29 -0700930 break;
931 }
932 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700933 final CharSequence body = res.getText(R.string.data_usage_limit_body);
934
935 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -0400936 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700937 switch (policy.template.getMatchRule()) {
938 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700939 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700940 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700941 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700942 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700943 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700944 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700945 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700946 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700947 case MATCH_WIFI:
948 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -0400949 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700950 break;
951 default:
952 title = null;
953 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700954 }
955
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800956 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -0400957 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700958 builder.setTicker(title);
959 builder.setContentTitle(title);
960 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700961
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700962 final Intent intent = buildNetworkOverLimitIntent(policy.template);
963 builder.setContentIntent(PendingIntent.getActivity(
964 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
965 break;
966 }
967 case TYPE_LIMIT_SNOOZED: {
968 final long overBytes = totalBytes - policy.limitBytes;
969 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
970 Formatter.formatFileSize(mContext, overBytes));
971
972 final CharSequence title;
973 switch (policy.template.getMatchRule()) {
974 case MATCH_MOBILE_3G_LOWER:
975 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
976 break;
977 case MATCH_MOBILE_4G:
978 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
979 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700980 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700981 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
982 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700983 case MATCH_WIFI:
984 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
985 break;
986 default:
987 title = null;
988 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700989 }
990
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800991 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700992 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700993 builder.setTicker(title);
994 builder.setContentTitle(title);
995 builder.setContentText(body);
996
997 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700998 builder.setContentIntent(PendingIntent.getActivity(
999 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001000 break;
1001 }
1002 }
1003
1004 // TODO: move to NotificationManager once we can mock it
1005 try {
1006 final String packageName = mContext.getPackageName();
1007 final int[] idReceived = new int[1];
1008 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001009 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001010 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001011 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001012 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001013 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001014 }
1015 }
1016
1017 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001018 * Show ongoing notification to reflect that {@link #mRestrictBackground}
1019 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -07001020 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001021 private void enqueueRestrictedNotification(String tag) {
1022 final Resources res = mContext.getResources();
1023 final Notification.Builder builder = new Notification.Builder(mContext);
1024
1025 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
1026 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
1027
1028 builder.setOnlyAlertOnce(true);
1029 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001030 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001031 builder.setTicker(title);
1032 builder.setContentTitle(title);
1033 builder.setContentText(body);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001034 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001035 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001036
1037 final Intent intent = buildAllowBackgroundDataIntent();
1038 builder.setContentIntent(
1039 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001040
1041 // TODO: move to NotificationManager once we can mock it
1042 try {
1043 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001044 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001045 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001046 0x0, builder.getNotification(), idReceived, UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001047 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001048 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001049 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001050 }
1051 }
1052
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001053 private void cancelNotification(String tag) {
1054 // TODO: move to NotificationManager once we can mock it
1055 try {
1056 final String packageName = mContext.getPackageName();
1057 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001058 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001059 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001060 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001061 }
1062 }
1063
1064 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001065 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001066 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001067 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001068 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001069 @Override
1070 public void onReceive(Context context, Intent intent) {
1071 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1072 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001073
1074 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001075 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001076 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001077 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001078 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001079 updateNetworkRulesLocked();
1080 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001081 }
1082 }
1083 };
1084
1085 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001086 * Proactively control network data connections when they exceed
1087 * {@link NetworkPolicy#limitBytes}.
1088 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001089 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001090 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1091
1092 // TODO: reset any policy-disabled networks when any policy is removed
1093 // completely, which is currently rare case.
1094
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001095 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001096 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1097 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001098 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001099 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001100 setNetworkTemplateEnabled(policy.template, true);
1101 continue;
1102 }
1103
1104 final long start = computeLastCycleBoundary(currentTime, policy);
1105 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001106 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001107
1108 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001109 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1110 && policy.lastLimitSnooze < start;
1111 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001112
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001113 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001114 }
1115 }
1116
1117 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001118 * Proactively disable networks that match the given
1119 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001120 */
1121 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001122 // TODO: reach into ConnectivityManager to proactively disable bringing
1123 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001124 }
1125
1126 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001127 * Examine all connected {@link NetworkState}, looking for
1128 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1129 * remaining quota based on usage cycle and historical stats.
1130 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001131 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001132 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001133
1134 final NetworkState[] states;
1135 try {
1136 states = mConnManager.getAllNetworkState();
1137 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001138 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001139 return;
1140 }
1141
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001142 // If we are in restrict power mode, we want to treat all interfaces
1143 // as metered, to restrict access to the network by uid. However, we
1144 // will not have a bandwidth limit. Also only do this if restrict
Felipe Lemeb85a6372016-01-14 16:16:16 -08001145 // background data use is *not* enabled, since that takes precedence
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001146 // use over those networks can have a cost associated with it).
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001147 final boolean powerSave = mRestrictPower && !mRestrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001148
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001149 // First, generate identities of all connected networks so we can
1150 // quickly compare them against all defined policies below.
1151 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001152 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001153 for (NetworkState state : states) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001154 if (state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001155 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001156
1157 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001158 if (baseIface != null) {
1159 connIdents.add(Pair.create(baseIface, ident));
1160 if (powerSave) {
1161 connIfaces.add(baseIface);
1162 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001163 }
1164
1165 // Stacked interfaces are considered to have same identity as
1166 // their parent network.
1167 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1168 for (LinkProperties stackedLink : stackedLinks) {
1169 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001170 if (stackedIface != null) {
1171 connIdents.add(Pair.create(stackedIface, ident));
1172 if (powerSave) {
1173 connIfaces.add(stackedIface);
1174 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001175 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001176 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001177 }
1178 }
1179
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001180 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001181 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001182 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001183 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001184 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001185
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001186 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001187 for (int j = connIdents.size() - 1; j >= 0; j--) {
1188 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1189 if (policy.template.matches(ident.second)) {
1190 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001191 }
1192 }
1193
1194 if (ifaceList.size() > 0) {
1195 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001196 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001197 }
1198 }
1199
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001200 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001201 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001202
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001203 // apply each policy that we found ifaces for; compute remaining data
1204 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001205 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001206 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1207 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1208 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001209
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001210 final long start;
1211 final long totalBytes;
1212 if (policy.hasCycle()) {
1213 start = computeLastCycleBoundary(currentTime, policy);
1214 totalBytes = getTotalBytes(policy.template, start, currentTime);
1215 } else {
1216 start = Long.MAX_VALUE;
1217 totalBytes = 0;
1218 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001219
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001220 if (LOGD) {
1221 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001222 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001223 }
1224
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001225 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001226 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001227 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001228 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001229 if (!hasLimit) {
1230 // metered network, but no policy limit; we still need to
1231 // restrict apps, so push really high quota.
1232 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001233 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001234 // snoozing past quota, but we still need to restrict apps,
1235 // so push really high quota.
1236 quotaBytes = Long.MAX_VALUE;
1237 } else {
1238 // remaining "quota" bytes are based on total usage in
1239 // current cycle. kernel doesn't like 0-byte rules, so we
1240 // set 1-byte quota and disable the radio later.
1241 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1242 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001243
1244 if (ifaces.length > 1) {
1245 // TODO: switch to shared quota once NMS supports
1246 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001247 }
1248
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001249 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001250 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001251 setInterfaceQuota(iface, quotaBytes);
1252 newMeteredIfaces.add(iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001253 if (powerSave) {
1254 connIfaces.remove(iface);
1255 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001256 }
1257 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001258
1259 // keep track of lowest warning or limit of active policies
1260 if (hasWarning && policy.warningBytes < lowestRule) {
1261 lowestRule = policy.warningBytes;
1262 }
1263 if (hasLimit && policy.limitBytes < lowestRule) {
1264 lowestRule = policy.limitBytes;
1265 }
1266 }
1267
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001268 for (int i = connIfaces.size()-1; i >= 0; i--) {
1269 String iface = connIfaces.valueAt(i);
1270 removeInterfaceQuota(iface);
1271 setInterfaceQuota(iface, Long.MAX_VALUE);
1272 newMeteredIfaces.add(iface);
1273 }
1274
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001275 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001276
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001277 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001278 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1279 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001280 if (!newMeteredIfaces.contains(iface)) {
1281 removeInterfaceQuota(iface);
1282 }
1283 }
1284 mMeteredIfaces = newMeteredIfaces;
1285
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001286 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001287 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001288 }
1289
1290 /**
1291 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1292 * have at least a default mobile policy defined.
1293 */
1294 private void ensureActiveMobilePolicyLocked() {
1295 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001296 if (mSuppressDefaultPolicy) return;
1297
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001298 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001299 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001300
Jeff Sharkey32566012014-12-02 18:30:14 -08001301 final int[] subIds = sub.getActiveSubscriptionIdList();
1302 for (int subId : subIds) {
1303 final String subscriberId = tele.getSubscriberId(subId);
1304 ensureActiveMobilePolicyLocked(subscriberId);
1305 }
1306 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001307
Jeff Sharkey32566012014-12-02 18:30:14 -08001308 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1309 // Poke around to see if we already have a policy
1310 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1311 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1312 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1313 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1314 if (template.matches(probeIdent)) {
1315 if (LOGD) {
1316 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1317 + NetworkIdentity.scrubSubscriberId(subscriberId));
1318 }
1319 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001320 }
1321 }
1322
Jeff Sharkey32566012014-12-02 18:30:14 -08001323 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1324 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001325
Jeff Sharkey32566012014-12-02 18:30:14 -08001326 // Build default mobile policy, and assume usage cycle starts today
1327 final long warningBytes = mContext.getResources().getInteger(
1328 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001329
Jeff Sharkey32566012014-12-02 18:30:14 -08001330 final Time time = new Time();
1331 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001332
Jeff Sharkey32566012014-12-02 18:30:14 -08001333 final int cycleDay = time.monthDay;
1334 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001335
Jeff Sharkey32566012014-12-02 18:30:14 -08001336 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1337 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1338 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1339 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001340 }
1341
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001342 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001343 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001344
1345 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001346 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001347 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001348
1349 FileInputStream fis = null;
1350 try {
1351 fis = mPolicyFile.openRead();
1352 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001353 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001354
1355 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001356 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001357 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001358 while ((type = in.next()) != END_DOCUMENT) {
1359 final String tag = in.getName();
1360 if (type == START_TAG) {
1361 if (TAG_POLICY_LIST.equals(tag)) {
1362 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001363 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1364 mRestrictBackground = readBooleanAttribute(
1365 in, ATTR_RESTRICT_BACKGROUND);
1366 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001367 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001368 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001369
1370 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1371 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1372 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001373 final String networkId;
1374 if (version >= VERSION_ADDED_NETWORK_ID) {
1375 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1376 } else {
1377 networkId = null;
1378 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001379 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001380 final String cycleTimezone;
1381 if (version >= VERSION_ADDED_TIMEZONE) {
1382 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1383 } else {
1384 cycleTimezone = Time.TIMEZONE_UTC;
1385 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001386 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1387 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001388 final long lastLimitSnooze;
1389 if (version >= VERSION_SPLIT_SNOOZE) {
1390 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1391 } else if (version >= VERSION_ADDED_SNOOZE) {
1392 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001393 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001394 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001395 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001396 final boolean metered;
1397 if (version >= VERSION_ADDED_METERED) {
1398 metered = readBooleanAttribute(in, ATTR_METERED);
1399 } else {
1400 switch (networkTemplate) {
1401 case MATCH_MOBILE_3G_LOWER:
1402 case MATCH_MOBILE_4G:
1403 case MATCH_MOBILE_ALL:
1404 metered = true;
1405 break;
1406 default:
1407 metered = false;
1408 }
1409 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001410 final long lastWarningSnooze;
1411 if (version >= VERSION_SPLIT_SNOOZE) {
1412 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1413 } else {
1414 lastWarningSnooze = SNOOZE_NEVER;
1415 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001416 final boolean inferred;
1417 if (version >= VERSION_ADDED_INFERRED) {
1418 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1419 } else {
1420 inferred = false;
1421 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001422
Jeff Sharkey32566012014-12-02 18:30:14 -08001423 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1424 subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001425 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001426 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001427 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001428
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001429 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001430 final int uid = readIntAttribute(in, ATTR_UID);
1431 final int policy = readIntAttribute(in, ATTR_POLICY);
1432
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001433 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001434 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001435 } else {
1436 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1437 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001438 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001439 final int appId = readIntAttribute(in, ATTR_APP_ID);
1440 final int policy = readIntAttribute(in, ATTR_POLICY);
1441
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001442 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001443 // app policy is deprecated so this is only used in pre system user split.
1444 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001445 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001446 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001447 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001448 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001449 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001450 } else if (TAG_WHITELIST.equals(tag)) {
1451 insideWhitelist = true;
1452 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1453 final int uid = readIntAttribute(in, ATTR_UID);
1454 mRestrictBackgroundWhitelistUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001455 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001456 } else if (type == END_TAG) {
1457 if (TAG_WHITELIST.equals(tag)) {
1458 insideWhitelist = false;
1459 }
1460
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001461 }
1462 }
1463
1464 } catch (FileNotFoundException e) {
1465 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001466 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001467 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001468 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001469 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001470 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001471 } finally {
1472 IoUtils.closeQuietly(fis);
1473 }
1474 }
1475
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001476 /**
1477 * Upgrade legacy background data flags, notifying listeners of one last
1478 * change to always-true.
1479 */
1480 private void upgradeLegacyBackgroundData() {
1481 mRestrictBackground = Settings.Secure.getInt(
1482 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1483
1484 // kick off one last broadcast if restricted
1485 if (mRestrictBackground) {
1486 final Intent broadcast = new Intent(
1487 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001488 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001489 }
1490 }
1491
Dianne Hackborn497175b2014-07-01 12:56:08 -07001492 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001493 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001494
1495 FileOutputStream fos = null;
1496 try {
1497 fos = mPolicyFile.startWrite();
1498
1499 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001500 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001501 out.startDocument(null, true);
1502
1503 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001504 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001505 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001506
1507 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001508 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1509 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001510 final NetworkTemplate template = policy.template;
1511
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001512 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001513 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1514 final String subscriberId = template.getSubscriberId();
1515 if (subscriberId != null) {
1516 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001517 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001518 final String networkId = template.getNetworkId();
1519 if (networkId != null) {
1520 out.attribute(null, ATTR_NETWORK_ID, networkId);
1521 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001522 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001523 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001524 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1525 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001526 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1527 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001528 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001529 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001530 out.endTag(null, TAG_NETWORK_POLICY);
1531 }
1532
1533 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001534 for (int i = 0; i < mUidPolicy.size(); i++) {
1535 final int uid = mUidPolicy.keyAt(i);
1536 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001537
Jeff Sharkey497e4432011-06-14 17:27:29 -07001538 // skip writing empty policies
1539 if (policy == POLICY_NONE) continue;
1540
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001541 out.startTag(null, TAG_UID_POLICY);
1542 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001543 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001544 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001545 }
1546
1547 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001548
1549 // write all whitelists
1550 out.startTag(null, TAG_WHITELIST);
1551
1552 // restrict background whitelist
1553 final int size = mRestrictBackgroundWhitelistUids.size();
1554 for (int i = 0; i < size; i++) {
1555 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1556 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1557 writeIntAttribute(out, ATTR_UID, uid);
1558 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1559 }
1560
1561 out.endTag(null, TAG_WHITELIST);
1562
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001563 out.endDocument();
1564
1565 mPolicyFile.finishWrite(fos);
1566 } catch (IOException e) {
1567 if (fos != null) {
1568 mPolicyFile.failWrite(fos);
1569 }
1570 }
1571 }
1572
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001573 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001574 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001575 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001576
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001577 if (!UserHandle.isApp(uid)) {
1578 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001579 }
1580
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001581 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001582 final long token = Binder.clearCallingIdentity();
1583 try {
1584 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1585 if (oldPolicy != policy) {
1586 setUidPolicyUncheckedLocked(uid, policy, true);
1587 }
1588 } finally {
1589 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001590 }
1591 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001592 }
1593
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001594 @Override
1595 public void addUidPolicy(int uid, int policy) {
1596 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001597
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001598 if (!UserHandle.isApp(uid)) {
1599 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1600 }
1601
1602 synchronized (mRulesLock) {
1603 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1604 policy |= oldPolicy;
1605 if (oldPolicy != policy) {
1606 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001607 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001608 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001609 }
1610
1611 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001612 public void removeUidPolicy(int uid, int policy) {
1613 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1614
1615 if (!UserHandle.isApp(uid)) {
1616 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1617 }
1618
1619 synchronized (mRulesLock) {
1620 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1621 policy = oldPolicy & ~policy;
1622 if (oldPolicy != policy) {
1623 setUidPolicyUncheckedLocked(uid, policy, true);
1624 }
1625 }
1626 }
1627
1628 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1629 mUidPolicy.put(uid, policy);
1630
1631 // uid policy changed, recompute rules and persist policy.
1632 updateRulesForUidLocked(uid);
1633 if (persist) {
1634 writePolicyLocked();
1635 }
1636 }
1637
1638 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001639 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001640 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1641
Jeff Sharkeya4620792011-05-20 15:29:23 -07001642 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001643 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001644 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001645 }
1646
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001647 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001648 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001649 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1650
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001651 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001652 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001653 for (int i = 0; i < mUidPolicy.size(); i++) {
1654 final int uid = mUidPolicy.keyAt(i);
1655 final int uidPolicy = mUidPolicy.valueAt(i);
1656 if (uidPolicy == policy) {
1657 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001658 }
1659 }
1660 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001661 return uids;
1662 }
1663
1664 /**
1665 * Remove any policies associated with given {@link UserHandle}, persisting
1666 * if any changes are made.
1667 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001668 void removePoliciesForUserLocked(int userId) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001669 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1670
1671 int[] uids = new int[0];
1672 for (int i = 0; i < mUidPolicy.size(); i++) {
1673 final int uid = mUidPolicy.keyAt(i);
1674 if (UserHandle.getUserId(uid) == userId) {
1675 uids = appendInt(uids, uid);
1676 }
1677 }
1678
1679 if (uids.length > 0) {
1680 for (int uid : uids) {
1681 mUidPolicy.delete(uid);
1682 updateRulesForUidLocked(uid);
1683 }
1684 writePolicyLocked();
1685 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001686 }
1687
1688 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001689 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001690 // TODO: create permission for observing network policy
1691 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1692
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001693 mListeners.register(listener);
1694
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001695 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001696 }
1697
1698 @Override
1699 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001700 // TODO: create permission for observing network policy
1701 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1702
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001703 mListeners.unregister(listener);
1704 }
1705
Jeff Sharkey1b861272011-05-22 00:34:52 -07001706 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001707 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001708 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1709
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001710 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001711 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001712 normalizePoliciesLocked(policies);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001713 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001714 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001715 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001716 writePolicyLocked();
1717 }
1718 }
1719
Dianne Hackborn497175b2014-07-01 12:56:08 -07001720 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001721 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001722 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1723 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001724 }
1725
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001726 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001727 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001728 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001729 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001730 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1731 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1732 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001733 } catch (SecurityException e) {
1734 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001735
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001736 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1737 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1738 return new NetworkPolicy[0];
1739 }
Svet Ganov16a16892015-04-16 10:32:04 -07001740 }
1741
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001742 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001743 final int size = mNetworkPolicy.size();
1744 final NetworkPolicy[] policies = new NetworkPolicy[size];
1745 for (int i = 0; i < size; i++) {
1746 policies[i] = mNetworkPolicy.valueAt(i);
1747 }
1748 return policies;
1749 }
1750 }
1751
1752 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001753 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001754 }
1755
1756 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1757 final TelephonyManager tele = TelephonyManager.from(mContext);
1758 final String[] merged = tele.getMergedSubscriberIds();
1759
1760 mNetworkPolicy.clear();
1761 for (NetworkPolicy policy : policies) {
1762 // When two normalized templates conflict, prefer the most
1763 // restrictive policy
1764 policy.template = NetworkTemplate.normalize(policy.template, merged);
1765 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1766 if (existing == null || existing.compareTo(policy) > 0) {
1767 if (existing != null) {
1768 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1769 }
1770 mNetworkPolicy.put(policy.template, policy);
1771 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001772 }
1773 }
1774
1775 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001776 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001777 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001778
1779 final long token = Binder.clearCallingIdentity();
1780 try {
1781 performSnooze(template, TYPE_LIMIT);
1782 } finally {
1783 Binder.restoreCallingIdentity(token);
1784 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001785 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001786
Dianne Hackborn497175b2014-07-01 12:56:08 -07001787 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001788 maybeRefreshTrustedTime();
1789 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001790 synchronized (mRulesLock) {
1791 // find and snooze local policy that matches
1792 final NetworkPolicy policy = mNetworkPolicy.get(template);
1793 if (policy == null) {
1794 throw new IllegalArgumentException("unable to find policy for " + template);
1795 }
1796
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001797 switch (type) {
1798 case TYPE_WARNING:
1799 policy.lastWarningSnooze = currentTime;
1800 break;
1801 case TYPE_LIMIT:
1802 policy.lastLimitSnooze = currentTime;
1803 break;
1804 default:
1805 throw new IllegalArgumentException("unexpected type");
1806 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001807
Jeff Sharkey32566012014-12-02 18:30:14 -08001808 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001809 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001810 updateNetworkRulesLocked();
1811 updateNotificationsLocked();
1812 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001813 }
1814 }
1815
1816 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001817 public void setRestrictBackground(boolean restrictBackground) {
1818 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1819
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001820 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001821 synchronized (mRulesLock) {
1822 mRestrictBackground = restrictBackground;
Jeff Sharkey9d142062015-08-12 16:46:05 -07001823 updateRulesForGlobalChangeLocked(true);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001824 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001825 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001826 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001827
1828 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1829 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001830 }
1831
1832 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08001833 public void addRestrictBackgroundWhitelistedUid(int uid) {
1834 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1835 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
1836 synchronized (mRulesLock) {
1837 mRestrictBackgroundWhitelistUids.append(uid, true);
1838 writePolicyLocked();
1839 // TODO: call other update methods like updateNetworkRulesLocked?
1840 }
1841 }
1842
1843 @Override
1844 public void removeRestrictBackgroundWhitelistedUid(int uid) {
1845 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1846 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
1847 synchronized (mRulesLock) {
1848 removeRestrictBackgroundWhitelistedUidLocked(uid);
1849 }
1850 }
1851
1852 private void removeRestrictBackgroundWhitelistedUidLocked(int uid) {
1853 mRestrictBackgroundWhitelistUids.delete(uid);
1854 writePolicyLocked();
1855 // TODO: call other update methods like updateNetworkRulesLocked?
1856 }
1857
1858 @Override
1859 public int[] getRestrictBackgroundWhitelistedUids() {
1860 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1861 synchronized (mRulesLock) {
1862 final int size = mRestrictBackgroundWhitelistUids.size();
1863 final int[] whitelist = new int[size];
1864 for (int i = 0; i < size; i++) {
1865 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
1866 }
1867 if (LOGV) {
1868 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
1869 + mRestrictBackgroundWhitelistUids);
1870 }
1871 return whitelist;
1872 }
1873 }
1874
1875 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001876 public boolean getRestrictBackground() {
1877 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1878
1879 synchronized (mRulesLock) {
1880 return mRestrictBackground;
1881 }
1882 }
1883
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001884 @Override
1885 public void setDeviceIdleMode(boolean enabled) {
1886 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1887
1888 synchronized (mRulesLock) {
1889 if (mDeviceIdleMode != enabled) {
1890 mDeviceIdleMode = enabled;
1891 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07001892 // Device idle change means we need to rebuild rules for all
1893 // known apps, so do a global refresh.
1894 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001895 }
1896 if (enabled) {
1897 EventLogTags.writeDeviceIdleOnPhase("net");
1898 } else {
1899 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001900 }
1901 }
1902 }
1903 }
1904
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001905 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001906 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1907 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001908 if (policy.template.matches(ident)) {
1909 return policy;
1910 }
1911 }
1912 return null;
1913 }
1914
1915 @Override
1916 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1917 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1918
1919 // only returns usage summary, so we don't require caller to have
1920 // READ_NETWORK_USAGE_HISTORY.
1921 final long token = Binder.clearCallingIdentity();
1922 try {
1923 return getNetworkQuotaInfoUnchecked(state);
1924 } finally {
1925 Binder.restoreCallingIdentity(token);
1926 }
1927 }
1928
1929 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1930 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1931
1932 final NetworkPolicy policy;
1933 synchronized (mRulesLock) {
1934 policy = findPolicyForNetworkLocked(ident);
1935 }
1936
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001937 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001938 // missing policy means we can't derive useful quota info
1939 return null;
1940 }
1941
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001942 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001943
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001944 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001945 final long start = computeLastCycleBoundary(currentTime, policy);
1946 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001947 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001948
1949 // report soft and hard limits under policy
1950 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1951 : NetworkQuotaInfo.NO_LIMIT;
1952 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1953 : NetworkQuotaInfo.NO_LIMIT;
1954
1955 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1956 }
1957
Jeff Sharkey46645002011-07-27 21:11:21 -07001958 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001959 public boolean isNetworkMetered(NetworkState state) {
1960 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1961
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001962 // roaming networks are always considered metered
1963 if (ident.getRoaming()) {
1964 return true;
1965 }
1966
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001967 final NetworkPolicy policy;
1968 synchronized (mRulesLock) {
1969 policy = findPolicyForNetworkLocked(ident);
1970 }
1971
1972 if (policy != null) {
1973 return policy.metered;
1974 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001975 final int type = state.networkInfo.getType();
1976 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1977 return true;
1978 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001979 return false;
1980 }
1981 }
1982
1983 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001984 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001985 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001986
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001987 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1988
Dianne Hackborn497175b2014-07-01 12:56:08 -07001989 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001990 for (String arg : args) {
1991 argSet.add(arg);
1992 }
1993
Jeff Sharkey1b861272011-05-22 00:34:52 -07001994 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001995 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001996 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1997 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001998 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001999
Jeff Sharkey32566012014-12-02 18:30:14 -08002000 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002001 updateNetworkEnabledLocked();
2002 updateNetworkRulesLocked();
2003 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002004 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002005
2006 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002007 return;
2008 }
2009
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002010 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07002011 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002012 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002013 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002014 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002015 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002016 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2017 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002018 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002019 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002020
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07002021 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2022
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002023 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002024 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002025 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002026 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002027 final int uid = mUidPolicy.keyAt(i);
2028 final int policy = mUidPolicy.valueAt(i);
2029 fout.print("UID=");
2030 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002031 fout.print(" policy=");
Jeff Sharkeydc988062015-09-14 10:09:47 -07002032 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002033 fout.println();
2034 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002035 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002036
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002037 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2038 if (size > 0) {
2039 fout.println("Power save whitelist (except idle) app ids:");
2040 fout.increaseIndent();
2041 for (int i = 0; i < size; i++) {
2042 fout.print("UID=");
2043 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2044 fout.print(": ");
2045 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2046 fout.println();
2047 }
2048 fout.decreaseIndent();
2049 }
2050
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002051 size = mPowerSaveWhitelistAppIds.size();
2052 if (size > 0) {
2053 fout.println("Power save whitelist app ids:");
2054 fout.increaseIndent();
2055 for (int i = 0; i < size; i++) {
2056 fout.print("UID=");
2057 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2058 fout.print(": ");
2059 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2060 fout.println();
2061 }
2062 fout.decreaseIndent();
2063 }
2064
Felipe Lemeb85a6372016-01-14 16:16:16 -08002065 size = mRestrictBackgroundWhitelistUids.size();
2066 if (size > 0) {
2067 fout.println("Restrict background whitelist uids:");
2068 fout.increaseIndent();
2069 for (int i = 0; i < size; i++) {
2070 fout.print("UID=");
2071 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2072 fout.println();
2073 }
2074 fout.decreaseIndent();
2075 }
2076
Jeff Sharkey1b861272011-05-22 00:34:52 -07002077 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07002078 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002079 collectKeys(mUidRules, knownUids);
2080
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002081 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002082 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002083 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002084 for (int i = 0; i < size; i++) {
2085 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002086 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07002087 fout.print(uid);
2088
Jeff Sharkeydc988062015-09-14 10:09:47 -07002089 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002090 fout.print(" state=");
2091 fout.print(state);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002092 fout.print(state <= ActivityManager.PROCESS_STATE_TOP ? " (fg)" : " (bg)");
Dianne Hackborn497175b2014-07-01 12:56:08 -07002093
Jeff Sharkeydc988062015-09-14 10:09:47 -07002094 final int rule = mUidRules.get(uid, RULE_UNKNOWN);
2095 fout.print(" rule=");
2096 fout.print(DebugUtils.valueToString(NetworkPolicyManager.class, "RULE_", rule));
Jeff Sharkey1b861272011-05-22 00:34:52 -07002097
2098 fout.println();
2099 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002100 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002101 }
2102 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002103
2104 @Override
2105 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002106 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2107
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002108 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002109 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002110 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002111 }
2112
Dianne Hackborn497175b2014-07-01 12:56:08 -07002113 boolean isUidForegroundLocked(int uid) {
2114 // only really in foreground when screen is also on
2115 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002116 <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002117 }
2118
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002119 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002120 * Process state of UID changed; if needed, will trigger
2121 * {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002122 */
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002123 void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002124 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2125 if (oldUidState != uidState) {
2126 // state changed, push updated rules
2127 mUidState.put(uid, uidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002128 updateRulesForUidStateChangeLocked(uid, oldUidState, uidState);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002129 if (mDeviceIdleMode && isProcStateAllowedWhileIdle(oldUidState)
2130 != isProcStateAllowedWhileIdle(uidState)) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002131 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002132 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002133 }
2134 }
2135
2136 void removeUidStateLocked(int uid) {
2137 final int index = mUidState.indexOfKey(uid);
2138 if (index >= 0) {
2139 final int oldUidState = mUidState.valueAt(index);
2140 mUidState.removeAt(index);
2141 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
2142 updateRulesForUidStateChangeLocked(uid, oldUidState,
2143 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002144 if (mDeviceIdleMode) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002145 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002146 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002147 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002148 }
2149 }
2150
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002151 void updateRulesForUidStateChangeLocked(int uid, int oldUidState, int newUidState) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002152 final boolean oldForeground = oldUidState <= ActivityManager.PROCESS_STATE_TOP;
2153 final boolean newForeground = newUidState <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002154 if (oldForeground != newForeground) {
2155 updateRulesForUidLocked(uid);
2156 }
2157 }
2158
Jeff Sharkeya4620792011-05-20 15:29:23 -07002159 private void updateScreenOn() {
2160 synchronized (mRulesLock) {
2161 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002162 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002163 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002164 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002165 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002166 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002167 }
2168 }
2169
2170 /**
2171 * Update rules that might be changed by {@link #mScreenOn} value.
2172 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002173 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002174 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002175 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002176 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002177 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002178 final int uid = mUidState.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002179 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002180 }
2181 }
2182 }
2183
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002184 static boolean isProcStateAllowedWhileIdle(int procState) {
2185 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2186 }
2187
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002188 void updateRulesForDeviceIdleLocked() {
2189 if (mDeviceIdleMode) {
2190 // sync the whitelists before enable dozable chain. We don't care about the rules if
2191 // we are disabling the chain.
Jeff Sharkeydc988062015-09-14 10:09:47 -07002192 final SparseIntArray uidRules = mUidFirewallDozableRules;
2193 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002194 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002195 for (int ui = users.size() - 1; ui >= 0; ui--) {
2196 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002197 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002198 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2199 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2200 int uid = UserHandle.getUid(user.id, appId);
2201 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2202 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002203 }
2204 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2205 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2206 int uid = UserHandle.getUid(user.id, appId);
2207 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2208 }
2209 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002210 for (int i = mUidState.size() - 1; i >= 0; i--) {
2211 if (isProcStateAllowedWhileIdle(mUidState.valueAt(i))) {
2212 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2213 }
2214 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002215 setUidFirewallRules(FIREWALL_CHAIN_DOZABLE, uidRules);
2216 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002217
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002218 enableFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, mDeviceIdleMode);
2219 }
2220
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002221 void updateRuleForDeviceIdleLocked(int uid) {
2222 if (mDeviceIdleMode) {
2223 int appId = UserHandle.getAppId(uid);
2224 if (mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId)
2225 || isProcStateAllowedWhileIdle(mUidState.get(uid))) {
2226 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_ALLOW);
2227 } else {
2228 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
2229 }
2230 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002231
2232 updateRulesForUidLocked(uid);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002233 }
2234
2235 void updateRulesForAppIdleLocked() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002236 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2237 uidRules.clear();
2238
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002239 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002240 final List<UserInfo> users = mUserManager.getUsers();
2241 for (int ui = users.size() - 1; ui >= 0; ui--) {
2242 UserInfo user = users.get(ui);
2243 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2244 for (int uid : idleUids) {
2245 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2246 uidRules.put(uid, FIREWALL_RULE_DENY);
2247 }
2248 }
2249 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002250
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002251 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2252 }
2253
2254 void updateRuleForAppIdleLocked(int uid) {
2255 if (!isUidValidForRules(uid)) return;
2256
2257 int appId = UserHandle.getAppId(uid);
2258 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)) {
2259 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2260 } else {
2261 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2262 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002263
2264 updateRulesForUidLocked(uid);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002265 }
2266
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002267 void updateRulesForAppIdleParoleLocked() {
2268 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2269 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Jeff Sharkeydc988062015-09-14 10:09:47 -07002270 updateRulesForUidsLocked(mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002271 }
2272
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002273 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002274 * Update rules that might be changed by {@link #mRestrictBackground},
2275 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002276 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002277 void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002278 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002279
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002280 updateRulesForDeviceIdleLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002281 updateRulesForAppIdleLocked();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002282
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002283 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002284 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002285 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey2a9e3f82015-12-18 10:57:58 -07002286 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS
2287 | PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002288
2289 for (UserInfo user : users) {
2290 for (ApplicationInfo app : apps) {
2291 final int uid = UserHandle.getUid(user.id, app.uid);
2292 updateRulesForUidLocked(uid);
2293 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002294 }
2295
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002296 // limit data usage for some internal system services
2297 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
2298 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002299
2300 // If the set of restricted networks may have changed, re-evaluate those.
2301 if (restrictedNetworksChanged) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002302 normalizePoliciesLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002303 updateNetworkRulesLocked();
2304 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002305 }
2306
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002307 void updateRulesForTempWhitelistChangeLocked() {
2308 final List<UserInfo> users = mUserManager.getUsers();
2309 for (UserInfo user : users) {
2310 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
2311 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2312 int uid = UserHandle.getUid(user.id, appId);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002313 updateRuleForAppIdleLocked(uid);
2314 updateRuleForDeviceIdleLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002315 }
2316 }
2317 }
2318
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002319 private static boolean isUidValidForRules(int uid) {
2320 // allow rules on specific system services, and any apps
2321 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002322 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002323 return true;
2324 }
2325
2326 return false;
2327 }
2328
Amith Yamasani15e472352015-04-24 19:06:07 -07002329 private boolean isUidIdle(int uid) {
2330 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2331 final int userId = UserHandle.getUserId(uid);
2332
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002333 if (!ArrayUtils.isEmpty(packages)) {
2334 for (String packageName : packages) {
2335 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2336 return false;
2337 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002338 }
2339 }
2340 return true;
2341 }
2342
Jeff Sharkeydc988062015-09-14 10:09:47 -07002343 void updateRulesForUidsLocked(SparseIntArray uids) {
2344 for (int i = 0; i < uids.size(); i++) {
2345 updateRulesForUidLocked(uids.keyAt(i));
2346 }
2347 }
2348
Amith Yamasani15e472352015-04-24 19:06:07 -07002349 /**
2350 * Applies network rules to bandwidth and firewall controllers based on uid policy.
2351 * @param uid The uid for which to apply the latest policy
2352 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002353 void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002354 if (!isUidValidForRules(uid)) return;
2355
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002356 // quick check: if this uid doesn't have INTERNET permission, it doesn't have
2357 // network access anyway, so it is a waste to mess with it here.
2358 final IPackageManager ipm = AppGlobals.getPackageManager();
2359 try {
2360 if (ipm.checkUidPermission(Manifest.permission.INTERNET, uid)
2361 != PackageManager.PERMISSION_GRANTED) {
2362 return;
2363 }
2364 } catch (RemoteException e) {
2365 }
2366
Dianne Hackborn497175b2014-07-01 12:56:08 -07002367 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2368 final boolean uidForeground = isUidForegroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002369
Jeff Sharkeydc988062015-09-14 10:09:47 -07002370 // Derive active rules based on policy and active state
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002371 int appId = UserHandle.getAppId(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002372 int uidRules = RULE_ALLOW_ALL;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002373 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002374 // uid in background, and policy says to block metered data
2375 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002376 } else if (mRestrictBackground) {
2377 if (!uidForeground) {
Felipe Lemeb85a6372016-01-14 16:16:16 -08002378 // uid in background, global background disabled, and this uid is not on the white
2379 // list of those allowed background access while global background is disabled
2380 if (!mRestrictBackgroundWhitelistUids.get(uid)) {
2381 uidRules = RULE_REJECT_METERED;
2382 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002383 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002384 } else if (mRestrictPower) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002385 final boolean whitelisted = mPowerSaveWhitelistExceptIdleAppIds.get(appId)
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002386 || mPowerSaveTempWhitelistAppIds.get(appId);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002387 if (!whitelisted && !uidForeground
2388 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
2389 // uid is in background, restrict power use mode is on (so we want to
2390 // restrict all background network access), and this uid is not on the
2391 // white list of those allowed background access.
2392 uidRules = RULE_REJECT_METERED;
2393 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002394 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002395
Jeff Sharkeydc988062015-09-14 10:09:47 -07002396 // Check dozable state, which is whitelist
2397 if (mFirewallChainStates.get(FIREWALL_CHAIN_DOZABLE)
2398 && mUidFirewallDozableRules.get(uid, FIREWALL_RULE_DEFAULT) != FIREWALL_RULE_ALLOW) {
2399 uidRules = RULE_REJECT_ALL;
2400 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002401
Jeff Sharkeydc988062015-09-14 10:09:47 -07002402 // Check standby state, which is blacklist
2403 if (mFirewallChainStates.get(FIREWALL_CHAIN_STANDBY)
2404 && mUidFirewallStandbyRules.get(uid, FIREWALL_RULE_DEFAULT) == FIREWALL_RULE_DENY) {
2405 uidRules = RULE_REJECT_ALL;
2406 }
2407
2408 final int oldRules = mUidRules.get(uid);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002409 if (uidRules == RULE_ALLOW_ALL) {
2410 mUidRules.delete(uid);
2411 } else {
2412 mUidRules.put(uid, uidRules);
2413 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002414
Jeff Sharkeydc988062015-09-14 10:09:47 -07002415 final boolean rejectMetered = (uidRules == RULE_REJECT_METERED);
2416 setUidNetworkRules(uid, rejectMetered);
Amith Yamasani15e472352015-04-24 19:06:07 -07002417
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002418 // dispatch changed rule to existing listeners
Amith Yamasani15e472352015-04-24 19:06:07 -07002419 if (oldRules != uidRules) {
2420 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
2421 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002422
2423 try {
2424 // adjust stats accounting based on foreground status
2425 mNetworkStats.setUidForeground(uid, uidForeground);
2426 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002427 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002428 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002429 }
2430
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002431 private class AppIdleStateChangeListener
2432 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2433
2434 @Override
2435 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2436 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002437 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
2438 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002439 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002440 updateRuleForAppIdleLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002441 }
2442 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002443 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002444 }
2445
2446 @Override
2447 public void onParoleStateChanged(boolean isParoleOn) {
2448 synchronized (mRulesLock) {
2449 updateRulesForAppIdleParoleLocked();
2450 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002451 }
2452 }
2453
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002454 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002455 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002456 public boolean handleMessage(Message msg) {
2457 switch (msg.what) {
2458 case MSG_RULES_CHANGED: {
2459 final int uid = msg.arg1;
2460 final int uidRules = msg.arg2;
2461 final int length = mListeners.beginBroadcast();
2462 for (int i = 0; i < length; i++) {
2463 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2464 if (listener != null) {
2465 try {
2466 listener.onUidRulesChanged(uid, uidRules);
2467 } catch (RemoteException e) {
2468 }
2469 }
2470 }
2471 mListeners.finishBroadcast();
2472 return true;
2473 }
2474 case MSG_METERED_IFACES_CHANGED: {
2475 final String[] meteredIfaces = (String[]) msg.obj;
2476 final int length = mListeners.beginBroadcast();
2477 for (int i = 0; i < length; i++) {
2478 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2479 if (listener != null) {
2480 try {
2481 listener.onMeteredIfacesChanged(meteredIfaces);
2482 } catch (RemoteException e) {
2483 }
2484 }
2485 }
2486 mListeners.finishBroadcast();
2487 return true;
2488 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002489 case MSG_LIMIT_REACHED: {
2490 final String iface = (String) msg.obj;
2491
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002492 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002493 synchronized (mRulesLock) {
2494 if (mMeteredIfaces.contains(iface)) {
2495 try {
2496 // force stats update to make sure we have
2497 // numbers that caused alert to trigger.
2498 mNetworkStats.forceUpdate();
2499 } catch (RemoteException e) {
2500 // ignored; service lives in system_server
2501 }
2502
2503 updateNetworkEnabledLocked();
2504 updateNotificationsLocked();
2505 }
2506 }
2507 return true;
2508 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002509 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2510 final boolean restrictBackground = msg.arg1 != 0;
2511 final int length = mListeners.beginBroadcast();
2512 for (int i = 0; i < length; i++) {
2513 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2514 if (listener != null) {
2515 try {
2516 listener.onRestrictBackgroundChanged(restrictBackground);
2517 } catch (RemoteException e) {
2518 }
2519 }
2520 }
2521 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002522 return true;
2523 }
2524 case MSG_ADVISE_PERSIST_THRESHOLD: {
2525 final long lowestRule = (Long) msg.obj;
2526 try {
2527 // make sure stats are recorded frequently enough; we aim
2528 // for 2MB threshold for 2GB/month rules.
2529 final long persistThreshold = lowestRule / 1000;
2530 mNetworkStats.advisePersistThreshold(persistThreshold);
2531 } catch (RemoteException e) {
2532 // ignored; service lives in system_server
2533 }
2534 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002535 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002536 case MSG_SCREEN_ON_CHANGED: {
2537 updateScreenOn();
2538 return true;
2539 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002540 default: {
2541 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002542 }
2543 }
2544 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002545 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002546
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002547 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002548 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002549 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002550 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002551 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002552 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002553 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002554 }
2555 }
2556
2557 private void removeInterfaceQuota(String iface) {
2558 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002559 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002560 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002561 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002562 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002563 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002564 }
2565 }
2566
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002567 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2568 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002569 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002570 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002571 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002572 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002573 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002574 }
2575 }
2576
Amith Yamasani15e472352015-04-24 19:06:07 -07002577 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002578 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
2579 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
2580 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07002581 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002582 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002583 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002584 int size = uidRules.size();
2585 int[] uids = new int[size];
2586 int[] rules = new int[size];
2587 for(int index = size - 1; index >= 0; --index) {
2588 uids[index] = uidRules.keyAt(index);
2589 rules[index] = uidRules.valueAt(index);
2590 }
2591 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002592 } catch (IllegalStateException e) {
2593 Log.wtf(TAG, "problem setting firewall uid rules", e);
2594 } catch (RemoteException e) {
2595 // ignored; service lives in system_server
2596 }
2597 }
2598
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002599 /**
2600 * Add or remove a uid to the firewall blacklist for all network ifaces.
2601 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002602 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002603 if (chain == FIREWALL_CHAIN_DOZABLE) {
2604 mUidFirewallDozableRules.put(uid, rule);
2605 } else if (chain == FIREWALL_CHAIN_STANDBY) {
2606 mUidFirewallStandbyRules.put(uid, rule);
2607 }
2608
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002609 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002610 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002611 } catch (IllegalStateException e) {
2612 Log.wtf(TAG, "problem setting firewall uid rules", e);
2613 } catch (RemoteException e) {
2614 // ignored; service lives in system_server
2615 }
2616 }
2617
2618 /**
2619 * Add or remove a uid to the firewall blacklist for all network ifaces.
2620 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002621 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002622 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
2623 mFirewallChainStates.get(chain) == enable) {
2624 // All is the same, nothing to do.
2625 return;
2626 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002627 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002628 try {
2629 mNetworkManager.setFirewallChainEnabled(chain, enable);
2630 } catch (IllegalStateException e) {
2631 Log.wtf(TAG, "problem enable firewall chain", e);
2632 } catch (RemoteException e) {
2633 // ignored; service lives in system_server
2634 }
2635 }
2636
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002637 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2638 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002639 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002640 } catch (RuntimeException e) {
2641 Slog.w(TAG, "problem reading network stats: " + e);
2642 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002643 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002644 // ignored; service lives in system_server
2645 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002646 }
2647 }
2648
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002649 private boolean isBandwidthControlEnabled() {
2650 final long token = Binder.clearCallingIdentity();
2651 try {
2652 return mNetworkManager.isBandwidthControlEnabled();
2653 } catch (RemoteException e) {
2654 // ignored; service lives in system_server
2655 return false;
2656 } finally {
2657 Binder.restoreCallingIdentity(token);
2658 }
2659 }
2660
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002661 /**
2662 * Try refreshing {@link #mTime} when stale.
2663 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002664 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002665 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002666 mTime.forceRefresh();
2667 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002668 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002669
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002670 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002671 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2672 }
2673
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002674 private static Intent buildAllowBackgroundDataIntent() {
2675 return new Intent(ACTION_ALLOW_BACKGROUND);
2676 }
2677
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002678 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2679 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2680 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2681 return intent;
2682 }
2683
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002684 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2685 final Intent intent = new Intent();
2686 intent.setComponent(new ComponentName(
2687 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2688 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2689 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2690 return intent;
2691 }
2692
2693 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2694 final Intent intent = new Intent();
2695 intent.setComponent(new ComponentName(
2696 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2697 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2698 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2699 return intent;
2700 }
2701
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002702 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002703 public void addIdleHandler(IdleHandler handler) {
2704 mHandler.getLooper().getQueue().addIdleHandler(handler);
2705 }
2706
Jeff Sharkey1b861272011-05-22 00:34:52 -07002707 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2708 final int size = source.size();
2709 for (int i = 0; i < size; i++) {
2710 target.put(source.keyAt(i), true);
2711 }
2712 }
2713
Stuart Scottf1fb3972015-04-02 18:00:02 -07002714 @Override
2715 public void factoryReset(String subscriber) {
2716 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2717
Stuart Scotte3e314d2015-04-20 14:07:45 -07002718 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
2719 return;
2720 }
2721
Stuart Scottf1fb3972015-04-02 18:00:02 -07002722 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07002723 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07002724 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
2725 for (NetworkPolicy policy : policies) {
2726 if (policy.template.equals(template)) {
2727 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2728 policy.inferred = false;
2729 policy.clearSnooze();
2730 }
2731 }
2732 setNetworkPolicies(policies);
2733
2734 // Turn restrict background data off
2735 setRestrictBackground(false);
2736
Stuart Scotte3e314d2015-04-20 14:07:45 -07002737 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
2738 // Remove app's "restrict background data" flag
2739 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
2740 setUidPolicy(uid, POLICY_NONE);
2741 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07002742 }
2743 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002744
2745 private class MyPackageMonitor extends PackageMonitor {
2746
2747 @Override
2748 public void onPackageRemoved(String packageName, int uid) {
2749 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
2750 synchronized (mRulesLock) {
2751 removeRestrictBackgroundWhitelistedUidLocked(uid);
2752 }
2753 }
2754
2755 @Override
2756 public void onPackageRemovedAllUsers(String packageName, int uid) {
2757 if (LOGV) Slog.v(TAG, "onPackageRemovedAllUsers: " + packageName + " ->" + uid);
2758 synchronized (mRulesLock) {
2759 removeRestrictBackgroundWhitelistedUidLocked(uid);
2760 }
2761 }
2762 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002763}