blob: 47643006d4edb2ed1381e87e8a2897c204f5fac9 [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;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -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
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700206 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800207 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700208 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800209 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700210 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700211
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700212 private static final String TAG_POLICY_LIST = "policy-list";
213 private static final String TAG_NETWORK_POLICY = "network-policy";
214 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700215 private static final String TAG_APP_POLICY = "app-policy";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700216
217 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700218 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700219 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
220 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700221 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700222 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800223 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700224 private static final String ATTR_WARNING_BYTES = "warningBytes";
225 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700226 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800227 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
228 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800229 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700230 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700231 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700232 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700233 private static final String ATTR_POLICY = "policy";
234
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700235 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
236
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800237 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800238 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800239 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800240 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700241
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700242 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
243
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700244 private static final int MSG_RULES_CHANGED = 1;
245 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800246 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800247 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700248 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700249 private static final int MSG_SCREEN_ON_CHANGED = 8;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700250
Jeff Sharkey75279902011-05-24 18:39:45 -0700251 private final Context mContext;
252 private final IActivityManager mActivityManager;
253 private final IPowerManager mPowerManager;
254 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700255 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700256 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700257 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700258 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700259
260 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700261 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700262 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700263 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700264
Dianne Hackborn497175b2014-07-01 12:56:08 -0700265 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700266
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700267 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700268 volatile boolean mScreenOn;
269 volatile boolean mRestrictBackground;
270 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700271 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700272
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700273 private final boolean mSuppressDefaultPolicy;
274
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700275 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800276 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700277 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800278 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700279
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700280 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700281 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700282 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800283 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700284
Jeff Sharkeydc988062015-09-14 10:09:47 -0700285 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
286 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
287
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700288 /** Set of states for the child firewall chains. True if the chain is active. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700289 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
290
Jeff Sharkey32566012014-12-02 18:30:14 -0800291 /**
292 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700293 * in power save mode, except device idle (doze) still applies.
294 * TODO: An int array might be sufficient
295 */
296 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
297
298 /**
299 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800300 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700301 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800302 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700303 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700304
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700305 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
306
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700307 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800308 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700309 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800310 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700311
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700312 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700313 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700314
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700315 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800316 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700317
Jeff Sharkey32566012014-12-02 18:30:14 -0800318 private final RemoteCallbackList<INetworkPolicyListener>
319 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700320
Dianne Hackborn497175b2014-07-01 12:56:08 -0700321 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700322
323 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700324
Svet Ganov16a16892015-04-16 10:32:04 -0700325 private final AppOpsManager mAppOps;
326
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700327 // TODO: keep whitelist of system-critical services that should never have
328 // rules enforced, such as system, phone, and radio UIDs.
329
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700330 // TODO: migrate notifications to SystemUI
331
Jeff Sharkey75279902011-05-24 18:39:45 -0700332 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700333 IPowerManager powerManager, INetworkStatsService networkStats,
334 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700335 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700336 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700337 }
338
339 private static File getSystemDir() {
340 return new File(Environment.getDataDirectory(), "system");
341 }
342
343 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700344 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700345 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
346 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700347 mContext = checkNotNull(context, "missing context");
348 mActivityManager = checkNotNull(activityManager, "missing activityManager");
349 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700350 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700351 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700352 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700353 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700354 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700355 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700356
Amith Yamasani450a16b2013-09-18 16:28:50 -0700357 HandlerThread thread = new HandlerThread(TAG);
358 thread.start();
359 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700360
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700361 mSuppressDefaultPolicy = suppressDefaultPolicy;
362
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700363 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700364
365 mAppOps = context.getSystemService(AppOpsManager.class);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700366 }
367
368 public void bindConnectivityManager(IConnectivityManager connManager) {
369 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700370 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700371
Jeff Sharkey497e4432011-06-14 17:27:29 -0700372 public void bindNotificationManager(INotificationManager notifManager) {
373 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
374 }
375
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700376 void updatePowerSaveWhitelistLocked() {
377 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700378 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
379 mPowerSaveWhitelistExceptIdleAppIds.clear();
380 if (whitelist != null) {
381 for (int uid : whitelist) {
382 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
383 }
384 }
385 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700386 mPowerSaveWhitelistAppIds.clear();
387 if (whitelist != null) {
388 for (int uid : whitelist) {
389 mPowerSaveWhitelistAppIds.put(uid, true);
390 }
391 }
392 } catch (RemoteException e) {
393 }
394 }
395
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700396 void updatePowerSaveTempWhitelistLocked() {
397 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700398 // Clear the states of the current whitelist
399 final int N = mPowerSaveTempWhitelistAppIds.size();
400 for (int i = 0; i < N; i++) {
401 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
402 }
403 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700404 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700405 if (whitelist != null) {
406 for (int uid : whitelist) {
407 mPowerSaveTempWhitelistAppIds.put(uid, true);
408 }
409 }
410 } catch (RemoteException e) {
411 }
412 }
413
Amith Yamasani06f08062015-06-12 13:23:33 -0700414 /**
415 * Remove unnecessary entries in the temp whitelist
416 */
417 void purgePowerSaveTempWhitelistLocked() {
418 final int N = mPowerSaveTempWhitelistAppIds.size();
419 for (int i = N - 1; i >= 0; i--) {
420 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
421 mPowerSaveTempWhitelistAppIds.removeAt(i);
422 }
423 }
424 }
425
Jeff Sharkeya4620792011-05-20 15:29:23 -0700426 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700427 if (!isBandwidthControlEnabled()) {
428 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
429 return;
430 }
431
Amith Yamasani15e472352015-04-24 19:06:07 -0700432 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
433
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700434 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700435 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700436 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
437 mPowerManagerInternal.registerLowPowerModeObserver(
438 new PowerManagerInternal.LowPowerModeListener() {
439 @Override
440 public void onLowPowerModeChanged(boolean enabled) {
441 synchronized (mRulesLock) {
442 if (mRestrictPower != enabled) {
443 mRestrictPower = enabled;
444 updateRulesForGlobalChangeLocked(true);
445 }
446 }
447 }
448 });
449 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700450 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700451
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700452 // read policy from disk
453 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700454
Jeff Sharkeydc988062015-09-14 10:09:47 -0700455 updateRulesForGlobalChangeLocked(false);
456 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700457 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700458
Jeff Sharkeya4620792011-05-20 15:29:23 -0700459 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700460
Jeff Sharkeya4620792011-05-20 15:29:23 -0700461 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700462 mActivityManager.registerUidObserver(mUidObserver,
463 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700464 mNetworkManager.registerObserver(mAlertObserver);
465 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700466 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700467 }
468
Jeff Sharkeya4620792011-05-20 15:29:23 -0700469 // TODO: traverse existing processes to know foreground state, or have
470 // activitymanager dispatch current state when new observer attached.
471
472 final IntentFilter screenFilter = new IntentFilter();
473 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
474 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700475 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700476
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700477 // listen for changes to power save whitelist
478 final IntentFilter whitelistFilter = new IntentFilter(
479 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
480 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
481
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700482 DeviceIdleController.LocalService deviceIdleService
483 = LocalServices.getService(DeviceIdleController.LocalService.class);
484 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
485
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700486 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900487 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700488 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
489
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700490 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700491 final IntentFilter packageFilter = new IntentFilter();
492 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700493 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700494 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700495
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700496 // listen for UID changes to update policy
497 mContext.registerReceiver(
498 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
499
500 // listen for user changes to update policy
501 final IntentFilter userFilter = new IntentFilter();
502 userFilter.addAction(ACTION_USER_ADDED);
503 userFilter.addAction(ACTION_USER_REMOVED);
504 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
505
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700506 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700507 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
508 mContext.registerReceiver(
509 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
510
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700511 // listen for restrict background changes from notifications
512 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
513 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
514
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800515 // listen for snooze warning from notifications
516 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
517 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
518 MANAGE_NETWORK_POLICY, mHandler);
519
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700520 // listen for configured wifi networks to be removed
521 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700522 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700523
524 // listen for wifi state changes to catch metered hint
525 final IntentFilter wifiStateFilter = new IntentFilter(
526 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700527 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700528
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700529 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700530
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700531 }
532
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700533 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700534 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700535 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700536 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700537 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700538 }
539
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700540 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700541 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700542 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700543 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700544 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700545
546 @Override public void onUidActive(int uid) throws RemoteException {
547 }
548
549 @Override public void onUidIdle(int uid) throws RemoteException {
550 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700551 };
552
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700553 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700554 @Override
555 public void onReceive(Context context, Intent intent) {
556 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
557 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700558 updatePowerSaveWhitelistLocked();
559 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700560 }
561 }
562 };
563
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700564 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
565 @Override
566 public void run() {
567 synchronized (mRulesLock) {
568 updatePowerSaveTempWhitelistLocked();
569 updateRulesForTempWhitelistChangeLocked();
570 purgePowerSaveTempWhitelistLocked();
571 }
572 }
573 };
574
575 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700576 @Override
577 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800578 // screen-related broadcasts are protected by system, no need
579 // for permissions check.
580 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700581 }
582 };
583
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700584 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700585 @Override
586 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700587 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700588
589 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700590 final int uid = intent.getIntExtra(EXTRA_UID, -1);
591 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700592
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700593 if (ACTION_PACKAGE_ADDED.equals(action)) {
594 // update rules for UID, since it might be subject to
595 // global background data policy
596 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
597 synchronized (mRulesLock) {
598 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700599 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700600 }
601 }
602 };
603
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700604 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700605 @Override
606 public void onReceive(Context context, Intent intent) {
607 // on background handler thread, and UID_REMOVED is protected
608
609 final int uid = intent.getIntExtra(EXTRA_UID, -1);
610 if (uid == -1) return;
611
612 // remove any policy and update rules to clean up
613 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
614 synchronized (mRulesLock) {
615 mUidPolicy.delete(uid);
616 updateRulesForUidLocked(uid);
617 writePolicyLocked();
618 }
619 }
620 };
621
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700622 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700623 @Override
624 public void onReceive(Context context, Intent intent) {
625 // on background handler thread, and USER_ADDED and USER_REMOVED
626 // broadcasts are protected
627
628 final String action = intent.getAction();
629 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
630 if (userId == -1) return;
631
Amith Yamasani15e472352015-04-24 19:06:07 -0700632 switch (action) {
633 case ACTION_USER_REMOVED:
634 case ACTION_USER_ADDED:
635 synchronized (mRulesLock) {
636 // Remove any policies for given user; both cleaning up after a
637 // USER_REMOVED, and one last sanity check during USER_ADDED
638 removePoliciesForUserLocked(userId);
639 // Update global restrict for new user
640 updateRulesForGlobalChangeLocked(true);
641 }
642 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700643 }
644 }
645 };
646
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700647 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700648 * Receiver that watches for {@link INetworkStatsService} updates, which we
649 * use to check against {@link NetworkPolicy#warningBytes}.
650 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700651 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700652 @Override
653 public void onReceive(Context context, Intent intent) {
654 // on background handler thread, and verified
655 // READ_NETWORK_USAGE_HISTORY permission above.
656
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800657 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700658 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700659 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700660 updateNotificationsLocked();
661 }
662 }
663 };
664
665 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700666 * Receiver that watches for {@link Notification} control of
667 * {@link #mRestrictBackground}.
668 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700669 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700670 @Override
671 public void onReceive(Context context, Intent intent) {
672 // on background handler thread, and verified MANAGE_NETWORK_POLICY
673 // permission above.
674
675 setRestrictBackground(false);
676 }
677 };
678
679 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800680 * Receiver that watches for {@link Notification} control of
681 * {@link NetworkPolicy#lastWarningSnooze}.
682 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700683 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800684 @Override
685 public void onReceive(Context context, Intent intent) {
686 // on background handler thread, and verified MANAGE_NETWORK_POLICY
687 // permission above.
688
689 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
690 performSnooze(template, TYPE_WARNING);
691 }
692 };
693
694 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700695 * Receiver that watches for {@link WifiConfiguration} to be changed.
696 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700697 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700698 @Override
699 public void onReceive(Context context, Intent intent) {
700 // on background handler thread, and verified CONNECTIVITY_INTERNAL
701 // permission above.
702
703 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
704 if (reason == CHANGE_REASON_REMOVED) {
705 final WifiConfiguration config = intent.getParcelableExtra(
706 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700707 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800708 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700709 synchronized (mRulesLock) {
710 if (mNetworkPolicy.containsKey(template)) {
711 mNetworkPolicy.remove(template);
712 writePolicyLocked();
713 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700714 }
715 }
716 }
717 }
718 };
719
720 /**
721 * Receiver that watches {@link WifiInfo} state changes to infer metered
722 * state. Ignores hints when policy is user-defined.
723 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700724 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700725 @Override
726 public void onReceive(Context context, Intent intent) {
727 // on background handler thread, and verified CONNECTIVITY_INTERNAL
728 // permission above.
729
730 // ignore when not connected
731 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
732 if (!netInfo.isConnected()) return;
733
734 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
735 final boolean meteredHint = info.getMeteredHint();
736
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800737 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700738 synchronized (mRulesLock) {
739 NetworkPolicy policy = mNetworkPolicy.get(template);
740 if (policy == null && meteredHint) {
741 // policy doesn't exist, and AP is hinting that it's
742 // metered: create an inferred policy.
743 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
744 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
745 meteredHint, true);
746 addNetworkPolicyLocked(policy);
747
748 } else if (policy != null && policy.inferred) {
749 // policy exists, and was inferred: update its current
750 // metered state.
751 policy.metered = meteredHint;
752
753 // since this is inferred for each wifi session, just update
754 // rules without persisting.
755 updateNetworkRulesLocked();
756 }
757 }
758 }
759 };
760
761 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700762 * Observer that watches for {@link INetworkManagementService} alerts.
763 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700764 final private INetworkManagementEventObserver mAlertObserver
765 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700766 @Override
767 public void limitReached(String limitName, String iface) {
768 // only someone like NMS should be calling us
769 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
770
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800771 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
772 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700773 }
774 }
775 };
776
777 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700778 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
779 * to show visible notifications as needed.
780 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700781 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700782 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
783
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700784 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700785 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700786 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700787
788 // TODO: when switching to kernel notifications, compute next future
789 // cycle boundary to recompute notifications.
790
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700791 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800792 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700793 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
794 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700795 // ignore policies that aren't relevant to user
796 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700797 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700798
Jeff Sharkey497e4432011-06-14 17:27:29 -0700799 final long start = computeLastCycleBoundary(currentTime, policy);
800 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700801 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700802
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700803 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800804 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700805 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
806 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700807 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
808 notifyOverLimitLocked(policy.template);
809 }
810
Jeff Sharkey497e4432011-06-14 17:27:29 -0700811 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700812 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700813
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800814 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700815 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700816 }
817 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700818 }
819
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700820 // ongoing notification when restricting background data
821 if (mRestrictBackground) {
822 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700823 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700824
825 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700826 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
827 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700828 if (!mActiveNotifs.contains(tag)) {
829 cancelNotification(tag);
830 }
831 }
832 }
833
834 /**
835 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700836 * current device state, such as when
837 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
838 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700839 */
840 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800841 if (template.isMatchRuleMobile()) {
842 final TelephonyManager tele = TelephonyManager.from(mContext);
843 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700844
Jeff Sharkey32566012014-12-02 18:30:14 -0800845 // Mobile template is relevant when any active subscriber matches
846 final int[] subIds = sub.getActiveSubscriptionIdList();
847 for (int subId : subIds) {
848 final String subscriberId = tele.getSubscriberId(subId);
849 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
850 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
851 if (template.matches(probeIdent)) {
852 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700853 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800854 }
855 return false;
856 } else {
857 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700858 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700859 }
860
861 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700862 * Notify that given {@link NetworkTemplate} is over
863 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
864 */
865 private void notifyOverLimitLocked(NetworkTemplate template) {
866 if (!mOverLimitNotified.contains(template)) {
867 mContext.startActivity(buildNetworkOverLimitIntent(template));
868 mOverLimitNotified.add(template);
869 }
870 }
871
872 private void notifyUnderLimitLocked(NetworkTemplate template) {
873 mOverLimitNotified.remove(template);
874 }
875
876 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700877 * Build unique tag that identifies an active {@link NetworkPolicy}
878 * notification of a specific type, like {@link #TYPE_LIMIT}.
879 */
880 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700881 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700882 }
883
884 /**
885 * Show notification for combined {@link NetworkPolicy} and specific type,
886 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
887 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700888 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700889 final String tag = buildNotificationTag(policy, type);
890 final Notification.Builder builder = new Notification.Builder(mContext);
891 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800892 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700893 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200894 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700895
896 final Resources res = mContext.getResources();
897 switch (type) {
898 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700899 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700900 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700901
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700902 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700903 builder.setTicker(title);
904 builder.setContentTitle(title);
905 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700906
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800907 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
908 builder.setDeleteIntent(PendingIntent.getBroadcast(
909 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
910
911 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700912 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800913 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
914
Jeff Sharkey497e4432011-06-14 17:27:29 -0700915 break;
916 }
917 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700918 final CharSequence body = res.getText(R.string.data_usage_limit_body);
919
920 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -0400921 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700922 switch (policy.template.getMatchRule()) {
923 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700924 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700925 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700926 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700927 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700928 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700929 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700930 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700931 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700932 case MATCH_WIFI:
933 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -0400934 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700935 break;
936 default:
937 title = null;
938 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700939 }
940
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800941 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -0400942 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700943 builder.setTicker(title);
944 builder.setContentTitle(title);
945 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700946
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700947 final Intent intent = buildNetworkOverLimitIntent(policy.template);
948 builder.setContentIntent(PendingIntent.getActivity(
949 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
950 break;
951 }
952 case TYPE_LIMIT_SNOOZED: {
953 final long overBytes = totalBytes - policy.limitBytes;
954 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
955 Formatter.formatFileSize(mContext, overBytes));
956
957 final CharSequence title;
958 switch (policy.template.getMatchRule()) {
959 case MATCH_MOBILE_3G_LOWER:
960 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
961 break;
962 case MATCH_MOBILE_4G:
963 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
964 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700965 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700966 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
967 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700968 case MATCH_WIFI:
969 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
970 break;
971 default:
972 title = null;
973 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700974 }
975
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800976 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700977 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700978 builder.setTicker(title);
979 builder.setContentTitle(title);
980 builder.setContentText(body);
981
982 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700983 builder.setContentIntent(PendingIntent.getActivity(
984 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700985 break;
986 }
987 }
988
989 // TODO: move to NotificationManager once we can mock it
990 try {
991 final String packageName = mContext.getPackageName();
992 final int[] idReceived = new int[1];
993 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800994 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -0700995 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700996 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700997 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700998 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700999 }
1000 }
1001
1002 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001003 * Show ongoing notification to reflect that {@link #mRestrictBackground}
1004 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -07001005 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001006 private void enqueueRestrictedNotification(String tag) {
1007 final Resources res = mContext.getResources();
1008 final Notification.Builder builder = new Notification.Builder(mContext);
1009
1010 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
1011 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
1012
1013 builder.setOnlyAlertOnce(true);
1014 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001015 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001016 builder.setTicker(title);
1017 builder.setContentTitle(title);
1018 builder.setContentText(body);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001019 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001020 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001021
1022 final Intent intent = buildAllowBackgroundDataIntent();
1023 builder.setContentIntent(
1024 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001025
1026 // TODO: move to NotificationManager once we can mock it
1027 try {
1028 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001029 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001030 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001031 0x0, builder.getNotification(), idReceived, UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001032 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001033 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001034 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001035 }
1036 }
1037
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001038 private void cancelNotification(String tag) {
1039 // TODO: move to NotificationManager once we can mock it
1040 try {
1041 final String packageName = mContext.getPackageName();
1042 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001043 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001044 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001045 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001046 }
1047 }
1048
1049 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001050 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001051 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001052 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001053 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001054 @Override
1055 public void onReceive(Context context, Intent intent) {
1056 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1057 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001058
1059 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001060 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001061 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001062 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001063 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001064 updateNetworkRulesLocked();
1065 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001066 }
1067 }
1068 };
1069
1070 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001071 * Proactively control network data connections when they exceed
1072 * {@link NetworkPolicy#limitBytes}.
1073 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001074 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001075 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1076
1077 // TODO: reset any policy-disabled networks when any policy is removed
1078 // completely, which is currently rare case.
1079
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001080 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001081 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1082 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001083 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001084 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001085 setNetworkTemplateEnabled(policy.template, true);
1086 continue;
1087 }
1088
1089 final long start = computeLastCycleBoundary(currentTime, policy);
1090 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001091 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001092
1093 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001094 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1095 && policy.lastLimitSnooze < start;
1096 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001097
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001098 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001099 }
1100 }
1101
1102 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001103 * Proactively disable networks that match the given
1104 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001105 */
1106 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001107 // TODO: reach into ConnectivityManager to proactively disable bringing
1108 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001109 }
1110
1111 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001112 * Examine all connected {@link NetworkState}, looking for
1113 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1114 * remaining quota based on usage cycle and historical stats.
1115 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001116 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001117 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001118
1119 final NetworkState[] states;
1120 try {
1121 states = mConnManager.getAllNetworkState();
1122 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001123 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001124 return;
1125 }
1126
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001127 // If we are in restrict power mode, we want to treat all interfaces
1128 // as metered, to restrict access to the network by uid. However, we
1129 // will not have a bandwidth limit. Also only do this if restrict
1130 // background data use is *not* enabled, since that takes precendence
1131 // use over those networks can have a cost associated with it).
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001132 final boolean powerSave = mRestrictPower && !mRestrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001133
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001134 // First, generate identities of all connected networks so we can
1135 // quickly compare them against all defined policies below.
1136 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001137 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001138 for (NetworkState state : states) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001139 if (state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001140 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001141
1142 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001143 if (baseIface != null) {
1144 connIdents.add(Pair.create(baseIface, ident));
1145 if (powerSave) {
1146 connIfaces.add(baseIface);
1147 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001148 }
1149
1150 // Stacked interfaces are considered to have same identity as
1151 // their parent network.
1152 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1153 for (LinkProperties stackedLink : stackedLinks) {
1154 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001155 if (stackedIface != null) {
1156 connIdents.add(Pair.create(stackedIface, ident));
1157 if (powerSave) {
1158 connIfaces.add(stackedIface);
1159 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001160 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001161 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001162 }
1163 }
1164
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001165 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001166 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001167 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001168 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001169 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001170
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001171 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001172 for (int j = connIdents.size() - 1; j >= 0; j--) {
1173 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1174 if (policy.template.matches(ident.second)) {
1175 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001176 }
1177 }
1178
1179 if (ifaceList.size() > 0) {
1180 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001181 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001182 }
1183 }
1184
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001185 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001186 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001187
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001188 // apply each policy that we found ifaces for; compute remaining data
1189 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001190 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001191 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1192 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1193 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001194
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001195 final long start;
1196 final long totalBytes;
1197 if (policy.hasCycle()) {
1198 start = computeLastCycleBoundary(currentTime, policy);
1199 totalBytes = getTotalBytes(policy.template, start, currentTime);
1200 } else {
1201 start = Long.MAX_VALUE;
1202 totalBytes = 0;
1203 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001204
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001205 if (LOGD) {
1206 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001207 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001208 }
1209
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001210 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001211 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001212 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001213 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001214 if (!hasLimit) {
1215 // metered network, but no policy limit; we still need to
1216 // restrict apps, so push really high quota.
1217 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001218 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001219 // snoozing past quota, but we still need to restrict apps,
1220 // so push really high quota.
1221 quotaBytes = Long.MAX_VALUE;
1222 } else {
1223 // remaining "quota" bytes are based on total usage in
1224 // current cycle. kernel doesn't like 0-byte rules, so we
1225 // set 1-byte quota and disable the radio later.
1226 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1227 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001228
1229 if (ifaces.length > 1) {
1230 // TODO: switch to shared quota once NMS supports
1231 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001232 }
1233
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001234 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001235 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001236 setInterfaceQuota(iface, quotaBytes);
1237 newMeteredIfaces.add(iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001238 if (powerSave) {
1239 connIfaces.remove(iface);
1240 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001241 }
1242 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001243
1244 // keep track of lowest warning or limit of active policies
1245 if (hasWarning && policy.warningBytes < lowestRule) {
1246 lowestRule = policy.warningBytes;
1247 }
1248 if (hasLimit && policy.limitBytes < lowestRule) {
1249 lowestRule = policy.limitBytes;
1250 }
1251 }
1252
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001253 for (int i = connIfaces.size()-1; i >= 0; i--) {
1254 String iface = connIfaces.valueAt(i);
1255 removeInterfaceQuota(iface);
1256 setInterfaceQuota(iface, Long.MAX_VALUE);
1257 newMeteredIfaces.add(iface);
1258 }
1259
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001260 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001261
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001262 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001263 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1264 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001265 if (!newMeteredIfaces.contains(iface)) {
1266 removeInterfaceQuota(iface);
1267 }
1268 }
1269 mMeteredIfaces = newMeteredIfaces;
1270
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001271 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001272 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001273 }
1274
1275 /**
1276 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1277 * have at least a default mobile policy defined.
1278 */
1279 private void ensureActiveMobilePolicyLocked() {
1280 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001281 if (mSuppressDefaultPolicy) return;
1282
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001283 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001284 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001285
Jeff Sharkey32566012014-12-02 18:30:14 -08001286 final int[] subIds = sub.getActiveSubscriptionIdList();
1287 for (int subId : subIds) {
1288 final String subscriberId = tele.getSubscriberId(subId);
1289 ensureActiveMobilePolicyLocked(subscriberId);
1290 }
1291 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001292
Jeff Sharkey32566012014-12-02 18:30:14 -08001293 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1294 // Poke around to see if we already have a policy
1295 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1296 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1297 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1298 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1299 if (template.matches(probeIdent)) {
1300 if (LOGD) {
1301 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1302 + NetworkIdentity.scrubSubscriberId(subscriberId));
1303 }
1304 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001305 }
1306 }
1307
Jeff Sharkey32566012014-12-02 18:30:14 -08001308 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1309 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001310
Jeff Sharkey32566012014-12-02 18:30:14 -08001311 // Build default mobile policy, and assume usage cycle starts today
1312 final long warningBytes = mContext.getResources().getInteger(
1313 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001314
Jeff Sharkey32566012014-12-02 18:30:14 -08001315 final Time time = new Time();
1316 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001317
Jeff Sharkey32566012014-12-02 18:30:14 -08001318 final int cycleDay = time.monthDay;
1319 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001320
Jeff Sharkey32566012014-12-02 18:30:14 -08001321 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1322 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1323 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1324 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001325 }
1326
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001327 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001328 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001329
1330 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001331 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001332 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001333
1334 FileInputStream fis = null;
1335 try {
1336 fis = mPolicyFile.openRead();
1337 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001338 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001339
1340 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001341 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001342 while ((type = in.next()) != END_DOCUMENT) {
1343 final String tag = in.getName();
1344 if (type == START_TAG) {
1345 if (TAG_POLICY_LIST.equals(tag)) {
1346 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001347 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1348 mRestrictBackground = readBooleanAttribute(
1349 in, ATTR_RESTRICT_BACKGROUND);
1350 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001351 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001352 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001353
1354 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1355 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1356 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001357 final String networkId;
1358 if (version >= VERSION_ADDED_NETWORK_ID) {
1359 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1360 } else {
1361 networkId = null;
1362 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001363 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001364 final String cycleTimezone;
1365 if (version >= VERSION_ADDED_TIMEZONE) {
1366 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1367 } else {
1368 cycleTimezone = Time.TIMEZONE_UTC;
1369 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001370 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1371 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001372 final long lastLimitSnooze;
1373 if (version >= VERSION_SPLIT_SNOOZE) {
1374 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1375 } else if (version >= VERSION_ADDED_SNOOZE) {
1376 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001377 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001378 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001379 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001380 final boolean metered;
1381 if (version >= VERSION_ADDED_METERED) {
1382 metered = readBooleanAttribute(in, ATTR_METERED);
1383 } else {
1384 switch (networkTemplate) {
1385 case MATCH_MOBILE_3G_LOWER:
1386 case MATCH_MOBILE_4G:
1387 case MATCH_MOBILE_ALL:
1388 metered = true;
1389 break;
1390 default:
1391 metered = false;
1392 }
1393 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001394 final long lastWarningSnooze;
1395 if (version >= VERSION_SPLIT_SNOOZE) {
1396 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1397 } else {
1398 lastWarningSnooze = SNOOZE_NEVER;
1399 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001400 final boolean inferred;
1401 if (version >= VERSION_ADDED_INFERRED) {
1402 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1403 } else {
1404 inferred = false;
1405 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001406
Jeff Sharkey32566012014-12-02 18:30:14 -08001407 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1408 subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001409 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001410 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001411 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001412
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001413 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001414 final int uid = readIntAttribute(in, ATTR_UID);
1415 final int policy = readIntAttribute(in, ATTR_POLICY);
1416
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001417 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001418 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001419 } else {
1420 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1421 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001422 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001423 final int appId = readIntAttribute(in, ATTR_APP_ID);
1424 final int policy = readIntAttribute(in, ATTR_POLICY);
1425
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001426 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001427 // app policy is deprecated so this is only used in pre system user split.
1428 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001429 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001430 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001431 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001432 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001433 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001434 }
1435 }
1436 }
1437
1438 } catch (FileNotFoundException e) {
1439 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001440 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001441 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001442 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001443 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001444 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001445 } finally {
1446 IoUtils.closeQuietly(fis);
1447 }
1448 }
1449
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001450 /**
1451 * Upgrade legacy background data flags, notifying listeners of one last
1452 * change to always-true.
1453 */
1454 private void upgradeLegacyBackgroundData() {
1455 mRestrictBackground = Settings.Secure.getInt(
1456 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1457
1458 // kick off one last broadcast if restricted
1459 if (mRestrictBackground) {
1460 final Intent broadcast = new Intent(
1461 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001462 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001463 }
1464 }
1465
Dianne Hackborn497175b2014-07-01 12:56:08 -07001466 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001467 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001468
1469 FileOutputStream fos = null;
1470 try {
1471 fos = mPolicyFile.startWrite();
1472
1473 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001474 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001475 out.startDocument(null, true);
1476
1477 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001478 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001479 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001480
1481 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001482 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1483 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001484 final NetworkTemplate template = policy.template;
1485
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001486 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001487 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1488 final String subscriberId = template.getSubscriberId();
1489 if (subscriberId != null) {
1490 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001491 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001492 final String networkId = template.getNetworkId();
1493 if (networkId != null) {
1494 out.attribute(null, ATTR_NETWORK_ID, networkId);
1495 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001496 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001497 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001498 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1499 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001500 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1501 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001502 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001503 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001504 out.endTag(null, TAG_NETWORK_POLICY);
1505 }
1506
1507 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001508 for (int i = 0; i < mUidPolicy.size(); i++) {
1509 final int uid = mUidPolicy.keyAt(i);
1510 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001511
Jeff Sharkey497e4432011-06-14 17:27:29 -07001512 // skip writing empty policies
1513 if (policy == POLICY_NONE) continue;
1514
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001515 out.startTag(null, TAG_UID_POLICY);
1516 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001517 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001518 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001519 }
1520
1521 out.endTag(null, TAG_POLICY_LIST);
1522 out.endDocument();
1523
1524 mPolicyFile.finishWrite(fos);
1525 } catch (IOException e) {
1526 if (fos != null) {
1527 mPolicyFile.failWrite(fos);
1528 }
1529 }
1530 }
1531
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001532 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001533 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001534 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001535
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001536 if (!UserHandle.isApp(uid)) {
1537 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001538 }
1539
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001540 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001541 final long token = Binder.clearCallingIdentity();
1542 try {
1543 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1544 if (oldPolicy != policy) {
1545 setUidPolicyUncheckedLocked(uid, policy, true);
1546 }
1547 } finally {
1548 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001549 }
1550 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001551 }
1552
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001553 @Override
1554 public void addUidPolicy(int uid, int policy) {
1555 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001556
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001557 if (!UserHandle.isApp(uid)) {
1558 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1559 }
1560
1561 synchronized (mRulesLock) {
1562 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1563 policy |= oldPolicy;
1564 if (oldPolicy != policy) {
1565 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001566 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001567 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001568 }
1569
1570 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001571 public void removeUidPolicy(int uid, int policy) {
1572 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1573
1574 if (!UserHandle.isApp(uid)) {
1575 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1576 }
1577
1578 synchronized (mRulesLock) {
1579 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1580 policy = oldPolicy & ~policy;
1581 if (oldPolicy != policy) {
1582 setUidPolicyUncheckedLocked(uid, policy, true);
1583 }
1584 }
1585 }
1586
1587 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1588 mUidPolicy.put(uid, policy);
1589
1590 // uid policy changed, recompute rules and persist policy.
1591 updateRulesForUidLocked(uid);
1592 if (persist) {
1593 writePolicyLocked();
1594 }
1595 }
1596
1597 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001598 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001599 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1600
Jeff Sharkeya4620792011-05-20 15:29:23 -07001601 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001602 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001603 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001604 }
1605
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001606 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001607 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001608 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1609
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001610 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001611 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001612 for (int i = 0; i < mUidPolicy.size(); i++) {
1613 final int uid = mUidPolicy.keyAt(i);
1614 final int uidPolicy = mUidPolicy.valueAt(i);
1615 if (uidPolicy == policy) {
1616 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001617 }
1618 }
1619 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001620 return uids;
1621 }
1622
1623 /**
1624 * Remove any policies associated with given {@link UserHandle}, persisting
1625 * if any changes are made.
1626 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001627 void removePoliciesForUserLocked(int userId) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001628 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1629
1630 int[] uids = new int[0];
1631 for (int i = 0; i < mUidPolicy.size(); i++) {
1632 final int uid = mUidPolicy.keyAt(i);
1633 if (UserHandle.getUserId(uid) == userId) {
1634 uids = appendInt(uids, uid);
1635 }
1636 }
1637
1638 if (uids.length > 0) {
1639 for (int uid : uids) {
1640 mUidPolicy.delete(uid);
1641 updateRulesForUidLocked(uid);
1642 }
1643 writePolicyLocked();
1644 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001645 }
1646
1647 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001648 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001649 // TODO: create permission for observing network policy
1650 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1651
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001652 mListeners.register(listener);
1653
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001654 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001655 }
1656
1657 @Override
1658 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001659 // TODO: create permission for observing network policy
1660 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1661
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001662 mListeners.unregister(listener);
1663 }
1664
Jeff Sharkey1b861272011-05-22 00:34:52 -07001665 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001666 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001667 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1668
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001669 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001670 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001671 normalizePoliciesLocked(policies);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001672 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001673 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001674 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001675 writePolicyLocked();
1676 }
1677 }
1678
Dianne Hackborn497175b2014-07-01 12:56:08 -07001679 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001680 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001681 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1682 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001683 }
1684
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001685 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001686 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001687 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001688 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001689 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1690 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1691 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001692 } catch (SecurityException e) {
1693 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001694
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001695 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1696 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1697 return new NetworkPolicy[0];
1698 }
Svet Ganov16a16892015-04-16 10:32:04 -07001699 }
1700
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001701 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001702 final int size = mNetworkPolicy.size();
1703 final NetworkPolicy[] policies = new NetworkPolicy[size];
1704 for (int i = 0; i < size; i++) {
1705 policies[i] = mNetworkPolicy.valueAt(i);
1706 }
1707 return policies;
1708 }
1709 }
1710
1711 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001712 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001713 }
1714
1715 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1716 final TelephonyManager tele = TelephonyManager.from(mContext);
1717 final String[] merged = tele.getMergedSubscriberIds();
1718
1719 mNetworkPolicy.clear();
1720 for (NetworkPolicy policy : policies) {
1721 // When two normalized templates conflict, prefer the most
1722 // restrictive policy
1723 policy.template = NetworkTemplate.normalize(policy.template, merged);
1724 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1725 if (existing == null || existing.compareTo(policy) > 0) {
1726 if (existing != null) {
1727 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1728 }
1729 mNetworkPolicy.put(policy.template, policy);
1730 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001731 }
1732 }
1733
1734 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001735 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001736 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001737
1738 final long token = Binder.clearCallingIdentity();
1739 try {
1740 performSnooze(template, TYPE_LIMIT);
1741 } finally {
1742 Binder.restoreCallingIdentity(token);
1743 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001744 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001745
Dianne Hackborn497175b2014-07-01 12:56:08 -07001746 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001747 maybeRefreshTrustedTime();
1748 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001749 synchronized (mRulesLock) {
1750 // find and snooze local policy that matches
1751 final NetworkPolicy policy = mNetworkPolicy.get(template);
1752 if (policy == null) {
1753 throw new IllegalArgumentException("unable to find policy for " + template);
1754 }
1755
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001756 switch (type) {
1757 case TYPE_WARNING:
1758 policy.lastWarningSnooze = currentTime;
1759 break;
1760 case TYPE_LIMIT:
1761 policy.lastLimitSnooze = currentTime;
1762 break;
1763 default:
1764 throw new IllegalArgumentException("unexpected type");
1765 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001766
Jeff Sharkey32566012014-12-02 18:30:14 -08001767 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001768 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001769 updateNetworkRulesLocked();
1770 updateNotificationsLocked();
1771 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001772 }
1773 }
1774
1775 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001776 public void setRestrictBackground(boolean restrictBackground) {
1777 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1778
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001779 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001780 synchronized (mRulesLock) {
1781 mRestrictBackground = restrictBackground;
Jeff Sharkey9d142062015-08-12 16:46:05 -07001782 updateRulesForGlobalChangeLocked(true);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001783 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001784 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001785 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001786
1787 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1788 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001789 }
1790
1791 @Override
1792 public boolean getRestrictBackground() {
1793 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1794
1795 synchronized (mRulesLock) {
1796 return mRestrictBackground;
1797 }
1798 }
1799
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001800 @Override
1801 public void setDeviceIdleMode(boolean enabled) {
1802 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1803
1804 synchronized (mRulesLock) {
1805 if (mDeviceIdleMode != enabled) {
1806 mDeviceIdleMode = enabled;
1807 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07001808 // Device idle change means we need to rebuild rules for all
1809 // known apps, so do a global refresh.
1810 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001811 }
1812 if (enabled) {
1813 EventLogTags.writeDeviceIdleOnPhase("net");
1814 } else {
1815 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001816 }
1817 }
1818 }
1819 }
1820
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001821 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001822 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1823 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001824 if (policy.template.matches(ident)) {
1825 return policy;
1826 }
1827 }
1828 return null;
1829 }
1830
1831 @Override
1832 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1833 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1834
1835 // only returns usage summary, so we don't require caller to have
1836 // READ_NETWORK_USAGE_HISTORY.
1837 final long token = Binder.clearCallingIdentity();
1838 try {
1839 return getNetworkQuotaInfoUnchecked(state);
1840 } finally {
1841 Binder.restoreCallingIdentity(token);
1842 }
1843 }
1844
1845 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1846 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1847
1848 final NetworkPolicy policy;
1849 synchronized (mRulesLock) {
1850 policy = findPolicyForNetworkLocked(ident);
1851 }
1852
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001853 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001854 // missing policy means we can't derive useful quota info
1855 return null;
1856 }
1857
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001858 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001859
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001860 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001861 final long start = computeLastCycleBoundary(currentTime, policy);
1862 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001863 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001864
1865 // report soft and hard limits under policy
1866 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1867 : NetworkQuotaInfo.NO_LIMIT;
1868 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1869 : NetworkQuotaInfo.NO_LIMIT;
1870
1871 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1872 }
1873
Jeff Sharkey46645002011-07-27 21:11:21 -07001874 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001875 public boolean isNetworkMetered(NetworkState state) {
1876 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1877
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001878 // roaming networks are always considered metered
1879 if (ident.getRoaming()) {
1880 return true;
1881 }
1882
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001883 final NetworkPolicy policy;
1884 synchronized (mRulesLock) {
1885 policy = findPolicyForNetworkLocked(ident);
1886 }
1887
1888 if (policy != null) {
1889 return policy.metered;
1890 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001891 final int type = state.networkInfo.getType();
1892 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1893 return true;
1894 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001895 return false;
1896 }
1897 }
1898
1899 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001900 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001901 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001902
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001903 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1904
Dianne Hackborn497175b2014-07-01 12:56:08 -07001905 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001906 for (String arg : args) {
1907 argSet.add(arg);
1908 }
1909
Jeff Sharkey1b861272011-05-22 00:34:52 -07001910 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001911 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001912 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1913 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001914 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001915
Jeff Sharkey32566012014-12-02 18:30:14 -08001916 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001917 updateNetworkEnabledLocked();
1918 updateNetworkRulesLocked();
1919 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001920 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001921
1922 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001923 return;
1924 }
1925
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001926 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07001927 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001928 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001929 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001930 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001931 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001932 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1933 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001934 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001935 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001936
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001937 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
1938
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001939 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001940 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001941 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001942 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001943 final int uid = mUidPolicy.keyAt(i);
1944 final int policy = mUidPolicy.valueAt(i);
1945 fout.print("UID=");
1946 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001947 fout.print(" policy=");
Jeff Sharkeydc988062015-09-14 10:09:47 -07001948 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001949 fout.println();
1950 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001951 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001952
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001953 size = mPowerSaveWhitelistExceptIdleAppIds.size();
1954 if (size > 0) {
1955 fout.println("Power save whitelist (except idle) app ids:");
1956 fout.increaseIndent();
1957 for (int i = 0; i < size; i++) {
1958 fout.print("UID=");
1959 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
1960 fout.print(": ");
1961 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
1962 fout.println();
1963 }
1964 fout.decreaseIndent();
1965 }
1966
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001967 size = mPowerSaveWhitelistAppIds.size();
1968 if (size > 0) {
1969 fout.println("Power save whitelist app ids:");
1970 fout.increaseIndent();
1971 for (int i = 0; i < size; i++) {
1972 fout.print("UID=");
1973 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
1974 fout.print(": ");
1975 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
1976 fout.println();
1977 }
1978 fout.decreaseIndent();
1979 }
1980
Jeff Sharkey1b861272011-05-22 00:34:52 -07001981 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07001982 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001983 collectKeys(mUidRules, knownUids);
1984
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001985 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001986 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001987 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001988 for (int i = 0; i < size; i++) {
1989 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001990 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001991 fout.print(uid);
1992
Jeff Sharkeydc988062015-09-14 10:09:47 -07001993 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001994 fout.print(" state=");
1995 fout.print(state);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001996 fout.print(state <= ActivityManager.PROCESS_STATE_TOP ? " (fg)" : " (bg)");
Dianne Hackborn497175b2014-07-01 12:56:08 -07001997
Jeff Sharkeydc988062015-09-14 10:09:47 -07001998 final int rule = mUidRules.get(uid, RULE_UNKNOWN);
1999 fout.print(" rule=");
2000 fout.print(DebugUtils.valueToString(NetworkPolicyManager.class, "RULE_", rule));
Jeff Sharkey1b861272011-05-22 00:34:52 -07002001
2002 fout.println();
2003 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002004 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002005 }
2006 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002007
2008 @Override
2009 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002010 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2011
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002012 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002013 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002014 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002015 }
2016
Dianne Hackborn497175b2014-07-01 12:56:08 -07002017 boolean isUidForegroundLocked(int uid) {
2018 // only really in foreground when screen is also on
2019 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002020 <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002021 }
2022
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002023 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002024 * Process state of UID changed; if needed, will trigger
2025 * {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002026 */
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002027 void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002028 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2029 if (oldUidState != uidState) {
2030 // state changed, push updated rules
2031 mUidState.put(uid, uidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002032 updateRulesForUidStateChangeLocked(uid, oldUidState, uidState);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002033 if (mDeviceIdleMode && isProcStateAllowedWhileIdle(oldUidState)
2034 != isProcStateAllowedWhileIdle(uidState)) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002035 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002036 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002037 }
2038 }
2039
2040 void removeUidStateLocked(int uid) {
2041 final int index = mUidState.indexOfKey(uid);
2042 if (index >= 0) {
2043 final int oldUidState = mUidState.valueAt(index);
2044 mUidState.removeAt(index);
2045 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
2046 updateRulesForUidStateChangeLocked(uid, oldUidState,
2047 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002048 if (mDeviceIdleMode) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002049 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002050 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002051 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002052 }
2053 }
2054
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002055 void updateRulesForUidStateChangeLocked(int uid, int oldUidState, int newUidState) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002056 final boolean oldForeground = oldUidState <= ActivityManager.PROCESS_STATE_TOP;
2057 final boolean newForeground = newUidState <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002058 if (oldForeground != newForeground) {
2059 updateRulesForUidLocked(uid);
2060 }
2061 }
2062
Jeff Sharkeya4620792011-05-20 15:29:23 -07002063 private void updateScreenOn() {
2064 synchronized (mRulesLock) {
2065 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002066 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002067 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002068 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002069 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002070 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002071 }
2072 }
2073
2074 /**
2075 * Update rules that might be changed by {@link #mScreenOn} value.
2076 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002077 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002078 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002079 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002080 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002081 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002082 final int uid = mUidState.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002083 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002084 }
2085 }
2086 }
2087
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002088 static boolean isProcStateAllowedWhileIdle(int procState) {
2089 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2090 }
2091
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002092 void updateRulesForDeviceIdleLocked() {
2093 if (mDeviceIdleMode) {
2094 // sync the whitelists before enable dozable chain. We don't care about the rules if
2095 // we are disabling the chain.
Jeff Sharkeydc988062015-09-14 10:09:47 -07002096 final SparseIntArray uidRules = mUidFirewallDozableRules;
2097 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002098 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002099 for (int ui = users.size() - 1; ui >= 0; ui--) {
2100 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002101 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002102 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2103 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2104 int uid = UserHandle.getUid(user.id, appId);
2105 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2106 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002107 }
2108 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2109 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2110 int uid = UserHandle.getUid(user.id, appId);
2111 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2112 }
2113 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002114 for (int i = mUidState.size() - 1; i >= 0; i--) {
2115 if (isProcStateAllowedWhileIdle(mUidState.valueAt(i))) {
2116 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2117 }
2118 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002119 setUidFirewallRules(FIREWALL_CHAIN_DOZABLE, uidRules);
2120 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002121
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002122 enableFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, mDeviceIdleMode);
2123 }
2124
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002125 void updateRuleForDeviceIdleLocked(int uid) {
2126 if (mDeviceIdleMode) {
2127 int appId = UserHandle.getAppId(uid);
2128 if (mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId)
2129 || isProcStateAllowedWhileIdle(mUidState.get(uid))) {
2130 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_ALLOW);
2131 } else {
2132 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
2133 }
2134 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002135
2136 updateRulesForUidLocked(uid);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002137 }
2138
2139 void updateRulesForAppIdleLocked() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002140 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2141 uidRules.clear();
2142
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002143 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002144 final List<UserInfo> users = mUserManager.getUsers();
2145 for (int ui = users.size() - 1; ui >= 0; ui--) {
2146 UserInfo user = users.get(ui);
2147 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2148 for (int uid : idleUids) {
2149 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2150 uidRules.put(uid, FIREWALL_RULE_DENY);
2151 }
2152 }
2153 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002154
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002155 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2156 }
2157
2158 void updateRuleForAppIdleLocked(int uid) {
2159 if (!isUidValidForRules(uid)) return;
2160
2161 int appId = UserHandle.getAppId(uid);
2162 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)) {
2163 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2164 } else {
2165 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2166 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002167
2168 updateRulesForUidLocked(uid);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002169 }
2170
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002171 void updateRulesForAppIdleParoleLocked() {
2172 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2173 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Jeff Sharkeydc988062015-09-14 10:09:47 -07002174 updateRulesForUidsLocked(mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002175 }
2176
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002177 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002178 * Update rules that might be changed by {@link #mRestrictBackground},
2179 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002180 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002181 void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002182 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002183
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002184 updateRulesForDeviceIdleLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002185 updateRulesForAppIdleLocked();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002186
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002187 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002188 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002189 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey2a9e3f82015-12-18 10:57:58 -07002190 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS
2191 | PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002192
2193 for (UserInfo user : users) {
2194 for (ApplicationInfo app : apps) {
2195 final int uid = UserHandle.getUid(user.id, app.uid);
2196 updateRulesForUidLocked(uid);
2197 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002198 }
2199
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002200 // limit data usage for some internal system services
2201 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
2202 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002203
2204 // If the set of restricted networks may have changed, re-evaluate those.
2205 if (restrictedNetworksChanged) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002206 normalizePoliciesLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002207 updateNetworkRulesLocked();
2208 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002209 }
2210
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002211 void updateRulesForTempWhitelistChangeLocked() {
2212 final List<UserInfo> users = mUserManager.getUsers();
2213 for (UserInfo user : users) {
2214 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
2215 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2216 int uid = UserHandle.getUid(user.id, appId);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002217 updateRuleForAppIdleLocked(uid);
2218 updateRuleForDeviceIdleLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002219 }
2220 }
2221 }
2222
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002223 private static boolean isUidValidForRules(int uid) {
2224 // allow rules on specific system services, and any apps
2225 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002226 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002227 return true;
2228 }
2229
2230 return false;
2231 }
2232
Amith Yamasani15e472352015-04-24 19:06:07 -07002233 private boolean isUidIdle(int uid) {
2234 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2235 final int userId = UserHandle.getUserId(uid);
2236
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002237 if (!ArrayUtils.isEmpty(packages)) {
2238 for (String packageName : packages) {
2239 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2240 return false;
2241 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002242 }
2243 }
2244 return true;
2245 }
2246
Jeff Sharkeydc988062015-09-14 10:09:47 -07002247 void updateRulesForUidsLocked(SparseIntArray uids) {
2248 for (int i = 0; i < uids.size(); i++) {
2249 updateRulesForUidLocked(uids.keyAt(i));
2250 }
2251 }
2252
Amith Yamasani15e472352015-04-24 19:06:07 -07002253 /**
2254 * Applies network rules to bandwidth and firewall controllers based on uid policy.
2255 * @param uid The uid for which to apply the latest policy
2256 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002257 void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002258 if (!isUidValidForRules(uid)) return;
2259
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002260 // quick check: if this uid doesn't have INTERNET permission, it doesn't have
2261 // network access anyway, so it is a waste to mess with it here.
2262 final IPackageManager ipm = AppGlobals.getPackageManager();
2263 try {
2264 if (ipm.checkUidPermission(Manifest.permission.INTERNET, uid)
2265 != PackageManager.PERMISSION_GRANTED) {
2266 return;
2267 }
2268 } catch (RemoteException e) {
2269 }
2270
Dianne Hackborn497175b2014-07-01 12:56:08 -07002271 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2272 final boolean uidForeground = isUidForegroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002273
Jeff Sharkeydc988062015-09-14 10:09:47 -07002274 // Derive active rules based on policy and active state
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002275 int appId = UserHandle.getAppId(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002276 int uidRules = RULE_ALLOW_ALL;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002277 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002278 // uid in background, and policy says to block metered data
2279 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002280 } else if (mRestrictBackground) {
2281 if (!uidForeground) {
2282 // uid in background, and global background disabled
2283 uidRules = RULE_REJECT_METERED;
2284 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002285 } else if (mRestrictPower) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002286 final boolean whitelisted = mPowerSaveWhitelistExceptIdleAppIds.get(appId)
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002287 || mPowerSaveTempWhitelistAppIds.get(appId);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002288 if (!whitelisted && !uidForeground
2289 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
2290 // uid is in background, restrict power use mode is on (so we want to
2291 // restrict all background network access), and this uid is not on the
2292 // white list of those allowed background access.
2293 uidRules = RULE_REJECT_METERED;
2294 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002295 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002296
Jeff Sharkeydc988062015-09-14 10:09:47 -07002297 // Check dozable state, which is whitelist
2298 if (mFirewallChainStates.get(FIREWALL_CHAIN_DOZABLE)
2299 && mUidFirewallDozableRules.get(uid, FIREWALL_RULE_DEFAULT) != FIREWALL_RULE_ALLOW) {
2300 uidRules = RULE_REJECT_ALL;
2301 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002302
Jeff Sharkeydc988062015-09-14 10:09:47 -07002303 // Check standby state, which is blacklist
2304 if (mFirewallChainStates.get(FIREWALL_CHAIN_STANDBY)
2305 && mUidFirewallStandbyRules.get(uid, FIREWALL_RULE_DEFAULT) == FIREWALL_RULE_DENY) {
2306 uidRules = RULE_REJECT_ALL;
2307 }
2308
2309 final int oldRules = mUidRules.get(uid);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002310 if (uidRules == RULE_ALLOW_ALL) {
2311 mUidRules.delete(uid);
2312 } else {
2313 mUidRules.put(uid, uidRules);
2314 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002315
Jeff Sharkeydc988062015-09-14 10:09:47 -07002316 final boolean rejectMetered = (uidRules == RULE_REJECT_METERED);
2317 setUidNetworkRules(uid, rejectMetered);
Amith Yamasani15e472352015-04-24 19:06:07 -07002318
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002319 // dispatch changed rule to existing listeners
Amith Yamasani15e472352015-04-24 19:06:07 -07002320 if (oldRules != uidRules) {
2321 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
2322 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002323
2324 try {
2325 // adjust stats accounting based on foreground status
2326 mNetworkStats.setUidForeground(uid, uidForeground);
2327 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002328 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002329 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002330 }
2331
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002332 private class AppIdleStateChangeListener
2333 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2334
2335 @Override
2336 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2337 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002338 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
2339 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002340 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002341 updateRuleForAppIdleLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002342 }
2343 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002344 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002345 }
2346
2347 @Override
2348 public void onParoleStateChanged(boolean isParoleOn) {
2349 synchronized (mRulesLock) {
2350 updateRulesForAppIdleParoleLocked();
2351 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002352 }
2353 }
2354
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002355 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002356 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002357 public boolean handleMessage(Message msg) {
2358 switch (msg.what) {
2359 case MSG_RULES_CHANGED: {
2360 final int uid = msg.arg1;
2361 final int uidRules = msg.arg2;
2362 final int length = mListeners.beginBroadcast();
2363 for (int i = 0; i < length; i++) {
2364 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2365 if (listener != null) {
2366 try {
2367 listener.onUidRulesChanged(uid, uidRules);
2368 } catch (RemoteException e) {
2369 }
2370 }
2371 }
2372 mListeners.finishBroadcast();
2373 return true;
2374 }
2375 case MSG_METERED_IFACES_CHANGED: {
2376 final String[] meteredIfaces = (String[]) msg.obj;
2377 final int length = mListeners.beginBroadcast();
2378 for (int i = 0; i < length; i++) {
2379 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2380 if (listener != null) {
2381 try {
2382 listener.onMeteredIfacesChanged(meteredIfaces);
2383 } catch (RemoteException e) {
2384 }
2385 }
2386 }
2387 mListeners.finishBroadcast();
2388 return true;
2389 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002390 case MSG_LIMIT_REACHED: {
2391 final String iface = (String) msg.obj;
2392
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002393 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002394 synchronized (mRulesLock) {
2395 if (mMeteredIfaces.contains(iface)) {
2396 try {
2397 // force stats update to make sure we have
2398 // numbers that caused alert to trigger.
2399 mNetworkStats.forceUpdate();
2400 } catch (RemoteException e) {
2401 // ignored; service lives in system_server
2402 }
2403
2404 updateNetworkEnabledLocked();
2405 updateNotificationsLocked();
2406 }
2407 }
2408 return true;
2409 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002410 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2411 final boolean restrictBackground = msg.arg1 != 0;
2412 final int length = mListeners.beginBroadcast();
2413 for (int i = 0; i < length; i++) {
2414 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2415 if (listener != null) {
2416 try {
2417 listener.onRestrictBackgroundChanged(restrictBackground);
2418 } catch (RemoteException e) {
2419 }
2420 }
2421 }
2422 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002423 return true;
2424 }
2425 case MSG_ADVISE_PERSIST_THRESHOLD: {
2426 final long lowestRule = (Long) msg.obj;
2427 try {
2428 // make sure stats are recorded frequently enough; we aim
2429 // for 2MB threshold for 2GB/month rules.
2430 final long persistThreshold = lowestRule / 1000;
2431 mNetworkStats.advisePersistThreshold(persistThreshold);
2432 } catch (RemoteException e) {
2433 // ignored; service lives in system_server
2434 }
2435 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002436 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002437 case MSG_SCREEN_ON_CHANGED: {
2438 updateScreenOn();
2439 return true;
2440 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002441 default: {
2442 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002443 }
2444 }
2445 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002446 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002447
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002448 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002449 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002450 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002451 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002452 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002453 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002454 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002455 }
2456 }
2457
2458 private void removeInterfaceQuota(String iface) {
2459 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002460 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002461 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002462 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002463 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002464 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002465 }
2466 }
2467
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002468 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2469 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002470 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002471 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002472 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002473 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002474 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002475 }
2476 }
2477
Amith Yamasani15e472352015-04-24 19:06:07 -07002478 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002479 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
2480 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
2481 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07002482 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002483 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002484 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002485 int size = uidRules.size();
2486 int[] uids = new int[size];
2487 int[] rules = new int[size];
2488 for(int index = size - 1; index >= 0; --index) {
2489 uids[index] = uidRules.keyAt(index);
2490 rules[index] = uidRules.valueAt(index);
2491 }
2492 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002493 } catch (IllegalStateException e) {
2494 Log.wtf(TAG, "problem setting firewall uid rules", e);
2495 } catch (RemoteException e) {
2496 // ignored; service lives in system_server
2497 }
2498 }
2499
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002500 /**
2501 * Add or remove a uid to the firewall blacklist for all network ifaces.
2502 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002503 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002504 if (chain == FIREWALL_CHAIN_DOZABLE) {
2505 mUidFirewallDozableRules.put(uid, rule);
2506 } else if (chain == FIREWALL_CHAIN_STANDBY) {
2507 mUidFirewallStandbyRules.put(uid, rule);
2508 }
2509
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002510 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002511 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002512 } catch (IllegalStateException e) {
2513 Log.wtf(TAG, "problem setting firewall uid rules", e);
2514 } catch (RemoteException e) {
2515 // ignored; service lives in system_server
2516 }
2517 }
2518
2519 /**
2520 * Add or remove a uid to the firewall blacklist for all network ifaces.
2521 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002522 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002523 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
2524 mFirewallChainStates.get(chain) == enable) {
2525 // All is the same, nothing to do.
2526 return;
2527 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002528 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002529 try {
2530 mNetworkManager.setFirewallChainEnabled(chain, enable);
2531 } catch (IllegalStateException e) {
2532 Log.wtf(TAG, "problem enable firewall chain", e);
2533 } catch (RemoteException e) {
2534 // ignored; service lives in system_server
2535 }
2536 }
2537
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002538 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2539 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002540 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002541 } catch (RuntimeException e) {
2542 Slog.w(TAG, "problem reading network stats: " + e);
2543 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002544 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002545 // ignored; service lives in system_server
2546 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002547 }
2548 }
2549
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002550 private boolean isBandwidthControlEnabled() {
2551 final long token = Binder.clearCallingIdentity();
2552 try {
2553 return mNetworkManager.isBandwidthControlEnabled();
2554 } catch (RemoteException e) {
2555 // ignored; service lives in system_server
2556 return false;
2557 } finally {
2558 Binder.restoreCallingIdentity(token);
2559 }
2560 }
2561
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002562 /**
2563 * Try refreshing {@link #mTime} when stale.
2564 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002565 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002566 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002567 mTime.forceRefresh();
2568 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002569 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002570
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002571 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002572 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2573 }
2574
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002575 private static Intent buildAllowBackgroundDataIntent() {
2576 return new Intent(ACTION_ALLOW_BACKGROUND);
2577 }
2578
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002579 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2580 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2581 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2582 return intent;
2583 }
2584
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002585 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2586 final Intent intent = new Intent();
2587 intent.setComponent(new ComponentName(
2588 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2589 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2590 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2591 return intent;
2592 }
2593
2594 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2595 final Intent intent = new Intent();
2596 intent.setComponent(new ComponentName(
2597 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2598 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2599 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2600 return intent;
2601 }
2602
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002603 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002604 public void addIdleHandler(IdleHandler handler) {
2605 mHandler.getLooper().getQueue().addIdleHandler(handler);
2606 }
2607
Jeff Sharkey1b861272011-05-22 00:34:52 -07002608 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2609 final int size = source.size();
2610 for (int i = 0; i < size; i++) {
2611 target.put(source.keyAt(i), true);
2612 }
2613 }
2614
Stuart Scottf1fb3972015-04-02 18:00:02 -07002615 @Override
2616 public void factoryReset(String subscriber) {
2617 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2618
Stuart Scotte3e314d2015-04-20 14:07:45 -07002619 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
2620 return;
2621 }
2622
Stuart Scottf1fb3972015-04-02 18:00:02 -07002623 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07002624 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07002625 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
2626 for (NetworkPolicy policy : policies) {
2627 if (policy.template.equals(template)) {
2628 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2629 policy.inferred = false;
2630 policy.clearSnooze();
2631 }
2632 }
2633 setNetworkPolicies(policies);
2634
2635 // Turn restrict background data off
2636 setRestrictBackground(false);
2637
Stuart Scotte3e314d2015-04-20 14:07:45 -07002638 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
2639 // Remove app's "restrict background data" flag
2640 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
2641 setUidPolicy(uid, POLICY_NONE);
2642 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07002643 }
2644 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002645}