blob: 75b37c2ad8e76a3c8a499ccbedc4db2981efea71 [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;
78import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070079
Dianne Hackborn88e98df2015-03-23 13:29:14 -070080import android.Manifest;
Dianne Hackborn497175b2014-07-01 12:56:08 -070081import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070082import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070083import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070084import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070085import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070086import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070087import android.app.Notification;
88import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -070089import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -070090import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070091import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070092import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070093import android.content.Intent;
94import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070095import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070096import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070097import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -070098import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -070099import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700100import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700101import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700102import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700103import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700104import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700105import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700106import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700107import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700108import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700109import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700110import android.net.NetworkPolicy;
Zach Johnson143ebdb2015-08-10 16:34:04 -0700111import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700112import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700113import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700114import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700115import android.net.wifi.WifiConfiguration;
116import android.net.wifi.WifiInfo;
117import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700118import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700119import android.os.Environment;
120import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700121import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700122import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700123import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700124import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700125import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700126import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700127import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700128import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700129import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700130import android.os.RemoteException;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700131import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700132import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700133import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700134import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800135import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700136import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700137import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700138import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700139import android.util.ArrayMap;
140import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700141import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700142import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700143import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700144import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700145import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700146import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700147import android.util.SparseBooleanArray;
148import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700149import android.util.TrustedTime;
150import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700151
Jeff Sharkey32566012014-12-02 18:30:14 -0800152import libcore.io.IoUtils;
153
Jeff Sharkey497e4432011-06-14 17:27:29 -0700154import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800155import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey32566012014-12-02 18:30:14 -0800156import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700157import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700158import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700159import com.android.server.DeviceIdleController;
160import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700161import com.android.server.LocalServices;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700162import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700163
164import org.xmlpull.v1.XmlPullParser;
165import org.xmlpull.v1.XmlPullParserException;
166import org.xmlpull.v1.XmlSerializer;
167
168import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700169import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700170import java.io.FileInputStream;
171import java.io.FileNotFoundException;
172import java.io.FileOutputStream;
173import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700174import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100175import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700176import java.util.ArrayList;
177import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700178import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700179
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700180/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700181 * Service that maintains low-level network policy rules, using
182 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700183 * <p>
184 * Derives active rules by combining a given policy with other system status,
185 * and delivers to listeners, such as {@link ConnectivityManager}, for
186 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700187 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700188public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700189 private static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700190 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700191 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700192
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700193 private static final int VERSION_INIT = 1;
194 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700195 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800196 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800197 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800198 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700199 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700200 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700201 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700202 private static final int VERSION_SWITCH_UID = 10;
203 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700204
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800205 @VisibleForTesting
Zach Johnson143ebdb2015-08-10 16:34:04 -0700206 public static final int TYPE_NONE = 0;
207 @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";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700218
219 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700220 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700221 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
222 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700223 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700224 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800225 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700226 private static final String ATTR_WARNING_BYTES = "warningBytes";
227 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700228 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800229 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
230 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800231 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700232 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700233 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700234 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700235 private static final String ATTR_POLICY = "policy";
236
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700237 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
238
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800239 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800240 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800241 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800242 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700243
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700244 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
245
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700246 private static final int MSG_RULES_CHANGED = 1;
247 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800248 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800249 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700250 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700251 private static final int MSG_SCREEN_ON_CHANGED = 8;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700252
Jeff Sharkey75279902011-05-24 18:39:45 -0700253 private final Context mContext;
254 private final IActivityManager mActivityManager;
255 private final IPowerManager mPowerManager;
256 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700257 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700258 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700259 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700260 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700261
262 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700263 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700264 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700265 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700266
Zach Johnson143ebdb2015-08-10 16:34:04 -0700267 private final ComponentName mNotificationComponent;
268 private int mNotificationSequenceNumber;
269
Dianne Hackborn497175b2014-07-01 12:56:08 -0700270 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700271
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700272 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700273 volatile boolean mScreenOn;
274 volatile boolean mRestrictBackground;
275 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700276 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700277
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700278 private final boolean mSuppressDefaultPolicy;
279
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700280 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800281 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700282 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800283 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700284
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700285 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700286 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700287 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800288 final SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700289
290 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
291 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
292
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700293 /** Set of states for the child firewall chains. True if the chain is active. */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700294 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700295
Jeff Sharkey32566012014-12-02 18:30:14 -0800296 /**
297 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700298 * in power save mode, except device idle (doze) still applies.
299 * TODO: An int array might be sufficient
300 */
301 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
302
303 /**
304 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800305 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700306 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800307 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700308 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700309
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700310 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
311
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700312 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800313 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700314 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800315 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700316
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700317 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700318 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700319
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700320 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800321 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700322
Jeff Sharkey32566012014-12-02 18:30:14 -0800323 private final RemoteCallbackList<INetworkPolicyListener>
324 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700325
Dianne Hackborn497175b2014-07-01 12:56:08 -0700326 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700327
328 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700329
Svet Ganov16a16892015-04-16 10:32:04 -0700330 private final AppOpsManager mAppOps;
331
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700332 // TODO: keep whitelist of system-critical services that should never have
333 // rules enforced, such as system, phone, and radio UIDs.
334
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700335 // TODO: migrate notifications to SystemUI
336
Jeff Sharkey75279902011-05-24 18:39:45 -0700337 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700338 IPowerManager powerManager, INetworkStatsService networkStats,
339 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700340 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700341 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700342 }
343
344 private static File getSystemDir() {
345 return new File(Environment.getDataDirectory(), "system");
346 }
347
348 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700349 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700350 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
351 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700352 mContext = checkNotNull(context, "missing context");
353 mActivityManager = checkNotNull(activityManager, "missing activityManager");
354 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700355 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700356 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700357 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700358 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700359 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700360 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700361
Amith Yamasani450a16b2013-09-18 16:28:50 -0700362 HandlerThread thread = new HandlerThread(TAG);
363 thread.start();
364 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700365
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700366 mSuppressDefaultPolicy = suppressDefaultPolicy;
367
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700368 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700369
370 mAppOps = context.getSystemService(AppOpsManager.class);
Zach Johnson143ebdb2015-08-10 16:34:04 -0700371
372 final String notificationComponent = context.getString(
373 R.string.config_networkPolicyNotificationComponent);
374 mNotificationComponent = notificationComponent != null
375 ? ComponentName.unflattenFromString(notificationComponent) : null;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700376 }
377
378 public void bindConnectivityManager(IConnectivityManager connManager) {
379 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700380 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700381
Jeff Sharkey497e4432011-06-14 17:27:29 -0700382 public void bindNotificationManager(INotificationManager notifManager) {
383 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
384 }
385
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700386 void updatePowerSaveWhitelistLocked() {
387 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700388 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
389 mPowerSaveWhitelistExceptIdleAppIds.clear();
390 if (whitelist != null) {
391 for (int uid : whitelist) {
392 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
393 }
394 }
395 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700396 mPowerSaveWhitelistAppIds.clear();
397 if (whitelist != null) {
398 for (int uid : whitelist) {
399 mPowerSaveWhitelistAppIds.put(uid, true);
400 }
401 }
402 } catch (RemoteException e) {
403 }
404 }
405
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700406 void updatePowerSaveTempWhitelistLocked() {
407 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700408 // Clear the states of the current whitelist
409 final int N = mPowerSaveTempWhitelistAppIds.size();
410 for (int i = 0; i < N; i++) {
411 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
412 }
413 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700414 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700415 if (whitelist != null) {
416 for (int uid : whitelist) {
417 mPowerSaveTempWhitelistAppIds.put(uid, true);
418 }
419 }
420 } catch (RemoteException e) {
421 }
422 }
423
Amith Yamasani06f08062015-06-12 13:23:33 -0700424 /**
425 * Remove unnecessary entries in the temp whitelist
426 */
427 void purgePowerSaveTempWhitelistLocked() {
428 final int N = mPowerSaveTempWhitelistAppIds.size();
429 for (int i = N - 1; i >= 0; i--) {
430 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
431 mPowerSaveTempWhitelistAppIds.removeAt(i);
432 }
433 }
434 }
435
Jeff Sharkeya4620792011-05-20 15:29:23 -0700436 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700437 if (!isBandwidthControlEnabled()) {
438 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
439 return;
440 }
441
Amith Yamasani15e472352015-04-24 19:06:07 -0700442 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
443
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700444 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700445 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700446 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
447 mPowerManagerInternal.registerLowPowerModeObserver(
448 new PowerManagerInternal.LowPowerModeListener() {
449 @Override
450 public void onLowPowerModeChanged(boolean enabled) {
451 synchronized (mRulesLock) {
452 if (mRestrictPower != enabled) {
453 mRestrictPower = enabled;
454 updateRulesForGlobalChangeLocked(true);
455 }
456 }
457 }
458 });
459 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700460 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700461
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700462 // read policy from disk
463 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700464
Jeff Sharkeydc988062015-09-14 10:09:47 -0700465 updateRulesForGlobalChangeLocked(false);
466 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700467 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700468
Jeff Sharkeya4620792011-05-20 15:29:23 -0700469 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700470
Jeff Sharkeya4620792011-05-20 15:29:23 -0700471 try {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700472 mActivityManager.registerUidObserver(mUidObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700473 mNetworkManager.registerObserver(mAlertObserver);
474 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700475 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700476 }
477
Jeff Sharkeya4620792011-05-20 15:29:23 -0700478 // TODO: traverse existing processes to know foreground state, or have
479 // activitymanager dispatch current state when new observer attached.
480
481 final IntentFilter screenFilter = new IntentFilter();
482 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
483 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700484 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700485
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700486 // listen for changes to power save whitelist
487 final IntentFilter whitelistFilter = new IntentFilter(
488 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
489 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
490
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700491 DeviceIdleController.LocalService deviceIdleService
492 = LocalServices.getService(DeviceIdleController.LocalService.class);
493 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
494
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700495 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900496 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700497 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
498
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700499 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700500 final IntentFilter packageFilter = new IntentFilter();
501 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700502 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700503 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700504
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700505 // listen for UID changes to update policy
506 mContext.registerReceiver(
507 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
508
509 // listen for user changes to update policy
510 final IntentFilter userFilter = new IntentFilter();
511 userFilter.addAction(ACTION_USER_ADDED);
512 userFilter.addAction(ACTION_USER_REMOVED);
513 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
514
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700515 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700516 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
517 mContext.registerReceiver(
518 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
519
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700520 // listen for restrict background changes from notifications
521 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
522 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
523
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800524 // listen for snooze warning from notifications
525 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
526 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
527 MANAGE_NETWORK_POLICY, mHandler);
528
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700529 // listen for configured wifi networks to be removed
530 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700531 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700532
533 // listen for wifi state changes to catch metered hint
534 final IntentFilter wifiStateFilter = new IntentFilter(
535 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700536 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700537
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700538 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700539
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700540 }
541
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700542 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700543 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700544 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700545 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700546 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700547 }
548
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700549 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700550 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700551 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700552 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700553 }
554 };
555
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700556 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700557 @Override
558 public void onReceive(Context context, Intent intent) {
559 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
560 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700561 updatePowerSaveWhitelistLocked();
562 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700563 }
564 }
565 };
566
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700567 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
568 @Override
569 public void run() {
570 synchronized (mRulesLock) {
571 updatePowerSaveTempWhitelistLocked();
572 updateRulesForTempWhitelistChangeLocked();
573 purgePowerSaveTempWhitelistLocked();
574 }
575 }
576 };
577
578 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700579 @Override
580 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800581 // screen-related broadcasts are protected by system, no need
582 // for permissions check.
583 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700584 }
585 };
586
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700587 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700588 @Override
589 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700590 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700591
592 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700593 final int uid = intent.getIntExtra(EXTRA_UID, -1);
594 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700595
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700596 if (ACTION_PACKAGE_ADDED.equals(action)) {
597 // update rules for UID, since it might be subject to
598 // global background data policy
599 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
600 synchronized (mRulesLock) {
601 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700602 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700603 }
604 }
605 };
606
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700607 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700608 @Override
609 public void onReceive(Context context, Intent intent) {
610 // on background handler thread, and UID_REMOVED is protected
611
612 final int uid = intent.getIntExtra(EXTRA_UID, -1);
613 if (uid == -1) return;
614
615 // remove any policy and update rules to clean up
616 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
617 synchronized (mRulesLock) {
618 mUidPolicy.delete(uid);
619 updateRulesForUidLocked(uid);
620 writePolicyLocked();
621 }
622 }
623 };
624
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700625 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700626 @Override
627 public void onReceive(Context context, Intent intent) {
628 // on background handler thread, and USER_ADDED and USER_REMOVED
629 // broadcasts are protected
630
631 final String action = intent.getAction();
632 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
633 if (userId == -1) return;
634
Amith Yamasani15e472352015-04-24 19:06:07 -0700635 switch (action) {
636 case ACTION_USER_REMOVED:
637 case ACTION_USER_ADDED:
638 synchronized (mRulesLock) {
639 // Remove any policies for given user; both cleaning up after a
640 // USER_REMOVED, and one last sanity check during USER_ADDED
641 removePoliciesForUserLocked(userId);
642 // Update global restrict for new user
643 updateRulesForGlobalChangeLocked(true);
644 }
645 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700646 }
647 }
648 };
649
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700650 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700651 * Receiver that watches for {@link INetworkStatsService} updates, which we
652 * use to check against {@link NetworkPolicy#warningBytes}.
653 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700654 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700655 @Override
656 public void onReceive(Context context, Intent intent) {
657 // on background handler thread, and verified
658 // READ_NETWORK_USAGE_HISTORY permission above.
659
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800660 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700661 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700662 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700663 updateNotificationsLocked();
664 }
665 }
666 };
667
668 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700669 * Receiver that watches for {@link Notification} control of
670 * {@link #mRestrictBackground}.
671 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700672 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700673 @Override
674 public void onReceive(Context context, Intent intent) {
675 // on background handler thread, and verified MANAGE_NETWORK_POLICY
676 // permission above.
677
678 setRestrictBackground(false);
679 }
680 };
681
682 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800683 * Receiver that watches for {@link Notification} control of
684 * {@link NetworkPolicy#lastWarningSnooze}.
685 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700686 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800687 @Override
688 public void onReceive(Context context, Intent intent) {
689 // on background handler thread, and verified MANAGE_NETWORK_POLICY
690 // permission above.
691
692 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
693 performSnooze(template, TYPE_WARNING);
694 }
695 };
696
697 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700698 * Receiver that watches for {@link WifiConfiguration} to be changed.
699 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700700 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700701 @Override
702 public void onReceive(Context context, Intent intent) {
703 // on background handler thread, and verified CONNECTIVITY_INTERNAL
704 // permission above.
705
706 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
707 if (reason == CHANGE_REASON_REMOVED) {
708 final WifiConfiguration config = intent.getParcelableExtra(
709 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700710 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800711 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700712 synchronized (mRulesLock) {
713 if (mNetworkPolicy.containsKey(template)) {
714 mNetworkPolicy.remove(template);
715 writePolicyLocked();
716 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700717 }
718 }
719 }
720 }
721 };
722
723 /**
724 * Receiver that watches {@link WifiInfo} state changes to infer metered
725 * state. Ignores hints when policy is user-defined.
726 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700727 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700728 @Override
729 public void onReceive(Context context, Intent intent) {
730 // on background handler thread, and verified CONNECTIVITY_INTERNAL
731 // permission above.
732
733 // ignore when not connected
734 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
735 if (!netInfo.isConnected()) return;
736
737 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
738 final boolean meteredHint = info.getMeteredHint();
739
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800740 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700741 synchronized (mRulesLock) {
742 NetworkPolicy policy = mNetworkPolicy.get(template);
743 if (policy == null && meteredHint) {
744 // policy doesn't exist, and AP is hinting that it's
745 // metered: create an inferred policy.
746 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
747 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
748 meteredHint, true);
749 addNetworkPolicyLocked(policy);
750
751 } else if (policy != null && policy.inferred) {
752 // policy exists, and was inferred: update its current
753 // metered state.
754 policy.metered = meteredHint;
755
756 // since this is inferred for each wifi session, just update
757 // rules without persisting.
758 updateNetworkRulesLocked();
759 }
760 }
761 }
762 };
763
764 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700765 * Observer that watches for {@link INetworkManagementService} alerts.
766 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700767 final private INetworkManagementEventObserver mAlertObserver
768 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700769 @Override
770 public void limitReached(String limitName, String iface) {
771 // only someone like NMS should be calling us
772 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
773
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800774 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
775 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700776 }
777 }
778 };
779
780 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700781 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
782 * to show visible notifications as needed.
783 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700784 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700785 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
786
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700787 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700788 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700789 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700790
Zach Johnson143ebdb2015-08-10 16:34:04 -0700791 // increment the sequence number so custom components know
792 // this update is new
793 mNotificationSequenceNumber++;
794 boolean hasNotifications = false;
795
Jeff Sharkey497e4432011-06-14 17:27:29 -0700796 // TODO: when switching to kernel notifications, compute next future
797 // cycle boundary to recompute notifications.
798
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700799 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800800 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700801 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
802 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700803 // ignore policies that aren't relevant to user
804 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700805 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700806
Jeff Sharkey497e4432011-06-14 17:27:29 -0700807 final long start = computeLastCycleBoundary(currentTime, policy);
808 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700809 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700810
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700811 if (policy.isOverLimit(totalBytes)) {
Zach Johnson143ebdb2015-08-10 16:34:04 -0700812 hasNotifications = true;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800813 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700814 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
815 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700816 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
817 notifyOverLimitLocked(policy.template);
818 }
819
Jeff Sharkey497e4432011-06-14 17:27:29 -0700820 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700821 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700822
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800823 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700824 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Zach Johnson143ebdb2015-08-10 16:34:04 -0700825 hasNotifications = true;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700826 }
827 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700828 }
829
Zach Johnson143ebdb2015-08-10 16:34:04 -0700830 // right now we don't care about restricted background notifications
831 // in the custom notification component, so trigger an update now
832 // if we didn't update anything this pass
833 if (!hasNotifications) {
834 sendNotificationToCustomComponent(null, TYPE_NONE, 0);
835 }
836
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700837 // ongoing notification when restricting background data
838 if (mRestrictBackground) {
839 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700840 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700841
842 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700843 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
844 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700845 if (!mActiveNotifs.contains(tag)) {
846 cancelNotification(tag);
847 }
848 }
849 }
850
851 /**
852 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700853 * current device state, such as when
854 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
855 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700856 */
857 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800858 if (template.isMatchRuleMobile()) {
859 final TelephonyManager tele = TelephonyManager.from(mContext);
860 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700861
Jeff Sharkey32566012014-12-02 18:30:14 -0800862 // Mobile template is relevant when any active subscriber matches
863 final int[] subIds = sub.getActiveSubscriptionIdList();
864 for (int subId : subIds) {
865 final String subscriberId = tele.getSubscriberId(subId);
866 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
867 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
868 if (template.matches(probeIdent)) {
869 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700870 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800871 }
872 return false;
873 } else {
874 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700875 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700876 }
877
878 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700879 * Notify that given {@link NetworkTemplate} is over
880 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
881 */
882 private void notifyOverLimitLocked(NetworkTemplate template) {
Zach Johnson143ebdb2015-08-10 16:34:04 -0700883 if (mNotificationComponent != null) {
884 // It is the job of the notification component to handle UI,
885 // so we do nothing here
886 return;
887 }
888
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700889 if (!mOverLimitNotified.contains(template)) {
890 mContext.startActivity(buildNetworkOverLimitIntent(template));
891 mOverLimitNotified.add(template);
892 }
893 }
894
895 private void notifyUnderLimitLocked(NetworkTemplate template) {
896 mOverLimitNotified.remove(template);
897 }
898
899 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700900 * Build unique tag that identifies an active {@link NetworkPolicy}
901 * notification of a specific type, like {@link #TYPE_LIMIT}.
902 */
903 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700904 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700905 }
906
Zach Johnson143ebdb2015-08-10 16:34:04 -0700907 private boolean sendNotificationToCustomComponent(
908 NetworkPolicy policy,
909 int type,
910 long totalBytes) {
911 if (mNotificationComponent == null) {
912 return false;
913 }
914
915 Intent intent = new Intent();
916 intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND);
917 intent.setComponent(mNotificationComponent);
918
919 int notificationType = NetworkPolicyManager.NOTIFICATION_TYPE_NONE;
920 switch (type) {
921 case TYPE_WARNING:
922 notificationType = NetworkPolicyManager.NOTIFICATION_TYPE_USAGE_WARNING;
923 break;
924 case TYPE_LIMIT:
925 notificationType = NetworkPolicyManager.NOTIFICATION_TYPE_USAGE_REACHED_LIMIT;
926 break;
927 case TYPE_LIMIT_SNOOZED:
928 notificationType = NetworkPolicyManager.NOTIFICATION_TYPE_USAGE_EXCEEDED_LIMIT;
929 break;
930 }
931
932 intent.setAction(NetworkPolicyManager.ACTION_SHOW_NETWORK_POLICY_NOTIFICATION);
933 intent.putExtra(NetworkPolicyManager.EXTRA_NOTIFICATION_TYPE, notificationType);
934 intent.putExtra(
935 NetworkPolicyManager.EXTRA_NOTIFICATION_SEQUENCE_NUMBER,
936 mNotificationSequenceNumber);
937
938 if (notificationType != NetworkPolicyManager.NOTIFICATION_TYPE_NONE) {
939 intent.putExtra(NetworkPolicyManager.EXTRA_NETWORK_POLICY, policy);
940 intent.putExtra(NetworkPolicyManager.EXTRA_BYTES_USED, totalBytes);
941 }
942
943 mContext.sendBroadcast(intent);
944 return true;
945 }
946
Jeff Sharkey497e4432011-06-14 17:27:29 -0700947 /**
948 * Show notification for combined {@link NetworkPolicy} and specific type,
949 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
950 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700951 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Zach Johnson143ebdb2015-08-10 16:34:04 -0700952 if (sendNotificationToCustomComponent(policy, type, totalBytes)) {
953 return;
954 }
955
Jeff Sharkey497e4432011-06-14 17:27:29 -0700956 final String tag = buildNotificationTag(policy, type);
957 final Notification.Builder builder = new Notification.Builder(mContext);
958 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800959 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700960 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200961 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700962
963 final Resources res = mContext.getResources();
964 switch (type) {
965 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700966 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700967 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700968
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700969 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700970 builder.setTicker(title);
971 builder.setContentTitle(title);
972 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700973
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800974 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
975 builder.setDeleteIntent(PendingIntent.getBroadcast(
976 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
977
978 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700979 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800980 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
981
Jeff Sharkey497e4432011-06-14 17:27:29 -0700982 break;
983 }
984 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700985 final CharSequence body = res.getText(R.string.data_usage_limit_body);
986
987 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -0400988 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700989 switch (policy.template.getMatchRule()) {
990 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700991 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700992 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700993 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700994 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700995 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700996 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700997 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700998 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700999 case MATCH_WIFI:
1000 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001001 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001002 break;
1003 default:
1004 title = null;
1005 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001006 }
1007
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001008 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001009 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001010 builder.setTicker(title);
1011 builder.setContentTitle(title);
1012 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001013
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001014 final Intent intent = buildNetworkOverLimitIntent(policy.template);
1015 builder.setContentIntent(PendingIntent.getActivity(
1016 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1017 break;
1018 }
1019 case TYPE_LIMIT_SNOOZED: {
1020 final long overBytes = totalBytes - policy.limitBytes;
1021 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
1022 Formatter.formatFileSize(mContext, overBytes));
1023
1024 final CharSequence title;
1025 switch (policy.template.getMatchRule()) {
1026 case MATCH_MOBILE_3G_LOWER:
1027 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1028 break;
1029 case MATCH_MOBILE_4G:
1030 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1031 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001032 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001033 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1034 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001035 case MATCH_WIFI:
1036 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1037 break;
1038 default:
1039 title = null;
1040 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001041 }
1042
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001043 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001044 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001045 builder.setTicker(title);
1046 builder.setContentTitle(title);
1047 builder.setContentText(body);
1048
1049 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001050 builder.setContentIntent(PendingIntent.getActivity(
1051 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001052 break;
1053 }
1054 }
1055
1056 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -07001057 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -07001058 try {
1059 final String packageName = mContext.getPackageName();
1060 final int[] idReceived = new int[1];
1061 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001062 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Dianne Hackborn41203752012-08-31 14:05:51 -07001063 UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001064 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001065 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001066 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001067 }
1068 }
1069
1070 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001071 * Show ongoing notification to reflect that {@link #mRestrictBackground}
1072 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -07001073 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001074 private void enqueueRestrictedNotification(String tag) {
1075 final Resources res = mContext.getResources();
1076 final Notification.Builder builder = new Notification.Builder(mContext);
1077
1078 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
1079 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
1080
1081 builder.setOnlyAlertOnce(true);
1082 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001083 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001084 builder.setTicker(title);
1085 builder.setContentTitle(title);
1086 builder.setContentText(body);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001087 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001088 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001089
1090 final Intent intent = buildAllowBackgroundDataIntent();
1091 builder.setContentIntent(
1092 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001093
1094 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -07001095 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -07001096 try {
1097 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001098 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001099 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Dianne Hackborn41203752012-08-31 14:05:51 -07001100 0x0, builder.getNotification(), idReceived, UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001101 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001102 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001103 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001104 }
1105 }
1106
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001107 private void cancelNotification(String tag) {
1108 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -07001109 // XXX what to do about multi-user?
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001110 try {
1111 final String packageName = mContext.getPackageName();
1112 mNotifManager.cancelNotificationWithTag(
Dianne Hackborn41203752012-08-31 14:05:51 -07001113 packageName, tag, 0x0, UserHandle.USER_OWNER);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001114 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001115 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001116 }
1117 }
1118
1119 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001120 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001121 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001122 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001123 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001124 @Override
1125 public void onReceive(Context context, Intent intent) {
1126 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1127 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001128
1129 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001130 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001131 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001132 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001133 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001134 updateNetworkRulesLocked();
1135 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001136 }
1137 }
1138 };
1139
1140 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001141 * Proactively control network data connections when they exceed
1142 * {@link NetworkPolicy#limitBytes}.
1143 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001144 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001145 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1146
1147 // TODO: reset any policy-disabled networks when any policy is removed
1148 // completely, which is currently rare case.
1149
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001150 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001151 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1152 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001153 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001154 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001155 setNetworkTemplateEnabled(policy.template, true);
1156 continue;
1157 }
1158
1159 final long start = computeLastCycleBoundary(currentTime, policy);
1160 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001161 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001162
1163 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001164 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1165 && policy.lastLimitSnooze < start;
1166 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001167
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001168 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001169 }
1170 }
1171
1172 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001173 * Proactively disable networks that match the given
1174 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001175 */
1176 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001177 // TODO: reach into ConnectivityManager to proactively disable bringing
1178 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001179 }
1180
1181 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001182 * Examine all connected {@link NetworkState}, looking for
1183 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1184 * remaining quota based on usage cycle and historical stats.
1185 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001186 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001187 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001188
1189 final NetworkState[] states;
1190 try {
1191 states = mConnManager.getAllNetworkState();
1192 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001193 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001194 return;
1195 }
1196
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001197 // If we are in restrict power mode, we want to treat all interfaces
1198 // as metered, to restrict access to the network by uid. However, we
1199 // will not have a bandwidth limit. Also only do this if restrict
1200 // background data use is *not* enabled, since that takes precendence
1201 // use over those networks can have a cost associated with it).
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001202 final boolean powerSave = mRestrictPower && !mRestrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001203
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001204 // First, generate identities of all connected networks so we can
1205 // quickly compare them against all defined policies below.
1206 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001207 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001208 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001209 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001210 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001211
1212 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001213 if (baseIface != null) {
1214 connIdents.add(Pair.create(baseIface, ident));
1215 if (powerSave) {
1216 connIfaces.add(baseIface);
1217 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001218 }
1219
1220 // Stacked interfaces are considered to have same identity as
1221 // their parent network.
1222 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1223 for (LinkProperties stackedLink : stackedLinks) {
1224 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001225 if (stackedIface != null) {
1226 connIdents.add(Pair.create(stackedIface, ident));
1227 if (powerSave) {
1228 connIfaces.add(stackedIface);
1229 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001230 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001231 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001232 }
1233 }
1234
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001235 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001236 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001237 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001238 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001239 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001240
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001241 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001242 for (int j = connIdents.size() - 1; j >= 0; j--) {
1243 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1244 if (policy.template.matches(ident.second)) {
1245 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001246 }
1247 }
1248
1249 if (ifaceList.size() > 0) {
1250 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001251 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001252 }
1253 }
1254
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001255 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001256 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001257
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001258 // apply each policy that we found ifaces for; compute remaining data
1259 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001260 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001261 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1262 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1263 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001264
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001265 final long start;
1266 final long totalBytes;
1267 if (policy.hasCycle()) {
1268 start = computeLastCycleBoundary(currentTime, policy);
1269 totalBytes = getTotalBytes(policy.template, start, currentTime);
1270 } else {
1271 start = Long.MAX_VALUE;
1272 totalBytes = 0;
1273 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001274
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001275 if (LOGD) {
1276 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001277 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001278 }
1279
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001280 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001281 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001282 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001283 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001284 if (!hasLimit) {
1285 // metered network, but no policy limit; we still need to
1286 // restrict apps, so push really high quota.
1287 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001288 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001289 // snoozing past quota, but we still need to restrict apps,
1290 // so push really high quota.
1291 quotaBytes = Long.MAX_VALUE;
1292 } else {
1293 // remaining "quota" bytes are based on total usage in
1294 // current cycle. kernel doesn't like 0-byte rules, so we
1295 // set 1-byte quota and disable the radio later.
1296 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1297 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001298
1299 if (ifaces.length > 1) {
1300 // TODO: switch to shared quota once NMS supports
1301 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001302 }
1303
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001304 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001305 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001306 setInterfaceQuota(iface, quotaBytes);
1307 newMeteredIfaces.add(iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001308 if (powerSave) {
1309 connIfaces.remove(iface);
1310 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001311 }
1312 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001313
1314 // keep track of lowest warning or limit of active policies
1315 if (hasWarning && policy.warningBytes < lowestRule) {
1316 lowestRule = policy.warningBytes;
1317 }
1318 if (hasLimit && policy.limitBytes < lowestRule) {
1319 lowestRule = policy.limitBytes;
1320 }
1321 }
1322
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001323 for (int i = connIfaces.size()-1; i >= 0; i--) {
1324 String iface = connIfaces.valueAt(i);
1325 removeInterfaceQuota(iface);
1326 setInterfaceQuota(iface, Long.MAX_VALUE);
1327 newMeteredIfaces.add(iface);
1328 }
1329
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001330 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001331
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001332 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001333 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1334 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001335 if (!newMeteredIfaces.contains(iface)) {
1336 removeInterfaceQuota(iface);
1337 }
1338 }
1339 mMeteredIfaces = newMeteredIfaces;
1340
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001341 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001342 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001343 }
1344
1345 /**
1346 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1347 * have at least a default mobile policy defined.
1348 */
1349 private void ensureActiveMobilePolicyLocked() {
1350 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001351 if (mSuppressDefaultPolicy) return;
1352
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001353 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001354 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001355
Jeff Sharkey32566012014-12-02 18:30:14 -08001356 final int[] subIds = sub.getActiveSubscriptionIdList();
1357 for (int subId : subIds) {
1358 final String subscriberId = tele.getSubscriberId(subId);
1359 ensureActiveMobilePolicyLocked(subscriberId);
1360 }
1361 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001362
Jeff Sharkey32566012014-12-02 18:30:14 -08001363 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1364 // Poke around to see if we already have a policy
1365 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1366 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1367 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1368 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1369 if (template.matches(probeIdent)) {
1370 if (LOGD) {
1371 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1372 + NetworkIdentity.scrubSubscriberId(subscriberId));
1373 }
1374 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001375 }
1376 }
1377
Jeff Sharkey32566012014-12-02 18:30:14 -08001378 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1379 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001380
Jeff Sharkey32566012014-12-02 18:30:14 -08001381 // Build default mobile policy, and assume usage cycle starts today
1382 final long warningBytes = mContext.getResources().getInteger(
1383 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001384
Jeff Sharkey32566012014-12-02 18:30:14 -08001385 final Time time = new Time();
1386 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001387
Jeff Sharkey32566012014-12-02 18:30:14 -08001388 final int cycleDay = time.monthDay;
1389 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001390
Jeff Sharkey32566012014-12-02 18:30:14 -08001391 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1392 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1393 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1394 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001395 }
1396
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001397 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001398 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001399
1400 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001401 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001402 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001403
1404 FileInputStream fis = null;
1405 try {
1406 fis = mPolicyFile.openRead();
1407 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001408 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001409
1410 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001411 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001412 while ((type = in.next()) != END_DOCUMENT) {
1413 final String tag = in.getName();
1414 if (type == START_TAG) {
1415 if (TAG_POLICY_LIST.equals(tag)) {
1416 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001417 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1418 mRestrictBackground = readBooleanAttribute(
1419 in, ATTR_RESTRICT_BACKGROUND);
1420 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001421 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001422 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001423
1424 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1425 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1426 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001427 final String networkId;
1428 if (version >= VERSION_ADDED_NETWORK_ID) {
1429 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1430 } else {
1431 networkId = null;
1432 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001433 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001434 final String cycleTimezone;
1435 if (version >= VERSION_ADDED_TIMEZONE) {
1436 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1437 } else {
1438 cycleTimezone = Time.TIMEZONE_UTC;
1439 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001440 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1441 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001442 final long lastLimitSnooze;
1443 if (version >= VERSION_SPLIT_SNOOZE) {
1444 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1445 } else if (version >= VERSION_ADDED_SNOOZE) {
1446 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001447 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001448 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001449 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001450 final boolean metered;
1451 if (version >= VERSION_ADDED_METERED) {
1452 metered = readBooleanAttribute(in, ATTR_METERED);
1453 } else {
1454 switch (networkTemplate) {
1455 case MATCH_MOBILE_3G_LOWER:
1456 case MATCH_MOBILE_4G:
1457 case MATCH_MOBILE_ALL:
1458 metered = true;
1459 break;
1460 default:
1461 metered = false;
1462 }
1463 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001464 final long lastWarningSnooze;
1465 if (version >= VERSION_SPLIT_SNOOZE) {
1466 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1467 } else {
1468 lastWarningSnooze = SNOOZE_NEVER;
1469 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001470 final boolean inferred;
1471 if (version >= VERSION_ADDED_INFERRED) {
1472 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1473 } else {
1474 inferred = false;
1475 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001476
Jeff Sharkey32566012014-12-02 18:30:14 -08001477 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1478 subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001479 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001480 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001481 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001482
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001483 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001484 final int uid = readIntAttribute(in, ATTR_UID);
1485 final int policy = readIntAttribute(in, ATTR_POLICY);
1486
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001487 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001488 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001489 } else {
1490 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1491 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001492 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001493 final int appId = readIntAttribute(in, ATTR_APP_ID);
1494 final int policy = readIntAttribute(in, ATTR_POLICY);
1495
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001496 // TODO: set for other users during upgrade
1497 final int uid = UserHandle.getUid(UserHandle.USER_OWNER, appId);
1498 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001499 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001500 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001501 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001502 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001503 }
1504 }
1505 }
1506
1507 } catch (FileNotFoundException e) {
1508 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001509 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001510 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001511 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001512 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001513 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001514 } finally {
1515 IoUtils.closeQuietly(fis);
1516 }
1517 }
1518
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001519 /**
1520 * Upgrade legacy background data flags, notifying listeners of one last
1521 * change to always-true.
1522 */
1523 private void upgradeLegacyBackgroundData() {
1524 mRestrictBackground = Settings.Secure.getInt(
1525 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1526
1527 // kick off one last broadcast if restricted
1528 if (mRestrictBackground) {
1529 final Intent broadcast = new Intent(
1530 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001531 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001532 }
1533 }
1534
Dianne Hackborn497175b2014-07-01 12:56:08 -07001535 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001536 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001537
1538 FileOutputStream fos = null;
1539 try {
1540 fos = mPolicyFile.startWrite();
1541
1542 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001543 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001544 out.startDocument(null, true);
1545
1546 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001547 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001548 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001549
1550 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001551 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1552 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001553 final NetworkTemplate template = policy.template;
1554
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001555 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001556 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1557 final String subscriberId = template.getSubscriberId();
1558 if (subscriberId != null) {
1559 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001560 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001561 final String networkId = template.getNetworkId();
1562 if (networkId != null) {
1563 out.attribute(null, ATTR_NETWORK_ID, networkId);
1564 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001565 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001566 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001567 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1568 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001569 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1570 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001571 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001572 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001573 out.endTag(null, TAG_NETWORK_POLICY);
1574 }
1575
1576 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001577 for (int i = 0; i < mUidPolicy.size(); i++) {
1578 final int uid = mUidPolicy.keyAt(i);
1579 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001580
Jeff Sharkey497e4432011-06-14 17:27:29 -07001581 // skip writing empty policies
1582 if (policy == POLICY_NONE) continue;
1583
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001584 out.startTag(null, TAG_UID_POLICY);
1585 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001586 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001587 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001588 }
1589
1590 out.endTag(null, TAG_POLICY_LIST);
1591 out.endDocument();
1592
1593 mPolicyFile.finishWrite(fos);
1594 } catch (IOException e) {
1595 if (fos != null) {
1596 mPolicyFile.failWrite(fos);
1597 }
1598 }
1599 }
1600
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001601 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001602 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001603 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001604
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001605 if (!UserHandle.isApp(uid)) {
1606 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001607 }
1608
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001609 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001610 final long token = Binder.clearCallingIdentity();
1611 try {
1612 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1613 if (oldPolicy != policy) {
1614 setUidPolicyUncheckedLocked(uid, policy, true);
1615 }
1616 } finally {
1617 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001618 }
1619 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001620 }
1621
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001622 @Override
1623 public void addUidPolicy(int uid, int policy) {
1624 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001625
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001626 if (!UserHandle.isApp(uid)) {
1627 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1628 }
1629
1630 synchronized (mRulesLock) {
1631 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1632 policy |= oldPolicy;
1633 if (oldPolicy != policy) {
1634 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001635 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001636 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001637 }
1638
1639 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001640 public void removeUidPolicy(int uid, int policy) {
1641 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1642
1643 if (!UserHandle.isApp(uid)) {
1644 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1645 }
1646
1647 synchronized (mRulesLock) {
1648 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1649 policy = oldPolicy & ~policy;
1650 if (oldPolicy != policy) {
1651 setUidPolicyUncheckedLocked(uid, policy, true);
1652 }
1653 }
1654 }
1655
1656 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1657 mUidPolicy.put(uid, policy);
1658
1659 // uid policy changed, recompute rules and persist policy.
1660 updateRulesForUidLocked(uid);
1661 if (persist) {
1662 writePolicyLocked();
1663 }
1664 }
1665
1666 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001667 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001668 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1669
Jeff Sharkeya4620792011-05-20 15:29:23 -07001670 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001671 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001672 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001673 }
1674
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001675 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001676 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001677 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1678
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001679 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001680 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001681 for (int i = 0; i < mUidPolicy.size(); i++) {
1682 final int uid = mUidPolicy.keyAt(i);
1683 final int uidPolicy = mUidPolicy.valueAt(i);
1684 if (uidPolicy == policy) {
1685 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001686 }
1687 }
1688 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001689 return uids;
1690 }
1691
1692 /**
1693 * Remove any policies associated with given {@link UserHandle}, persisting
1694 * if any changes are made.
1695 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001696 void removePoliciesForUserLocked(int userId) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001697 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1698
1699 int[] uids = new int[0];
1700 for (int i = 0; i < mUidPolicy.size(); i++) {
1701 final int uid = mUidPolicy.keyAt(i);
1702 if (UserHandle.getUserId(uid) == userId) {
1703 uids = appendInt(uids, uid);
1704 }
1705 }
1706
1707 if (uids.length > 0) {
1708 for (int uid : uids) {
1709 mUidPolicy.delete(uid);
1710 updateRulesForUidLocked(uid);
1711 }
1712 writePolicyLocked();
1713 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001714 }
1715
1716 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001717 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001718 // TODO: create permission for observing network policy
1719 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1720
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001721 mListeners.register(listener);
1722
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001723 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001724 }
1725
1726 @Override
1727 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001728 // TODO: create permission for observing network policy
1729 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1730
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001731 mListeners.unregister(listener);
1732 }
1733
Jeff Sharkey1b861272011-05-22 00:34:52 -07001734 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001735 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001736 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1737
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001738 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001739 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001740 normalizePoliciesLocked(policies);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001741 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001742 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001743 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001744 writePolicyLocked();
1745 }
1746 }
1747
Dianne Hackborn497175b2014-07-01 12:56:08 -07001748 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001749 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001750 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1751 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001752 }
1753
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001754 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001755 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001756 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001757 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001758 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1759 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1760 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001761 } catch (SecurityException e) {
1762 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001763
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001764 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1765 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1766 return new NetworkPolicy[0];
1767 }
Svet Ganov16a16892015-04-16 10:32:04 -07001768 }
1769
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001770 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001771 final int size = mNetworkPolicy.size();
1772 final NetworkPolicy[] policies = new NetworkPolicy[size];
1773 for (int i = 0; i < size; i++) {
1774 policies[i] = mNetworkPolicy.valueAt(i);
1775 }
1776 return policies;
1777 }
1778 }
1779
1780 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001781 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001782 }
1783
1784 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1785 final TelephonyManager tele = TelephonyManager.from(mContext);
1786 final String[] merged = tele.getMergedSubscriberIds();
1787
1788 mNetworkPolicy.clear();
1789 for (NetworkPolicy policy : policies) {
1790 // When two normalized templates conflict, prefer the most
1791 // restrictive policy
1792 policy.template = NetworkTemplate.normalize(policy.template, merged);
1793 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1794 if (existing == null || existing.compareTo(policy) > 0) {
1795 if (existing != null) {
1796 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1797 }
1798 mNetworkPolicy.put(policy.template, policy);
1799 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001800 }
1801 }
1802
1803 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001804 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001805 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001806
1807 final long token = Binder.clearCallingIdentity();
1808 try {
1809 performSnooze(template, TYPE_LIMIT);
1810 } finally {
1811 Binder.restoreCallingIdentity(token);
1812 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001813 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001814
Zach Johnson143ebdb2015-08-10 16:34:04 -07001815 @Override
1816 public void snoozeWarning(NetworkTemplate template) {
1817 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1818
1819 final long token = Binder.clearCallingIdentity();
1820 try {
1821 // TODO: this seems like a race condition? (along with snoozeLimit above)
1822 performSnooze(template, TYPE_WARNING);
1823 } finally {
1824 Binder.restoreCallingIdentity(token);
1825 }
1826 }
1827
Dianne Hackborn497175b2014-07-01 12:56:08 -07001828 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001829 maybeRefreshTrustedTime();
1830 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001831 synchronized (mRulesLock) {
1832 // find and snooze local policy that matches
1833 final NetworkPolicy policy = mNetworkPolicy.get(template);
1834 if (policy == null) {
1835 throw new IllegalArgumentException("unable to find policy for " + template);
1836 }
1837
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001838 switch (type) {
1839 case TYPE_WARNING:
1840 policy.lastWarningSnooze = currentTime;
1841 break;
1842 case TYPE_LIMIT:
1843 policy.lastLimitSnooze = currentTime;
1844 break;
1845 default:
1846 throw new IllegalArgumentException("unexpected type");
1847 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001848
Jeff Sharkey32566012014-12-02 18:30:14 -08001849 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001850 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001851 updateNetworkRulesLocked();
1852 updateNotificationsLocked();
1853 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001854 }
1855 }
1856
1857 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001858 public void setRestrictBackground(boolean restrictBackground) {
1859 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1860
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001861 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001862 synchronized (mRulesLock) {
1863 mRestrictBackground = restrictBackground;
Jeff Sharkey9d142062015-08-12 16:46:05 -07001864 updateRulesForGlobalChangeLocked(true);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001865 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001866 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001867 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001868
1869 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1870 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001871 }
1872
1873 @Override
1874 public boolean getRestrictBackground() {
1875 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1876
1877 synchronized (mRulesLock) {
1878 return mRestrictBackground;
1879 }
1880 }
1881
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001882 @Override
1883 public void setDeviceIdleMode(boolean enabled) {
1884 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1885
1886 synchronized (mRulesLock) {
1887 if (mDeviceIdleMode != enabled) {
1888 mDeviceIdleMode = enabled;
1889 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07001890 // Device idle change means we need to rebuild rules for all
1891 // known apps, so do a global refresh.
1892 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001893 }
1894 if (enabled) {
1895 EventLogTags.writeDeviceIdleOnPhase("net");
1896 } else {
1897 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001898 }
1899 }
1900 }
1901 }
1902
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001903 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001904 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1905 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001906 if (policy.template.matches(ident)) {
1907 return policy;
1908 }
1909 }
1910 return null;
1911 }
1912
1913 @Override
1914 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1915 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1916
1917 // only returns usage summary, so we don't require caller to have
1918 // READ_NETWORK_USAGE_HISTORY.
1919 final long token = Binder.clearCallingIdentity();
1920 try {
1921 return getNetworkQuotaInfoUnchecked(state);
1922 } finally {
1923 Binder.restoreCallingIdentity(token);
1924 }
1925 }
1926
1927 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1928 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1929
1930 final NetworkPolicy policy;
1931 synchronized (mRulesLock) {
1932 policy = findPolicyForNetworkLocked(ident);
1933 }
1934
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001935 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001936 // missing policy means we can't derive useful quota info
1937 return null;
1938 }
1939
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001940 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001941
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001942 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001943 final long start = computeLastCycleBoundary(currentTime, policy);
1944 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001945 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001946
1947 // report soft and hard limits under policy
1948 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1949 : NetworkQuotaInfo.NO_LIMIT;
1950 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1951 : NetworkQuotaInfo.NO_LIMIT;
1952
1953 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1954 }
1955
Jeff Sharkey46645002011-07-27 21:11:21 -07001956 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001957 public boolean isNetworkMetered(NetworkState state) {
1958 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1959
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001960 // roaming networks are always considered metered
1961 if (ident.getRoaming()) {
1962 return true;
1963 }
1964
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001965 final NetworkPolicy policy;
1966 synchronized (mRulesLock) {
1967 policy = findPolicyForNetworkLocked(ident);
1968 }
1969
1970 if (policy != null) {
1971 return policy.metered;
1972 } else {
Wei Liub8eaf452016-01-25 10:32:27 -08001973 if (state.networkInfo == null) {
1974 return false;
1975 }
1976
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001977 final int type = state.networkInfo.getType();
1978 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1979 return true;
1980 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001981 return false;
1982 }
1983 }
1984
1985 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001986 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001987 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001988
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001989 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1990
Dianne Hackborn497175b2014-07-01 12:56:08 -07001991 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001992 for (String arg : args) {
1993 argSet.add(arg);
1994 }
1995
Jeff Sharkey1b861272011-05-22 00:34:52 -07001996 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001997 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001998 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1999 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002000 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002001
Jeff Sharkey32566012014-12-02 18:30:14 -08002002 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002003 updateNetworkEnabledLocked();
2004 updateNetworkRulesLocked();
2005 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002006 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002007
2008 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002009 return;
2010 }
2011
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002012 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07002013 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002014 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002015 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002016 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002017 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002018 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2019 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002020 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002021 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002022
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07002023 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2024
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002025 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002026 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002027 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002028 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002029 final int uid = mUidPolicy.keyAt(i);
2030 final int policy = mUidPolicy.valueAt(i);
2031 fout.print("UID=");
2032 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002033 fout.print(" policy=");
Jeff Sharkeydc988062015-09-14 10:09:47 -07002034 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002035 fout.println();
2036 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002037 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002038
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002039 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2040 if (size > 0) {
2041 fout.println("Power save whitelist (except idle) app ids:");
2042 fout.increaseIndent();
2043 for (int i = 0; i < size; i++) {
2044 fout.print("UID=");
2045 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2046 fout.print(": ");
2047 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2048 fout.println();
2049 }
2050 fout.decreaseIndent();
2051 }
2052
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002053 size = mPowerSaveWhitelistAppIds.size();
2054 if (size > 0) {
2055 fout.println("Power save whitelist app ids:");
2056 fout.increaseIndent();
2057 for (int i = 0; i < size; i++) {
2058 fout.print("UID=");
2059 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2060 fout.print(": ");
2061 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2062 fout.println();
2063 }
2064 fout.decreaseIndent();
2065 }
2066
Jeff Sharkey1b861272011-05-22 00:34:52 -07002067 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07002068 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002069 collectKeys(mUidRules, knownUids);
2070
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002071 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002072 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002073 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002074 for (int i = 0; i < size; i++) {
2075 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002076 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07002077 fout.print(uid);
2078
Jeff Sharkeydc988062015-09-14 10:09:47 -07002079 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002080 fout.print(" state=");
2081 fout.print(state);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002082 fout.print(state <= ActivityManager.PROCESS_STATE_TOP ? " (fg)" : " (bg)");
Dianne Hackborn497175b2014-07-01 12:56:08 -07002083
Jeff Sharkeydc988062015-09-14 10:09:47 -07002084 final int rule = mUidRules.get(uid, RULE_UNKNOWN);
2085 fout.print(" rule=");
2086 fout.print(DebugUtils.valueToString(NetworkPolicyManager.class, "RULE_", rule));
Jeff Sharkey1b861272011-05-22 00:34:52 -07002087
2088 fout.println();
2089 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002090 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002091 }
2092 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002093
2094 @Override
2095 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002096 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2097
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002098 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002099 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002100 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002101 }
2102
Dianne Hackborn497175b2014-07-01 12:56:08 -07002103 boolean isUidForegroundLocked(int uid) {
2104 // only really in foreground when screen is also on
2105 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002106 <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002107 }
2108
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002109 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002110 * Process state of UID changed; if needed, will trigger
2111 * {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002112 */
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002113 void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002114 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2115 if (oldUidState != uidState) {
2116 // state changed, push updated rules
2117 mUidState.put(uid, uidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002118 updateRulesForUidStateChangeLocked(uid, oldUidState, uidState);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002119 if (mDeviceIdleMode && isProcStateAllowedWhileIdle(oldUidState)
2120 != isProcStateAllowedWhileIdle(uidState)) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002121 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002122 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002123 }
2124 }
2125
2126 void removeUidStateLocked(int uid) {
2127 final int index = mUidState.indexOfKey(uid);
2128 if (index >= 0) {
2129 final int oldUidState = mUidState.valueAt(index);
2130 mUidState.removeAt(index);
2131 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
2132 updateRulesForUidStateChangeLocked(uid, oldUidState,
2133 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002134 if (mDeviceIdleMode) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002135 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002136 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002137 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002138 }
2139 }
2140
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002141 void updateRulesForUidStateChangeLocked(int uid, int oldUidState, int newUidState) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002142 final boolean oldForeground = oldUidState <= ActivityManager.PROCESS_STATE_TOP;
2143 final boolean newForeground = newUidState <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002144 if (oldForeground != newForeground) {
2145 updateRulesForUidLocked(uid);
2146 }
2147 }
2148
Jeff Sharkeya4620792011-05-20 15:29:23 -07002149 private void updateScreenOn() {
2150 synchronized (mRulesLock) {
2151 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002152 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002153 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002154 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002155 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002156 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002157 }
2158 }
2159
2160 /**
2161 * Update rules that might be changed by {@link #mScreenOn} value.
2162 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002163 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002164 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002165 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002166 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002167 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002168 final int uid = mUidState.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002169 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002170 }
2171 }
2172 }
2173
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002174 static boolean isProcStateAllowedWhileIdle(int procState) {
2175 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2176 }
2177
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002178 void updateRulesForDeviceIdleLocked() {
2179 if (mDeviceIdleMode) {
2180 // sync the whitelists before enable dozable chain. We don't care about the rules if
2181 // we are disabling the chain.
Jeff Sharkeydc988062015-09-14 10:09:47 -07002182 final SparseIntArray uidRules = mUidFirewallDozableRules;
2183 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002184 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002185 for (int ui = users.size() - 1; ui >= 0; ui--) {
2186 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002187 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002188 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2189 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2190 int uid = UserHandle.getUid(user.id, appId);
2191 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2192 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002193 }
2194 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2195 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2196 int uid = UserHandle.getUid(user.id, appId);
2197 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2198 }
2199 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002200 for (int i = mUidState.size() - 1; i >= 0; i--) {
2201 if (isProcStateAllowedWhileIdle(mUidState.valueAt(i))) {
2202 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2203 }
2204 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002205 setUidFirewallRules(FIREWALL_CHAIN_DOZABLE, uidRules);
2206 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002207
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002208 enableFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, mDeviceIdleMode);
2209 }
2210
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002211 void updateRuleForDeviceIdleLocked(int uid) {
2212 if (mDeviceIdleMode) {
2213 int appId = UserHandle.getAppId(uid);
2214 if (mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId)
2215 || isProcStateAllowedWhileIdle(mUidState.get(uid))) {
2216 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_ALLOW);
2217 } else {
2218 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
2219 }
2220 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002221
2222 updateRulesForUidLocked(uid);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002223 }
2224
2225 void updateRulesForAppIdleLocked() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002226 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2227 uidRules.clear();
2228
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002229 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002230 final List<UserInfo> users = mUserManager.getUsers();
2231 for (int ui = users.size() - 1; ui >= 0; ui--) {
2232 UserInfo user = users.get(ui);
2233 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2234 for (int uid : idleUids) {
2235 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2236 uidRules.put(uid, FIREWALL_RULE_DENY);
2237 }
2238 }
2239 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002240
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002241 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2242 }
2243
2244 void updateRuleForAppIdleLocked(int uid) {
2245 if (!isUidValidForRules(uid)) return;
2246
2247 int appId = UserHandle.getAppId(uid);
2248 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)) {
2249 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2250 } else {
2251 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2252 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002253
2254 updateRulesForUidLocked(uid);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002255 }
2256
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002257 void updateRulesForAppIdleParoleLocked() {
2258 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2259 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Jeff Sharkeydc988062015-09-14 10:09:47 -07002260 updateRulesForUidsLocked(mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002261 }
2262
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002263 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002264 * Update rules that might be changed by {@link #mRestrictBackground},
2265 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002266 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002267 void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002268 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002269
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002270 updateRulesForDeviceIdleLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002271 updateRulesForAppIdleLocked();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002272
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002273 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002274 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002275 final List<ApplicationInfo> apps = pm.getInstalledApplications(
2276 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
2277
2278 for (UserInfo user : users) {
2279 for (ApplicationInfo app : apps) {
2280 final int uid = UserHandle.getUid(user.id, app.uid);
2281 updateRulesForUidLocked(uid);
2282 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002283 }
2284
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002285 // limit data usage for some internal system services
2286 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
2287 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002288
2289 // If the set of restricted networks may have changed, re-evaluate those.
2290 if (restrictedNetworksChanged) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002291 normalizePoliciesLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002292 updateNetworkRulesLocked();
2293 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002294 }
2295
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002296 void updateRulesForTempWhitelistChangeLocked() {
2297 final List<UserInfo> users = mUserManager.getUsers();
2298 for (UserInfo user : users) {
2299 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
2300 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2301 int uid = UserHandle.getUid(user.id, appId);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002302 updateRuleForAppIdleLocked(uid);
2303 updateRuleForDeviceIdleLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002304 }
2305 }
2306 }
2307
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002308 private static boolean isUidValidForRules(int uid) {
2309 // allow rules on specific system services, and any apps
2310 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002311 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002312 return true;
2313 }
2314
2315 return false;
2316 }
2317
Amith Yamasani15e472352015-04-24 19:06:07 -07002318 private boolean isUidIdle(int uid) {
2319 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2320 final int userId = UserHandle.getUserId(uid);
2321
Erik Wolsheimer23797962016-06-06 10:49:02 -07002322 if (!ArrayUtils.isEmpty(packages)) {
2323 for (String packageName : packages) {
2324 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2325 return false;
2326 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002327 }
2328 }
2329 return true;
2330 }
2331
Jeff Sharkeydc988062015-09-14 10:09:47 -07002332 void updateRulesForUidsLocked(SparseIntArray uids) {
2333 for (int i = 0; i < uids.size(); i++) {
2334 updateRulesForUidLocked(uids.keyAt(i));
2335 }
2336 }
2337
Amith Yamasani15e472352015-04-24 19:06:07 -07002338 /**
2339 * Applies network rules to bandwidth and firewall controllers based on uid policy.
2340 * @param uid The uid for which to apply the latest policy
2341 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002342 void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002343 if (!isUidValidForRules(uid)) return;
2344
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002345 // quick check: if this uid doesn't have INTERNET permission, it doesn't have
2346 // network access anyway, so it is a waste to mess with it here.
2347 final IPackageManager ipm = AppGlobals.getPackageManager();
2348 try {
2349 if (ipm.checkUidPermission(Manifest.permission.INTERNET, uid)
2350 != PackageManager.PERMISSION_GRANTED) {
2351 return;
2352 }
2353 } catch (RemoteException e) {
2354 }
2355
Dianne Hackborn497175b2014-07-01 12:56:08 -07002356 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2357 final boolean uidForeground = isUidForegroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002358
Jeff Sharkeydc988062015-09-14 10:09:47 -07002359 // Derive active rules based on policy and active state
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002360 int appId = UserHandle.getAppId(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002361 int uidRules = RULE_ALLOW_ALL;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002362 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002363 // uid in background, and policy says to block metered data
2364 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002365 } else if (mRestrictBackground) {
2366 if (!uidForeground) {
2367 // uid in background, and global background disabled
2368 uidRules = RULE_REJECT_METERED;
2369 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002370 } else if (mRestrictPower) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002371 final boolean whitelisted = mPowerSaveWhitelistExceptIdleAppIds.get(appId)
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002372 || mPowerSaveTempWhitelistAppIds.get(appId);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002373 if (!whitelisted && !uidForeground
2374 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
2375 // uid is in background, restrict power use mode is on (so we want to
2376 // restrict all background network access), and this uid is not on the
2377 // white list of those allowed background access.
2378 uidRules = RULE_REJECT_METERED;
2379 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002380 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002381
Jeff Sharkeydc988062015-09-14 10:09:47 -07002382 // Check dozable state, which is whitelist
2383 if (mFirewallChainStates.get(FIREWALL_CHAIN_DOZABLE)
2384 && mUidFirewallDozableRules.get(uid, FIREWALL_RULE_DEFAULT) != FIREWALL_RULE_ALLOW) {
2385 uidRules = RULE_REJECT_ALL;
2386 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002387
Jeff Sharkeydc988062015-09-14 10:09:47 -07002388 // Check standby state, which is blacklist
2389 if (mFirewallChainStates.get(FIREWALL_CHAIN_STANDBY)
2390 && mUidFirewallStandbyRules.get(uid, FIREWALL_RULE_DEFAULT) == FIREWALL_RULE_DENY) {
2391 uidRules = RULE_REJECT_ALL;
2392 }
2393
2394 final int oldRules = mUidRules.get(uid);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002395 if (uidRules == RULE_ALLOW_ALL) {
2396 mUidRules.delete(uid);
2397 } else {
2398 mUidRules.put(uid, uidRules);
2399 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002400
Jeff Sharkeydc988062015-09-14 10:09:47 -07002401 final boolean rejectMetered = (uidRules == RULE_REJECT_METERED);
2402 setUidNetworkRules(uid, rejectMetered);
Amith Yamasani15e472352015-04-24 19:06:07 -07002403
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002404 // dispatch changed rule to existing listeners
Amith Yamasani15e472352015-04-24 19:06:07 -07002405 if (oldRules != uidRules) {
2406 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
2407 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002408
2409 try {
2410 // adjust stats accounting based on foreground status
2411 mNetworkStats.setUidForeground(uid, uidForeground);
2412 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002413 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002414 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002415 }
2416
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002417 private class AppIdleStateChangeListener
2418 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2419
2420 @Override
2421 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2422 try {
2423 int uid = mContext.getPackageManager().getPackageUid(packageName, userId);
2424 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002425 updateRuleForAppIdleLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002426 }
2427 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002428 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002429 }
2430
2431 @Override
2432 public void onParoleStateChanged(boolean isParoleOn) {
2433 synchronized (mRulesLock) {
2434 updateRulesForAppIdleParoleLocked();
2435 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002436 }
2437 }
2438
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002439 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002440 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002441 public boolean handleMessage(Message msg) {
2442 switch (msg.what) {
2443 case MSG_RULES_CHANGED: {
2444 final int uid = msg.arg1;
2445 final int uidRules = msg.arg2;
2446 final int length = mListeners.beginBroadcast();
2447 for (int i = 0; i < length; i++) {
2448 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2449 if (listener != null) {
2450 try {
2451 listener.onUidRulesChanged(uid, uidRules);
2452 } catch (RemoteException e) {
2453 }
2454 }
2455 }
2456 mListeners.finishBroadcast();
2457 return true;
2458 }
2459 case MSG_METERED_IFACES_CHANGED: {
2460 final String[] meteredIfaces = (String[]) msg.obj;
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.onMeteredIfacesChanged(meteredIfaces);
2467 } catch (RemoteException e) {
2468 }
2469 }
2470 }
2471 mListeners.finishBroadcast();
2472 return true;
2473 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002474 case MSG_LIMIT_REACHED: {
2475 final String iface = (String) msg.obj;
2476
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002477 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002478 synchronized (mRulesLock) {
2479 if (mMeteredIfaces.contains(iface)) {
2480 try {
2481 // force stats update to make sure we have
2482 // numbers that caused alert to trigger.
2483 mNetworkStats.forceUpdate();
2484 } catch (RemoteException e) {
2485 // ignored; service lives in system_server
2486 }
2487
2488 updateNetworkEnabledLocked();
2489 updateNotificationsLocked();
2490 }
2491 }
2492 return true;
2493 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002494 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2495 final boolean restrictBackground = msg.arg1 != 0;
2496 final int length = mListeners.beginBroadcast();
2497 for (int i = 0; i < length; i++) {
2498 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2499 if (listener != null) {
2500 try {
2501 listener.onRestrictBackgroundChanged(restrictBackground);
2502 } catch (RemoteException e) {
2503 }
2504 }
2505 }
2506 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002507 return true;
2508 }
2509 case MSG_ADVISE_PERSIST_THRESHOLD: {
2510 final long lowestRule = (Long) msg.obj;
2511 try {
2512 // make sure stats are recorded frequently enough; we aim
2513 // for 2MB threshold for 2GB/month rules.
2514 final long persistThreshold = lowestRule / 1000;
2515 mNetworkStats.advisePersistThreshold(persistThreshold);
2516 } catch (RemoteException e) {
2517 // ignored; service lives in system_server
2518 }
2519 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002520 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002521 case MSG_SCREEN_ON_CHANGED: {
2522 updateScreenOn();
2523 return true;
2524 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002525 default: {
2526 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002527 }
2528 }
2529 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002530 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002531
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002532 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002533 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002534 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002535 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002536 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002537 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002538 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002539 }
2540 }
2541
2542 private void removeInterfaceQuota(String iface) {
2543 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002544 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002545 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002546 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002547 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002548 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002549 }
2550 }
2551
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002552 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2553 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002554 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002555 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002556 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002557 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002558 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002559 }
2560 }
2561
Amith Yamasani15e472352015-04-24 19:06:07 -07002562 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002563 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
2564 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
2565 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07002566 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002567 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002568 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002569 int size = uidRules.size();
2570 int[] uids = new int[size];
2571 int[] rules = new int[size];
2572 for(int index = size - 1; index >= 0; --index) {
2573 uids[index] = uidRules.keyAt(index);
2574 rules[index] = uidRules.valueAt(index);
2575 }
2576 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002577 } catch (IllegalStateException e) {
2578 Log.wtf(TAG, "problem setting firewall uid rules", e);
2579 } catch (RemoteException e) {
2580 // ignored; service lives in system_server
2581 }
2582 }
2583
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002584 /**
2585 * Add or remove a uid to the firewall blacklist for all network ifaces.
2586 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002587 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002588 if (chain == FIREWALL_CHAIN_DOZABLE) {
2589 mUidFirewallDozableRules.put(uid, rule);
2590 } else if (chain == FIREWALL_CHAIN_STANDBY) {
2591 mUidFirewallStandbyRules.put(uid, rule);
2592 }
2593
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002594 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002595 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002596 } catch (IllegalStateException e) {
2597 Log.wtf(TAG, "problem setting firewall uid rules", e);
2598 } catch (RemoteException e) {
2599 // ignored; service lives in system_server
2600 }
2601 }
2602
2603 /**
2604 * Add or remove a uid to the firewall blacklist for all network ifaces.
2605 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002606 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chen690f18a2015-10-20 13:53:45 -07002607 if (mFirewallChainStates.get(chain, false) == enable) {
2608 // All is the same, nothing to do. This relies on the fact that netd has child
2609 // chains default detached.
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002610 return;
2611 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002612 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002613 try {
2614 mNetworkManager.setFirewallChainEnabled(chain, enable);
2615 } catch (IllegalStateException e) {
2616 Log.wtf(TAG, "problem enable firewall chain", e);
2617 } catch (RemoteException e) {
2618 // ignored; service lives in system_server
2619 }
2620 }
2621
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002622 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2623 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002624 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002625 } catch (RuntimeException e) {
2626 Slog.w(TAG, "problem reading network stats: " + e);
2627 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002628 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002629 // ignored; service lives in system_server
2630 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002631 }
2632 }
2633
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002634 private boolean isBandwidthControlEnabled() {
2635 final long token = Binder.clearCallingIdentity();
2636 try {
2637 return mNetworkManager.isBandwidthControlEnabled();
2638 } catch (RemoteException e) {
2639 // ignored; service lives in system_server
2640 return false;
2641 } finally {
2642 Binder.restoreCallingIdentity(token);
2643 }
2644 }
2645
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002646 /**
2647 * Try refreshing {@link #mTime} when stale.
2648 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002649 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002650 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002651 mTime.forceRefresh();
2652 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002653 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002654
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002655 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002656 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2657 }
2658
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002659 private static Intent buildAllowBackgroundDataIntent() {
2660 return new Intent(ACTION_ALLOW_BACKGROUND);
2661 }
2662
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002663 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2664 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2665 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2666 return intent;
2667 }
2668
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002669 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2670 final Intent intent = new Intent();
2671 intent.setComponent(new ComponentName(
2672 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2673 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2674 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2675 return intent;
2676 }
2677
2678 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2679 final Intent intent = new Intent();
2680 intent.setComponent(new ComponentName(
2681 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2682 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2683 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2684 return intent;
2685 }
2686
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002687 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002688 public void addIdleHandler(IdleHandler handler) {
2689 mHandler.getLooper().getQueue().addIdleHandler(handler);
2690 }
2691
Jeff Sharkey1b861272011-05-22 00:34:52 -07002692 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2693 final int size = source.size();
2694 for (int i = 0; i < size; i++) {
2695 target.put(source.keyAt(i), true);
2696 }
2697 }
2698
Stuart Scottf1fb3972015-04-02 18:00:02 -07002699 @Override
2700 public void factoryReset(String subscriber) {
2701 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2702
Stuart Scotte3e314d2015-04-20 14:07:45 -07002703 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
2704 return;
2705 }
2706
Stuart Scottf1fb3972015-04-02 18:00:02 -07002707 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07002708 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07002709 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
2710 for (NetworkPolicy policy : policies) {
2711 if (policy.template.equals(template)) {
2712 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2713 policy.inferred = false;
2714 policy.clearSnooze();
2715 }
2716 }
2717 setNetworkPolicies(policies);
2718
2719 // Turn restrict background data off
2720 setRestrictBackground(false);
2721
Stuart Scotte3e314d2015-04-20 14:07:45 -07002722 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
2723 // Remove app's "restrict background data" flag
2724 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
2725 setUidPolicy(uid, POLICY_NONE);
2726 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07002727 }
2728 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002729}