blob: cd982d32d45d842d93a8f8b54c0b9d09e7b9eed9 [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;
Amith Yamasani15e472352015-04-24 19:06:07 -070043import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -070044import static android.net.NetworkPolicyManager.POLICY_ALLOW_BACKGROUND_BATTERY_SAVE;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070045import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070046import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070047import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070048import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Amith Yamasani15e472352015-04-24 19:06:07 -070049import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070050import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Jeff Sharkey1b861272011-05-22 00:34:52 -070051import static android.net.NetworkPolicyManager.dumpPolicy;
52import static android.net.NetworkPolicyManager.dumpRules;
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 Sharkeyf0ceede2011-08-02 17:22:34 -0700111import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700112import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700113import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700114import android.net.wifi.WifiConfiguration;
115import android.net.wifi.WifiInfo;
116import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700117import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700118import android.os.Environment;
119import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700120import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700121import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700122import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700123import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700124import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700125import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700126import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700127import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700128import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700129import android.os.RemoteException;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700130import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700131import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700132import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700133import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800134import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700135import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700136import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700137import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700138import android.util.ArrayMap;
139import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700140import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700141import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700142import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700143import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700144import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700145import android.util.SparseBooleanArray;
146import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700147import android.util.TrustedTime;
148import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700149
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700150import com.android.server.DeviceIdleController;
Dianne Hackborn3b16cf42015-07-01 15:05:04 -0700151import com.android.server.EventLogTags;
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;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700159import com.android.server.LocalServices;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700160import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700161
162import org.xmlpull.v1.XmlPullParser;
163import org.xmlpull.v1.XmlPullParserException;
164import org.xmlpull.v1.XmlSerializer;
165
166import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700167import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700168import java.io.FileInputStream;
169import java.io.FileNotFoundException;
170import java.io.FileOutputStream;
171import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700172import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100173import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700174import java.util.ArrayList;
175import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700176import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700177
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700178/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700179 * Service that maintains low-level network policy rules, using
180 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700181 * <p>
182 * Derives active rules by combining a given policy with other system status,
183 * and delivers to listeners, such as {@link ConnectivityManager}, for
184 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700185 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700186public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700187 private static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700188 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700189 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700190
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700191 private static final int VERSION_INIT = 1;
192 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700193 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800194 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800195 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800196 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700197 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700198 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700199 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700200 private static final int VERSION_SWITCH_UID = 10;
201 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700202
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800203 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700204 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800205 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700206 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800207 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700208 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700209
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700210 private static final String TAG_POLICY_LIST = "policy-list";
211 private static final String TAG_NETWORK_POLICY = "network-policy";
212 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700213 private static final String TAG_APP_POLICY = "app-policy";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700214
215 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700216 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700217 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
218 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700219 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700220 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800221 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700222 private static final String ATTR_WARNING_BYTES = "warningBytes";
223 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700224 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800225 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
226 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800227 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700228 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700229 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700230 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700231 private static final String ATTR_POLICY = "policy";
232
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700233 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
234
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800235 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800236 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800237 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800238 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700239
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700240 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
241
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700242 private static final int MSG_RULES_CHANGED = 1;
243 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800244 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800245 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700246 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700247 private static final int MSG_SCREEN_ON_CHANGED = 8;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700248
Jeff Sharkey75279902011-05-24 18:39:45 -0700249 private final Context mContext;
250 private final IActivityManager mActivityManager;
251 private final IPowerManager mPowerManager;
252 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700253 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700254 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700255 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700256 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700257
258 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700259 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700260 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700261 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700262
Dianne Hackborn497175b2014-07-01 12:56:08 -0700263 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700264
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700265 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700266 volatile boolean mScreenOn;
267 volatile boolean mRestrictBackground;
268 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700269 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700270
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700271 private final boolean mSuppressDefaultPolicy;
272
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700273 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800274 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700275 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800276 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700277
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700278 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700279 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700280 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800281 final SparseIntArray mUidRules = new SparseIntArray();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700282 /** Set of states for the child firewall chains. True if the chain is active. */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700283 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700284
Jeff Sharkey32566012014-12-02 18:30:14 -0800285 /**
286 * UIDs that have been white-listed to always be able to have network access
287 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700288 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800289 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700290 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700291
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700292 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
293
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700294 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800295 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700296 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800297 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700298
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700299 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700300 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700301
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700302 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800303 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700304
305 /** The current maximum process state that we are considering to be foreground. */
306 private int mCurForegroundState = ActivityManager.PROCESS_STATE_TOP;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700307
Jeff Sharkey32566012014-12-02 18:30:14 -0800308 private final RemoteCallbackList<INetworkPolicyListener>
309 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700310
Dianne Hackborn497175b2014-07-01 12:56:08 -0700311 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700312
313 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700314
Svet Ganov16a16892015-04-16 10:32:04 -0700315 private final AppOpsManager mAppOps;
316
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700317 // TODO: keep whitelist of system-critical services that should never have
318 // rules enforced, such as system, phone, and radio UIDs.
319
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700320 // TODO: migrate notifications to SystemUI
321
Jeff Sharkey75279902011-05-24 18:39:45 -0700322 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700323 IPowerManager powerManager, INetworkStatsService networkStats,
324 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700325 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700326 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700327 }
328
329 private static File getSystemDir() {
330 return new File(Environment.getDataDirectory(), "system");
331 }
332
333 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700334 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700335 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
336 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700337 mContext = checkNotNull(context, "missing context");
338 mActivityManager = checkNotNull(activityManager, "missing activityManager");
339 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700340 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700341 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700342 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700343 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700344 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700345 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700346
Amith Yamasani450a16b2013-09-18 16:28:50 -0700347 HandlerThread thread = new HandlerThread(TAG);
348 thread.start();
349 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700350
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700351 mSuppressDefaultPolicy = suppressDefaultPolicy;
352
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700353 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700354
355 mAppOps = context.getSystemService(AppOpsManager.class);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700356 }
357
358 public void bindConnectivityManager(IConnectivityManager connManager) {
359 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700360 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700361
Jeff Sharkey497e4432011-06-14 17:27:29 -0700362 public void bindNotificationManager(INotificationManager notifManager) {
363 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
364 }
365
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700366 void updatePowerSaveWhitelistLocked() {
367 try {
368 final int[] whitelist = mDeviceIdleController.getAppIdWhitelist();
369 mPowerSaveWhitelistAppIds.clear();
370 if (whitelist != null) {
371 for (int uid : whitelist) {
372 mPowerSaveWhitelistAppIds.put(uid, true);
373 }
374 }
375 } catch (RemoteException e) {
376 }
377 }
378
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700379 void updatePowerSaveTempWhitelistLocked() {
380 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700381 // Clear the states of the current whitelist
382 final int N = mPowerSaveTempWhitelistAppIds.size();
383 for (int i = 0; i < N; i++) {
384 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
385 }
386 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700387 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700388 if (whitelist != null) {
389 for (int uid : whitelist) {
390 mPowerSaveTempWhitelistAppIds.put(uid, true);
391 }
392 }
393 } catch (RemoteException e) {
394 }
395 }
396
Amith Yamasani06f08062015-06-12 13:23:33 -0700397 /**
398 * Remove unnecessary entries in the temp whitelist
399 */
400 void purgePowerSaveTempWhitelistLocked() {
401 final int N = mPowerSaveTempWhitelistAppIds.size();
402 for (int i = N - 1; i >= 0; i--) {
403 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
404 mPowerSaveTempWhitelistAppIds.removeAt(i);
405 }
406 }
407 }
408
Jeff Sharkeya4620792011-05-20 15:29:23 -0700409 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700410 if (!isBandwidthControlEnabled()) {
411 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
412 return;
413 }
414
Amith Yamasani15e472352015-04-24 19:06:07 -0700415 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
416
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700417 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700418 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700419 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
420 mPowerManagerInternal.registerLowPowerModeObserver(
421 new PowerManagerInternal.LowPowerModeListener() {
422 @Override
423 public void onLowPowerModeChanged(boolean enabled) {
424 synchronized (mRulesLock) {
425 if (mRestrictPower != enabled) {
426 mRestrictPower = enabled;
427 updateRulesForGlobalChangeLocked(true);
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700428 updateRulesForTempWhitelistChangeLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700429 }
430 }
431 }
432 });
433 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700434 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700435
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700436 // read policy from disk
437 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700438
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700439 if (mRestrictBackground || mRestrictPower || mDeviceIdleMode) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700440 updateRulesForGlobalChangeLocked(true);
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700441 updateRulesForTempWhitelistChangeLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700442 updateNotificationsLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700443 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700444 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700445
Jeff Sharkeya4620792011-05-20 15:29:23 -0700446 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700447
Jeff Sharkeya4620792011-05-20 15:29:23 -0700448 try {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700449 mActivityManager.registerUidObserver(mUidObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700450 mNetworkManager.registerObserver(mAlertObserver);
451 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700452 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700453 }
454
Jeff Sharkeya4620792011-05-20 15:29:23 -0700455 // TODO: traverse existing processes to know foreground state, or have
456 // activitymanager dispatch current state when new observer attached.
457
458 final IntentFilter screenFilter = new IntentFilter();
459 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
460 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700461 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700462
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700463 // listen for changes to power save whitelist
464 final IntentFilter whitelistFilter = new IntentFilter(
465 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
466 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
467
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700468 DeviceIdleController.LocalService deviceIdleService
469 = LocalServices.getService(DeviceIdleController.LocalService.class);
470 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
471
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700472 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900473 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700474 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
475
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700476 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700477 final IntentFilter packageFilter = new IntentFilter();
478 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700479 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700480 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700481
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700482 // listen for UID changes to update policy
483 mContext.registerReceiver(
484 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
485
486 // listen for user changes to update policy
487 final IntentFilter userFilter = new IntentFilter();
488 userFilter.addAction(ACTION_USER_ADDED);
489 userFilter.addAction(ACTION_USER_REMOVED);
490 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
491
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700492 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700493 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
494 mContext.registerReceiver(
495 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
496
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700497 // listen for restrict background changes from notifications
498 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
499 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
500
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800501 // listen for snooze warning from notifications
502 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
503 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
504 MANAGE_NETWORK_POLICY, mHandler);
505
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700506 // listen for configured wifi networks to be removed
507 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700508 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700509
510 // listen for wifi state changes to catch metered hint
511 final IntentFilter wifiStateFilter = new IntentFilter(
512 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700513 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700514
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700515 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700516
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700517 }
518
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700519 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700520 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700521 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700522 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700523 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700524 }
525
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700526 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700527 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700528 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700529 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700530 }
531 };
532
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700533 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700534 @Override
535 public void onReceive(Context context, Intent intent) {
536 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
537 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700538 updatePowerSaveWhitelistLocked();
539 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700540 }
541 }
542 };
543
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700544 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
545 @Override
546 public void run() {
547 synchronized (mRulesLock) {
548 updatePowerSaveTempWhitelistLocked();
549 updateRulesForTempWhitelistChangeLocked();
550 purgePowerSaveTempWhitelistLocked();
551 }
552 }
553 };
554
555 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700556 @Override
557 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800558 // screen-related broadcasts are protected by system, no need
559 // for permissions check.
560 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700561 }
562 };
563
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700564 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700565 @Override
566 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700567 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700568
569 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700570 final int uid = intent.getIntExtra(EXTRA_UID, -1);
571 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700572
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700573 if (ACTION_PACKAGE_ADDED.equals(action)) {
574 // update rules for UID, since it might be subject to
575 // global background data policy
576 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
577 synchronized (mRulesLock) {
578 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700579 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700580 }
581 }
582 };
583
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700584 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700585 @Override
586 public void onReceive(Context context, Intent intent) {
587 // on background handler thread, and UID_REMOVED is protected
588
589 final int uid = intent.getIntExtra(EXTRA_UID, -1);
590 if (uid == -1) return;
591
592 // remove any policy and update rules to clean up
593 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
594 synchronized (mRulesLock) {
595 mUidPolicy.delete(uid);
596 updateRulesForUidLocked(uid);
597 writePolicyLocked();
598 }
599 }
600 };
601
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700602 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700603 @Override
604 public void onReceive(Context context, Intent intent) {
605 // on background handler thread, and USER_ADDED and USER_REMOVED
606 // broadcasts are protected
607
608 final String action = intent.getAction();
609 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
610 if (userId == -1) return;
611
Amith Yamasani15e472352015-04-24 19:06:07 -0700612 switch (action) {
613 case ACTION_USER_REMOVED:
614 case ACTION_USER_ADDED:
615 synchronized (mRulesLock) {
616 // Remove any policies for given user; both cleaning up after a
617 // USER_REMOVED, and one last sanity check during USER_ADDED
618 removePoliciesForUserLocked(userId);
619 // Update global restrict for new user
620 updateRulesForGlobalChangeLocked(true);
621 }
622 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700623 }
624 }
625 };
626
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700627 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700628 * Receiver that watches for {@link INetworkStatsService} updates, which we
629 * use to check against {@link NetworkPolicy#warningBytes}.
630 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700631 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700632 @Override
633 public void onReceive(Context context, Intent intent) {
634 // on background handler thread, and verified
635 // READ_NETWORK_USAGE_HISTORY permission above.
636
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800637 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700638 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700639 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700640 updateNotificationsLocked();
641 }
642 }
643 };
644
645 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700646 * Receiver that watches for {@link Notification} control of
647 * {@link #mRestrictBackground}.
648 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700649 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700650 @Override
651 public void onReceive(Context context, Intent intent) {
652 // on background handler thread, and verified MANAGE_NETWORK_POLICY
653 // permission above.
654
655 setRestrictBackground(false);
656 }
657 };
658
659 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800660 * Receiver that watches for {@link Notification} control of
661 * {@link NetworkPolicy#lastWarningSnooze}.
662 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700663 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800664 @Override
665 public void onReceive(Context context, Intent intent) {
666 // on background handler thread, and verified MANAGE_NETWORK_POLICY
667 // permission above.
668
669 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
670 performSnooze(template, TYPE_WARNING);
671 }
672 };
673
674 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700675 * Receiver that watches for {@link WifiConfiguration} to be changed.
676 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700677 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700678 @Override
679 public void onReceive(Context context, Intent intent) {
680 // on background handler thread, and verified CONNECTIVITY_INTERNAL
681 // permission above.
682
683 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
684 if (reason == CHANGE_REASON_REMOVED) {
685 final WifiConfiguration config = intent.getParcelableExtra(
686 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700687 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800688 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700689 synchronized (mRulesLock) {
690 if (mNetworkPolicy.containsKey(template)) {
691 mNetworkPolicy.remove(template);
692 writePolicyLocked();
693 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700694 }
695 }
696 }
697 }
698 };
699
700 /**
701 * Receiver that watches {@link WifiInfo} state changes to infer metered
702 * state. Ignores hints when policy is user-defined.
703 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700704 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700705 @Override
706 public void onReceive(Context context, Intent intent) {
707 // on background handler thread, and verified CONNECTIVITY_INTERNAL
708 // permission above.
709
710 // ignore when not connected
711 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
712 if (!netInfo.isConnected()) return;
713
714 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
715 final boolean meteredHint = info.getMeteredHint();
716
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800717 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700718 synchronized (mRulesLock) {
719 NetworkPolicy policy = mNetworkPolicy.get(template);
720 if (policy == null && meteredHint) {
721 // policy doesn't exist, and AP is hinting that it's
722 // metered: create an inferred policy.
723 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
724 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
725 meteredHint, true);
726 addNetworkPolicyLocked(policy);
727
728 } else if (policy != null && policy.inferred) {
729 // policy exists, and was inferred: update its current
730 // metered state.
731 policy.metered = meteredHint;
732
733 // since this is inferred for each wifi session, just update
734 // rules without persisting.
735 updateNetworkRulesLocked();
736 }
737 }
738 }
739 };
740
741 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700742 * Observer that watches for {@link INetworkManagementService} alerts.
743 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700744 final private INetworkManagementEventObserver mAlertObserver
745 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700746 @Override
747 public void limitReached(String limitName, String iface) {
748 // only someone like NMS should be calling us
749 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
750
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800751 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
752 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700753 }
754 }
755 };
756
757 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700758 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
759 * to show visible notifications as needed.
760 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700761 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700762 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
763
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700764 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700765 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700766 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700767
768 // TODO: when switching to kernel notifications, compute next future
769 // cycle boundary to recompute notifications.
770
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700771 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800772 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700773 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
774 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700775 // ignore policies that aren't relevant to user
776 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700777 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700778
Jeff Sharkey497e4432011-06-14 17:27:29 -0700779 final long start = computeLastCycleBoundary(currentTime, policy);
780 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700781 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700782
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700783 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800784 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700785 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
786 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700787 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
788 notifyOverLimitLocked(policy.template);
789 }
790
Jeff Sharkey497e4432011-06-14 17:27:29 -0700791 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700792 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700793
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800794 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700795 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700796 }
797 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700798 }
799
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700800 // ongoing notification when restricting background data
801 if (mRestrictBackground) {
802 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700803 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700804
805 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700806 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
807 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700808 if (!mActiveNotifs.contains(tag)) {
809 cancelNotification(tag);
810 }
811 }
812 }
813
814 /**
815 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700816 * current device state, such as when
817 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
818 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700819 */
820 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800821 if (template.isMatchRuleMobile()) {
822 final TelephonyManager tele = TelephonyManager.from(mContext);
823 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700824
Jeff Sharkey32566012014-12-02 18:30:14 -0800825 // Mobile template is relevant when any active subscriber matches
826 final int[] subIds = sub.getActiveSubscriptionIdList();
827 for (int subId : subIds) {
828 final String subscriberId = tele.getSubscriberId(subId);
829 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
830 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
831 if (template.matches(probeIdent)) {
832 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700833 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800834 }
835 return false;
836 } else {
837 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700838 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700839 }
840
841 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700842 * Notify that given {@link NetworkTemplate} is over
843 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
844 */
845 private void notifyOverLimitLocked(NetworkTemplate template) {
846 if (!mOverLimitNotified.contains(template)) {
847 mContext.startActivity(buildNetworkOverLimitIntent(template));
848 mOverLimitNotified.add(template);
849 }
850 }
851
852 private void notifyUnderLimitLocked(NetworkTemplate template) {
853 mOverLimitNotified.remove(template);
854 }
855
856 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700857 * Build unique tag that identifies an active {@link NetworkPolicy}
858 * notification of a specific type, like {@link #TYPE_LIMIT}.
859 */
860 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700861 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700862 }
863
864 /**
865 * Show notification for combined {@link NetworkPolicy} and specific type,
866 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
867 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700868 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700869 final String tag = buildNotificationTag(policy, type);
870 final Notification.Builder builder = new Notification.Builder(mContext);
871 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800872 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700873 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200874 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700875
876 final Resources res = mContext.getResources();
877 switch (type) {
878 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700879 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700880 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700881
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700882 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700883 builder.setTicker(title);
884 builder.setContentTitle(title);
885 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700886
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800887 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
888 builder.setDeleteIntent(PendingIntent.getBroadcast(
889 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
890
891 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700892 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800893 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
894
Jeff Sharkey497e4432011-06-14 17:27:29 -0700895 break;
896 }
897 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700898 final CharSequence body = res.getText(R.string.data_usage_limit_body);
899
900 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -0400901 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700902 switch (policy.template.getMatchRule()) {
903 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700904 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700905 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700906 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700907 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700908 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700909 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700910 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700911 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700912 case MATCH_WIFI:
913 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -0400914 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700915 break;
916 default:
917 title = null;
918 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700919 }
920
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800921 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -0400922 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700923 builder.setTicker(title);
924 builder.setContentTitle(title);
925 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700926
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700927 final Intent intent = buildNetworkOverLimitIntent(policy.template);
928 builder.setContentIntent(PendingIntent.getActivity(
929 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
930 break;
931 }
932 case TYPE_LIMIT_SNOOZED: {
933 final long overBytes = totalBytes - policy.limitBytes;
934 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
935 Formatter.formatFileSize(mContext, overBytes));
936
937 final CharSequence title;
938 switch (policy.template.getMatchRule()) {
939 case MATCH_MOBILE_3G_LOWER:
940 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
941 break;
942 case MATCH_MOBILE_4G:
943 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
944 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700945 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700946 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
947 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700948 case MATCH_WIFI:
949 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
950 break;
951 default:
952 title = null;
953 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700954 }
955
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800956 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700957 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700958 builder.setTicker(title);
959 builder.setContentTitle(title);
960 builder.setContentText(body);
961
962 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700963 builder.setContentIntent(PendingIntent.getActivity(
964 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700965 break;
966 }
967 }
968
969 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700970 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700971 try {
972 final String packageName = mContext.getPackageName();
973 final int[] idReceived = new int[1];
974 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800975 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Dianne Hackborn41203752012-08-31 14:05:51 -0700976 UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700977 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700978 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700979 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700980 }
981 }
982
983 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700984 * Show ongoing notification to reflect that {@link #mRestrictBackground}
985 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700986 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700987 private void enqueueRestrictedNotification(String tag) {
988 final Resources res = mContext.getResources();
989 final Notification.Builder builder = new Notification.Builder(mContext);
990
991 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
992 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
993
994 builder.setOnlyAlertOnce(true);
995 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700996 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700997 builder.setTicker(title);
998 builder.setContentTitle(title);
999 builder.setContentText(body);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001000 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001001 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001002
1003 final Intent intent = buildAllowBackgroundDataIntent();
1004 builder.setContentIntent(
1005 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001006
1007 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -07001008 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -07001009 try {
1010 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001011 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001012 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Dianne Hackborn41203752012-08-31 14:05:51 -07001013 0x0, builder.getNotification(), idReceived, UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001014 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001015 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001016 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001017 }
1018 }
1019
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001020 private void cancelNotification(String tag) {
1021 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -07001022 // XXX what to do about multi-user?
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001023 try {
1024 final String packageName = mContext.getPackageName();
1025 mNotifManager.cancelNotificationWithTag(
Dianne Hackborn41203752012-08-31 14:05:51 -07001026 packageName, tag, 0x0, UserHandle.USER_OWNER);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001027 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001028 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001029 }
1030 }
1031
1032 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001033 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001034 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001035 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001036 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001037 @Override
1038 public void onReceive(Context context, Intent intent) {
1039 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1040 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001041
1042 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001043 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001044 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001045 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001046 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001047 updateNetworkRulesLocked();
1048 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001049 }
1050 }
1051 };
1052
1053 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001054 * Proactively control network data connections when they exceed
1055 * {@link NetworkPolicy#limitBytes}.
1056 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001057 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001058 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1059
1060 // TODO: reset any policy-disabled networks when any policy is removed
1061 // completely, which is currently rare case.
1062
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001063 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001064 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1065 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001066 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001067 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001068 setNetworkTemplateEnabled(policy.template, true);
1069 continue;
1070 }
1071
1072 final long start = computeLastCycleBoundary(currentTime, policy);
1073 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001074 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001075
1076 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001077 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1078 && policy.lastLimitSnooze < start;
1079 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001080
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001081 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001082 }
1083 }
1084
1085 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001086 * Proactively disable networks that match the given
1087 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001088 */
1089 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001090 // TODO: reach into ConnectivityManager to proactively disable bringing
1091 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001092 }
1093
1094 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001095 * Examine all connected {@link NetworkState}, looking for
1096 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1097 * remaining quota based on usage cycle and historical stats.
1098 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001099 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001100 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001101
1102 final NetworkState[] states;
1103 try {
1104 states = mConnManager.getAllNetworkState();
1105 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001106 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001107 return;
1108 }
1109
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001110 // If we are in restrict power mode, we want to treat all interfaces
1111 // as metered, to restrict access to the network by uid. However, we
1112 // will not have a bandwidth limit. Also only do this if restrict
1113 // background data use is *not* enabled, since that takes precendence
1114 // use over those networks can have a cost associated with it).
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001115 final boolean powerSave = mRestrictPower && !mRestrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001116
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001117 // First, generate identities of all connected networks so we can
1118 // quickly compare them against all defined policies below.
1119 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001120 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001121 for (NetworkState state : states) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001122 if (state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001123 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001124
1125 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001126 if (baseIface != null) {
1127 connIdents.add(Pair.create(baseIface, ident));
1128 if (powerSave) {
1129 connIfaces.add(baseIface);
1130 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001131 }
1132
1133 // Stacked interfaces are considered to have same identity as
1134 // their parent network.
1135 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1136 for (LinkProperties stackedLink : stackedLinks) {
1137 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001138 if (stackedIface != null) {
1139 connIdents.add(Pair.create(stackedIface, ident));
1140 if (powerSave) {
1141 connIfaces.add(stackedIface);
1142 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001143 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001144 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001145 }
1146 }
1147
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001148 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001149 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001150 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001151 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001152 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001153
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001154 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001155 for (int j = connIdents.size() - 1; j >= 0; j--) {
1156 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1157 if (policy.template.matches(ident.second)) {
1158 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001159 }
1160 }
1161
1162 if (ifaceList.size() > 0) {
1163 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001164 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001165 }
1166 }
1167
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001168 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001169 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001170
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001171 // apply each policy that we found ifaces for; compute remaining data
1172 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001173 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001174 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1175 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1176 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001177
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001178 final long start;
1179 final long totalBytes;
1180 if (policy.hasCycle()) {
1181 start = computeLastCycleBoundary(currentTime, policy);
1182 totalBytes = getTotalBytes(policy.template, start, currentTime);
1183 } else {
1184 start = Long.MAX_VALUE;
1185 totalBytes = 0;
1186 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001187
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001188 if (LOGD) {
1189 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001190 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001191 }
1192
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001193 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001194 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001195 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001196 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001197 if (!hasLimit) {
1198 // metered network, but no policy limit; we still need to
1199 // restrict apps, so push really high quota.
1200 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001201 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001202 // snoozing past quota, but we still need to restrict apps,
1203 // so push really high quota.
1204 quotaBytes = Long.MAX_VALUE;
1205 } else {
1206 // remaining "quota" bytes are based on total usage in
1207 // current cycle. kernel doesn't like 0-byte rules, so we
1208 // set 1-byte quota and disable the radio later.
1209 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1210 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001211
1212 if (ifaces.length > 1) {
1213 // TODO: switch to shared quota once NMS supports
1214 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001215 }
1216
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001217 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001218 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001219 setInterfaceQuota(iface, quotaBytes);
1220 newMeteredIfaces.add(iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001221 if (powerSave) {
1222 connIfaces.remove(iface);
1223 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001224 }
1225 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001226
1227 // keep track of lowest warning or limit of active policies
1228 if (hasWarning && policy.warningBytes < lowestRule) {
1229 lowestRule = policy.warningBytes;
1230 }
1231 if (hasLimit && policy.limitBytes < lowestRule) {
1232 lowestRule = policy.limitBytes;
1233 }
1234 }
1235
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001236 for (int i = connIfaces.size()-1; i >= 0; i--) {
1237 String iface = connIfaces.valueAt(i);
1238 removeInterfaceQuota(iface);
1239 setInterfaceQuota(iface, Long.MAX_VALUE);
1240 newMeteredIfaces.add(iface);
1241 }
1242
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001243 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001244
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001245 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001246 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1247 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001248 if (!newMeteredIfaces.contains(iface)) {
1249 removeInterfaceQuota(iface);
1250 }
1251 }
1252 mMeteredIfaces = newMeteredIfaces;
1253
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001254 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001255 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001256 }
1257
1258 /**
1259 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1260 * have at least a default mobile policy defined.
1261 */
1262 private void ensureActiveMobilePolicyLocked() {
1263 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001264 if (mSuppressDefaultPolicy) return;
1265
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001266 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001267 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001268
Jeff Sharkey32566012014-12-02 18:30:14 -08001269 final int[] subIds = sub.getActiveSubscriptionIdList();
1270 for (int subId : subIds) {
1271 final String subscriberId = tele.getSubscriberId(subId);
1272 ensureActiveMobilePolicyLocked(subscriberId);
1273 }
1274 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001275
Jeff Sharkey32566012014-12-02 18:30:14 -08001276 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1277 // Poke around to see if we already have a policy
1278 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1279 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1280 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1281 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1282 if (template.matches(probeIdent)) {
1283 if (LOGD) {
1284 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1285 + NetworkIdentity.scrubSubscriberId(subscriberId));
1286 }
1287 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001288 }
1289 }
1290
Jeff Sharkey32566012014-12-02 18:30:14 -08001291 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1292 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001293
Jeff Sharkey32566012014-12-02 18:30:14 -08001294 // Build default mobile policy, and assume usage cycle starts today
1295 final long warningBytes = mContext.getResources().getInteger(
1296 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001297
Jeff Sharkey32566012014-12-02 18:30:14 -08001298 final Time time = new Time();
1299 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001300
Jeff Sharkey32566012014-12-02 18:30:14 -08001301 final int cycleDay = time.monthDay;
1302 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001303
Jeff Sharkey32566012014-12-02 18:30:14 -08001304 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1305 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1306 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1307 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001308 }
1309
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001310 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001311 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001312
1313 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001314 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001315 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001316
1317 FileInputStream fis = null;
1318 try {
1319 fis = mPolicyFile.openRead();
1320 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001321 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001322
1323 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001324 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001325 while ((type = in.next()) != END_DOCUMENT) {
1326 final String tag = in.getName();
1327 if (type == START_TAG) {
1328 if (TAG_POLICY_LIST.equals(tag)) {
1329 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001330 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1331 mRestrictBackground = readBooleanAttribute(
1332 in, ATTR_RESTRICT_BACKGROUND);
1333 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001334 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001335 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001336
1337 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1338 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1339 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001340 final String networkId;
1341 if (version >= VERSION_ADDED_NETWORK_ID) {
1342 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1343 } else {
1344 networkId = null;
1345 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001346 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001347 final String cycleTimezone;
1348 if (version >= VERSION_ADDED_TIMEZONE) {
1349 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1350 } else {
1351 cycleTimezone = Time.TIMEZONE_UTC;
1352 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001353 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1354 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001355 final long lastLimitSnooze;
1356 if (version >= VERSION_SPLIT_SNOOZE) {
1357 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1358 } else if (version >= VERSION_ADDED_SNOOZE) {
1359 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001360 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001361 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001362 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001363 final boolean metered;
1364 if (version >= VERSION_ADDED_METERED) {
1365 metered = readBooleanAttribute(in, ATTR_METERED);
1366 } else {
1367 switch (networkTemplate) {
1368 case MATCH_MOBILE_3G_LOWER:
1369 case MATCH_MOBILE_4G:
1370 case MATCH_MOBILE_ALL:
1371 metered = true;
1372 break;
1373 default:
1374 metered = false;
1375 }
1376 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001377 final long lastWarningSnooze;
1378 if (version >= VERSION_SPLIT_SNOOZE) {
1379 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1380 } else {
1381 lastWarningSnooze = SNOOZE_NEVER;
1382 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001383 final boolean inferred;
1384 if (version >= VERSION_ADDED_INFERRED) {
1385 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1386 } else {
1387 inferred = false;
1388 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001389
Jeff Sharkey32566012014-12-02 18:30:14 -08001390 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1391 subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001392 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001393 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001394 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001395
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001396 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001397 final int uid = readIntAttribute(in, ATTR_UID);
1398 final int policy = readIntAttribute(in, ATTR_POLICY);
1399
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001400 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001401 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001402 } else {
1403 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1404 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001405 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001406 final int appId = readIntAttribute(in, ATTR_APP_ID);
1407 final int policy = readIntAttribute(in, ATTR_POLICY);
1408
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001409 // TODO: set for other users during upgrade
1410 final int uid = UserHandle.getUid(UserHandle.USER_OWNER, appId);
1411 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001412 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001413 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001414 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001415 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001416 }
1417 }
1418 }
1419
1420 } catch (FileNotFoundException e) {
1421 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001422 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001423 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001424 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001425 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001426 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001427 } finally {
1428 IoUtils.closeQuietly(fis);
1429 }
1430 }
1431
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001432 /**
1433 * Upgrade legacy background data flags, notifying listeners of one last
1434 * change to always-true.
1435 */
1436 private void upgradeLegacyBackgroundData() {
1437 mRestrictBackground = Settings.Secure.getInt(
1438 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1439
1440 // kick off one last broadcast if restricted
1441 if (mRestrictBackground) {
1442 final Intent broadcast = new Intent(
1443 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001444 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001445 }
1446 }
1447
Dianne Hackborn497175b2014-07-01 12:56:08 -07001448 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001449 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001450
1451 FileOutputStream fos = null;
1452 try {
1453 fos = mPolicyFile.startWrite();
1454
1455 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001456 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001457 out.startDocument(null, true);
1458
1459 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001460 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001461 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001462
1463 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001464 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1465 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001466 final NetworkTemplate template = policy.template;
1467
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001468 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001469 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1470 final String subscriberId = template.getSubscriberId();
1471 if (subscriberId != null) {
1472 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001473 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001474 final String networkId = template.getNetworkId();
1475 if (networkId != null) {
1476 out.attribute(null, ATTR_NETWORK_ID, networkId);
1477 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001478 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001479 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001480 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1481 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001482 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1483 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001484 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001485 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001486 out.endTag(null, TAG_NETWORK_POLICY);
1487 }
1488
1489 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001490 for (int i = 0; i < mUidPolicy.size(); i++) {
1491 final int uid = mUidPolicy.keyAt(i);
1492 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001493
Jeff Sharkey497e4432011-06-14 17:27:29 -07001494 // skip writing empty policies
1495 if (policy == POLICY_NONE) continue;
1496
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001497 out.startTag(null, TAG_UID_POLICY);
1498 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001499 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001500 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001501 }
1502
1503 out.endTag(null, TAG_POLICY_LIST);
1504 out.endDocument();
1505
1506 mPolicyFile.finishWrite(fos);
1507 } catch (IOException e) {
1508 if (fos != null) {
1509 mPolicyFile.failWrite(fos);
1510 }
1511 }
1512 }
1513
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001514 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001515 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001516 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001517
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001518 if (!UserHandle.isApp(uid)) {
1519 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001520 }
1521
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001522 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001523 final long token = Binder.clearCallingIdentity();
1524 try {
1525 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1526 if (oldPolicy != policy) {
1527 setUidPolicyUncheckedLocked(uid, policy, true);
1528 }
1529 } finally {
1530 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001531 }
1532 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001533 }
1534
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001535 @Override
1536 public void addUidPolicy(int uid, int policy) {
1537 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001538
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001539 if (!UserHandle.isApp(uid)) {
1540 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1541 }
1542
1543 synchronized (mRulesLock) {
1544 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1545 policy |= oldPolicy;
1546 if (oldPolicy != policy) {
1547 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001548 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001549 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001550 }
1551
1552 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001553 public void removeUidPolicy(int uid, int policy) {
1554 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1555
1556 if (!UserHandle.isApp(uid)) {
1557 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1558 }
1559
1560 synchronized (mRulesLock) {
1561 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1562 policy = oldPolicy & ~policy;
1563 if (oldPolicy != policy) {
1564 setUidPolicyUncheckedLocked(uid, policy, true);
1565 }
1566 }
1567 }
1568
1569 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1570 mUidPolicy.put(uid, policy);
1571
1572 // uid policy changed, recompute rules and persist policy.
1573 updateRulesForUidLocked(uid);
1574 if (persist) {
1575 writePolicyLocked();
1576 }
1577 }
1578
1579 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001580 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001581 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1582
Jeff Sharkeya4620792011-05-20 15:29:23 -07001583 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001584 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001585 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001586 }
1587
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001588 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001589 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001590 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1591
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001592 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001593 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001594 for (int i = 0; i < mUidPolicy.size(); i++) {
1595 final int uid = mUidPolicy.keyAt(i);
1596 final int uidPolicy = mUidPolicy.valueAt(i);
1597 if (uidPolicy == policy) {
1598 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001599 }
1600 }
1601 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001602 return uids;
1603 }
1604
1605 /**
1606 * Remove any policies associated with given {@link UserHandle}, persisting
1607 * if any changes are made.
1608 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001609 void removePoliciesForUserLocked(int userId) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001610 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1611
1612 int[] uids = new int[0];
1613 for (int i = 0; i < mUidPolicy.size(); i++) {
1614 final int uid = mUidPolicy.keyAt(i);
1615 if (UserHandle.getUserId(uid) == userId) {
1616 uids = appendInt(uids, uid);
1617 }
1618 }
1619
1620 if (uids.length > 0) {
1621 for (int uid : uids) {
1622 mUidPolicy.delete(uid);
1623 updateRulesForUidLocked(uid);
1624 }
1625 writePolicyLocked();
1626 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001627 }
1628
1629 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001630 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001631 // TODO: create permission for observing network policy
1632 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1633
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001634 mListeners.register(listener);
1635
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001636 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001637 }
1638
1639 @Override
1640 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001641 // TODO: create permission for observing network policy
1642 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1643
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001644 mListeners.unregister(listener);
1645 }
1646
Jeff Sharkey1b861272011-05-22 00:34:52 -07001647 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001648 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001649 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1650
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001651 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001652 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001653 normalizePoliciesLocked(policies);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001654 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001655 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001656 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001657 writePolicyLocked();
1658 }
1659 }
1660
Dianne Hackborn497175b2014-07-01 12:56:08 -07001661 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001662 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001663 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1664 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001665 }
1666
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001667 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001668 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001669 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001670 try {
1671 mContext.enforceCallingPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1672 // SKIP checking run-time OP_READ_PHONE_STATE since using PRIVILEGED
1673 } catch (SecurityException e) {
1674 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001675
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001676 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1677 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1678 return new NetworkPolicy[0];
1679 }
Svet Ganov16a16892015-04-16 10:32:04 -07001680 }
1681
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001682 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001683 final int size = mNetworkPolicy.size();
1684 final NetworkPolicy[] policies = new NetworkPolicy[size];
1685 for (int i = 0; i < size; i++) {
1686 policies[i] = mNetworkPolicy.valueAt(i);
1687 }
1688 return policies;
1689 }
1690 }
1691
1692 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001693 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001694 }
1695
1696 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1697 final TelephonyManager tele = TelephonyManager.from(mContext);
1698 final String[] merged = tele.getMergedSubscriberIds();
1699
1700 mNetworkPolicy.clear();
1701 for (NetworkPolicy policy : policies) {
1702 // When two normalized templates conflict, prefer the most
1703 // restrictive policy
1704 policy.template = NetworkTemplate.normalize(policy.template, merged);
1705 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1706 if (existing == null || existing.compareTo(policy) > 0) {
1707 if (existing != null) {
1708 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1709 }
1710 mNetworkPolicy.put(policy.template, policy);
1711 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001712 }
1713 }
1714
1715 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001716 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001717 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001718
1719 final long token = Binder.clearCallingIdentity();
1720 try {
1721 performSnooze(template, TYPE_LIMIT);
1722 } finally {
1723 Binder.restoreCallingIdentity(token);
1724 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001725 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001726
Dianne Hackborn497175b2014-07-01 12:56:08 -07001727 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001728 maybeRefreshTrustedTime();
1729 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001730 synchronized (mRulesLock) {
1731 // find and snooze local policy that matches
1732 final NetworkPolicy policy = mNetworkPolicy.get(template);
1733 if (policy == null) {
1734 throw new IllegalArgumentException("unable to find policy for " + template);
1735 }
1736
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001737 switch (type) {
1738 case TYPE_WARNING:
1739 policy.lastWarningSnooze = currentTime;
1740 break;
1741 case TYPE_LIMIT:
1742 policy.lastLimitSnooze = currentTime;
1743 break;
1744 default:
1745 throw new IllegalArgumentException("unexpected type");
1746 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001747
Jeff Sharkey32566012014-12-02 18:30:14 -08001748 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001749 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001750 updateNetworkRulesLocked();
1751 updateNotificationsLocked();
1752 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001753 }
1754 }
1755
1756 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001757 public void setRestrictBackground(boolean restrictBackground) {
1758 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1759
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001760 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001761 synchronized (mRulesLock) {
1762 mRestrictBackground = restrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001763 updateRulesForGlobalChangeLocked(false);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001764 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001765 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001766 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001767
1768 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1769 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001770 }
1771
1772 @Override
1773 public boolean getRestrictBackground() {
1774 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1775
1776 synchronized (mRulesLock) {
1777 return mRestrictBackground;
1778 }
1779 }
1780
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001781 @Override
1782 public void setDeviceIdleMode(boolean enabled) {
1783 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1784
1785 synchronized (mRulesLock) {
1786 if (mDeviceIdleMode != enabled) {
1787 mDeviceIdleMode = enabled;
1788 if (mSystemReady) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001789 updateRulesForDeviceIdleLocked();
1790 }
1791 if (enabled) {
1792 EventLogTags.writeDeviceIdleOnPhase("net");
1793 } else {
1794 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001795 }
1796 }
1797 }
1798 }
1799
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001800 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001801 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1802 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001803 if (policy.template.matches(ident)) {
1804 return policy;
1805 }
1806 }
1807 return null;
1808 }
1809
1810 @Override
1811 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1812 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1813
1814 // only returns usage summary, so we don't require caller to have
1815 // READ_NETWORK_USAGE_HISTORY.
1816 final long token = Binder.clearCallingIdentity();
1817 try {
1818 return getNetworkQuotaInfoUnchecked(state);
1819 } finally {
1820 Binder.restoreCallingIdentity(token);
1821 }
1822 }
1823
1824 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1825 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1826
1827 final NetworkPolicy policy;
1828 synchronized (mRulesLock) {
1829 policy = findPolicyForNetworkLocked(ident);
1830 }
1831
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001832 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001833 // missing policy means we can't derive useful quota info
1834 return null;
1835 }
1836
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001837 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001838
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001839 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001840 final long start = computeLastCycleBoundary(currentTime, policy);
1841 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001842 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001843
1844 // report soft and hard limits under policy
1845 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1846 : NetworkQuotaInfo.NO_LIMIT;
1847 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1848 : NetworkQuotaInfo.NO_LIMIT;
1849
1850 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1851 }
1852
Jeff Sharkey46645002011-07-27 21:11:21 -07001853 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001854 public boolean isNetworkMetered(NetworkState state) {
1855 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1856
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001857 // roaming networks are always considered metered
1858 if (ident.getRoaming()) {
1859 return true;
1860 }
1861
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001862 final NetworkPolicy policy;
1863 synchronized (mRulesLock) {
1864 policy = findPolicyForNetworkLocked(ident);
1865 }
1866
1867 if (policy != null) {
1868 return policy.metered;
1869 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001870 final int type = state.networkInfo.getType();
1871 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1872 return true;
1873 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001874 return false;
1875 }
1876 }
1877
1878 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001879 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001880 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001881
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001882 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1883
Dianne Hackborn497175b2014-07-01 12:56:08 -07001884 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001885 for (String arg : args) {
1886 argSet.add(arg);
1887 }
1888
Jeff Sharkey1b861272011-05-22 00:34:52 -07001889 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001890 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001891 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1892 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001893 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001894
Jeff Sharkey32566012014-12-02 18:30:14 -08001895 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001896 updateNetworkEnabledLocked();
1897 updateNetworkRulesLocked();
1898 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001899 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001900
1901 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001902 return;
1903 }
1904
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001905 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07001906 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001907 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001908 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001909 fout.print("Current foreground state: "); fout.println(mCurForegroundState);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001910 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001911 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001912 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1913 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001914 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001915 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001916
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001917 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
1918
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001919 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001920 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001921 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001922 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001923 final int uid = mUidPolicy.keyAt(i);
1924 final int policy = mUidPolicy.valueAt(i);
1925 fout.print("UID=");
1926 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001927 fout.print(" policy=");
1928 dumpPolicy(fout, policy);
1929 fout.println();
1930 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001931 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001932
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001933 size = mPowerSaveWhitelistAppIds.size();
1934 if (size > 0) {
1935 fout.println("Power save whitelist app ids:");
1936 fout.increaseIndent();
1937 for (int i = 0; i < size; i++) {
1938 fout.print("UID=");
1939 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
1940 fout.print(": ");
1941 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
1942 fout.println();
1943 }
1944 fout.decreaseIndent();
1945 }
1946
Jeff Sharkey1b861272011-05-22 00:34:52 -07001947 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07001948 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001949 collectKeys(mUidRules, knownUids);
1950
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001951 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001952 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001953 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001954 for (int i = 0; i < size; i++) {
1955 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001956 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001957 fout.print(uid);
1958
Dianne Hackborn497175b2014-07-01 12:56:08 -07001959 int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1960 fout.print(" state=");
1961 fout.print(state);
1962 fout.print(state <= mCurForegroundState ? " (fg)" : " (bg)");
1963
Jeff Sharkey1b861272011-05-22 00:34:52 -07001964 fout.print(" rules=");
1965 final int rulesIndex = mUidRules.indexOfKey(uid);
1966 if (rulesIndex < 0) {
1967 fout.print("UNKNOWN");
1968 } else {
1969 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1970 }
1971
1972 fout.println();
1973 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001974 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001975 }
1976 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001977
1978 @Override
1979 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001980 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1981
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001982 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001983 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001984 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001985 }
1986
Dianne Hackborn497175b2014-07-01 12:56:08 -07001987 boolean isUidForegroundLocked(int uid) {
1988 // only really in foreground when screen is also on
1989 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
1990 <= mCurForegroundState;
1991 }
1992
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001993 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07001994 * Process state of UID changed; if needed, will trigger
1995 * {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001996 */
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07001997 void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001998 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1999 if (oldUidState != uidState) {
2000 // state changed, push updated rules
2001 mUidState.put(uid, uidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002002 updateRulesForUidStateChangeLocked(uid, oldUidState, uidState);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002003 if (mDeviceIdleMode && isProcStateAllowedWhileIdle(oldUidState)
2004 != isProcStateAllowedWhileIdle(uidState)) {
2005 updateRulesForDeviceIdleLocked();
2006 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002007 }
2008 }
2009
2010 void removeUidStateLocked(int uid) {
2011 final int index = mUidState.indexOfKey(uid);
2012 if (index >= 0) {
2013 final int oldUidState = mUidState.valueAt(index);
2014 mUidState.removeAt(index);
2015 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
2016 updateRulesForUidStateChangeLocked(uid, oldUidState,
2017 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002018 if (mDeviceIdleMode) {
2019 updateRulesForDeviceIdleLocked();
2020 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002021 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002022 }
2023 }
2024
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002025 void updateRulesForUidStateChangeLocked(int uid, int oldUidState, int newUidState) {
2026 final boolean oldForeground = oldUidState <= mCurForegroundState;
2027 final boolean newForeground = newUidState <= mCurForegroundState;
2028 if (oldForeground != newForeground) {
2029 updateRulesForUidLocked(uid);
2030 }
2031 }
2032
Jeff Sharkeya4620792011-05-20 15:29:23 -07002033 private void updateScreenOn() {
2034 synchronized (mRulesLock) {
2035 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002036 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002037 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002038 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002039 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002040 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002041 }
2042 }
2043
2044 /**
2045 * Update rules that might be changed by {@link #mScreenOn} value.
2046 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002047 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002048 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002049 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002050 for (int i = 0; i < size; i++) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002051 if (mUidState.valueAt(i) <= mCurForegroundState) {
2052 final int uid = mUidState.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002053 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002054 }
2055 }
2056 }
2057
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002058 static boolean isProcStateAllowedWhileIdle(int procState) {
2059 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2060 }
2061
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002062 void updateRulesForDeviceIdleLocked() {
2063 if (mDeviceIdleMode) {
2064 // sync the whitelists before enable dozable chain. We don't care about the rules if
2065 // we are disabling the chain.
2066 SparseIntArray uidRules = new SparseIntArray();
2067 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002068 for (int ui = users.size() - 1; ui >= 0; ui--) {
2069 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002070 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
2071 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2072 int uid = UserHandle.getUid(user.id, appId);
2073 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2074 }
2075 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2076 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2077 int uid = UserHandle.getUid(user.id, appId);
2078 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2079 }
2080 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002081 for (int i = mUidState.size() - 1; i >= 0; i--) {
2082 if (isProcStateAllowedWhileIdle(mUidState.valueAt(i))) {
2083 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2084 }
2085 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002086 setUidFirewallRules(FIREWALL_CHAIN_DOZABLE, uidRules);
2087 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002088 enableFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, mDeviceIdleMode);
2089 }
2090
2091 void updateRulesForAppIdleParoleLocked() {
2092 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2093 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002094 }
2095
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002096 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002097 * Update rules that might be changed by {@link #mRestrictBackground},
2098 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002099 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002100 void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002101 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002102
Dianne Hackborn497175b2014-07-01 12:56:08 -07002103 // If we are in restrict power mode, we allow all important apps
2104 // to have data access. Otherwise, we restrict data access to only
2105 // the top apps.
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002106 mCurForegroundState = (!mRestrictBackground && mRestrictPower)
Dianne Hackbornd69e4c12015-04-24 09:54:54 -07002107 ? ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
Dianne Hackborn497175b2014-07-01 12:56:08 -07002108 : ActivityManager.PROCESS_STATE_TOP;
2109
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002110 updateRulesForDeviceIdleLocked();
2111
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002112 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002113 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002114 final List<ApplicationInfo> apps = pm.getInstalledApplications(
2115 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
2116
2117 for (UserInfo user : users) {
2118 for (ApplicationInfo app : apps) {
2119 final int uid = UserHandle.getUid(user.id, app.uid);
2120 updateRulesForUidLocked(uid);
2121 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002122 }
2123
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002124 // limit data usage for some internal system services
2125 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
2126 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002127
2128 // If the set of restricted networks may have changed, re-evaluate those.
2129 if (restrictedNetworksChanged) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002130 normalizePoliciesLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002131 updateNetworkRulesLocked();
2132 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002133 }
2134
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002135 void updateRulesForTempWhitelistChangeLocked() {
2136 final List<UserInfo> users = mUserManager.getUsers();
2137 for (UserInfo user : users) {
2138 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
2139 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
Xiaohui Chenc915eeb2015-06-26 16:20:48 -07002140 boolean isAllow = mPowerSaveTempWhitelistAppIds.valueAt(i);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002141 int uid = UserHandle.getUid(user.id, appId);
2142 updateRulesForUidLocked(uid);
Xiaohui Chenc915eeb2015-06-26 16:20:48 -07002143 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, !isAllow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002144 }
2145 }
2146 }
2147
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002148 private static boolean isUidValidForRules(int uid) {
2149 // allow rules on specific system services, and any apps
2150 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002151 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002152 return true;
2153 }
2154
2155 return false;
2156 }
2157
Amith Yamasani15e472352015-04-24 19:06:07 -07002158 private boolean isUidIdle(int uid) {
2159 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2160 final int userId = UserHandle.getUserId(uid);
2161
2162 for (String packageName : packages) {
2163 if (!mUsageStats.isAppIdle(packageName, userId)) {
2164 return false;
2165 }
2166 }
2167 return true;
2168 }
2169
2170 /**
2171 * Applies network rules to bandwidth and firewall controllers based on uid policy.
2172 * @param uid The uid for which to apply the latest policy
2173 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002174 void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002175 if (!isUidValidForRules(uid)) return;
2176
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002177 // quick check: if this uid doesn't have INTERNET permission, it doesn't have
2178 // network access anyway, so it is a waste to mess with it here.
2179 final IPackageManager ipm = AppGlobals.getPackageManager();
2180 try {
2181 if (ipm.checkUidPermission(Manifest.permission.INTERNET, uid)
2182 != PackageManager.PERMISSION_GRANTED) {
2183 return;
2184 }
2185 } catch (RemoteException e) {
2186 }
2187
Dianne Hackborn497175b2014-07-01 12:56:08 -07002188 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2189 final boolean uidForeground = isUidForegroundLocked(uid);
Amith Yamasani15e472352015-04-24 19:06:07 -07002190 final boolean uidIdle = isUidIdle(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002191
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002192 // derive active rules based on policy and active state
Amith Yamasani15e472352015-04-24 19:06:07 -07002193
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002194 int appId = UserHandle.getAppId(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002195 int uidRules = RULE_ALLOW_ALL;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002196 if (uidIdle && !mPowerSaveWhitelistAppIds.get(appId)
2197 && !mPowerSaveTempWhitelistAppIds.get(appId)) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002198 uidRules = RULE_REJECT_ALL;
2199 } else if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002200 // uid in background, and policy says to block metered data
2201 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002202 } else if (mRestrictBackground) {
2203 if (!uidForeground) {
2204 // uid in background, and global background disabled
2205 uidRules = RULE_REJECT_METERED;
2206 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002207 } else if (mRestrictPower) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002208 final boolean whitelisted = mPowerSaveWhitelistAppIds.get(appId)
2209 || mPowerSaveTempWhitelistAppIds.get(appId);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002210 if (!whitelisted && !uidForeground
2211 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
2212 // uid is in background, restrict power use mode is on (so we want to
2213 // restrict all background network access), and this uid is not on the
2214 // white list of those allowed background access.
2215 uidRules = RULE_REJECT_METERED;
2216 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002217 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002218
Amith Yamasani15e472352015-04-24 19:06:07 -07002219 final int oldRules = mUidRules.get(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002220
Jeff Sharkey350083e2011-06-29 10:45:16 -07002221 if (uidRules == RULE_ALLOW_ALL) {
2222 mUidRules.delete(uid);
2223 } else {
2224 mUidRules.put(uid, uidRules);
2225 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002226
Amith Yamasani15e472352015-04-24 19:06:07 -07002227 // Update bandwidth rules if necessary
2228 final boolean oldRejectMetered = (oldRules & RULE_REJECT_METERED) != 0;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002229 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Amith Yamasani15e472352015-04-24 19:06:07 -07002230 if (oldRejectMetered != rejectMetered) {
2231 setUidNetworkRules(uid, rejectMetered);
2232 }
2233
2234 // Update firewall rules if necessary
2235 final boolean oldFirewallReject = (oldRules & RULE_REJECT_ALL) != 0;
2236 final boolean firewallReject = (uidRules & RULE_REJECT_ALL) != 0;
2237 if (oldFirewallReject != firewallReject) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002238 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, firewallReject);
Amith Yamasani15e472352015-04-24 19:06:07 -07002239 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002240
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002241 // dispatch changed rule to existing listeners
Amith Yamasani15e472352015-04-24 19:06:07 -07002242 if (oldRules != uidRules) {
2243 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
2244 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002245
2246 try {
2247 // adjust stats accounting based on foreground status
2248 mNetworkStats.setUidForeground(uid, uidForeground);
2249 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002250 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002251 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002252 }
2253
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002254 private class AppIdleStateChangeListener
2255 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2256
2257 @Override
2258 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2259 try {
2260 int uid = mContext.getPackageManager().getPackageUid(packageName, userId);
2261 synchronized (mRulesLock) {
2262 updateRulesForUidLocked(uid);
2263 }
2264 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002265 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002266 }
2267
2268 @Override
2269 public void onParoleStateChanged(boolean isParoleOn) {
2270 synchronized (mRulesLock) {
2271 updateRulesForAppIdleParoleLocked();
2272 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002273 }
2274 }
2275
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002276 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002277 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002278 public boolean handleMessage(Message msg) {
2279 switch (msg.what) {
2280 case MSG_RULES_CHANGED: {
2281 final int uid = msg.arg1;
2282 final int uidRules = msg.arg2;
2283 final int length = mListeners.beginBroadcast();
2284 for (int i = 0; i < length; i++) {
2285 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2286 if (listener != null) {
2287 try {
2288 listener.onUidRulesChanged(uid, uidRules);
2289 } catch (RemoteException e) {
2290 }
2291 }
2292 }
2293 mListeners.finishBroadcast();
2294 return true;
2295 }
2296 case MSG_METERED_IFACES_CHANGED: {
2297 final String[] meteredIfaces = (String[]) msg.obj;
2298 final int length = mListeners.beginBroadcast();
2299 for (int i = 0; i < length; i++) {
2300 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2301 if (listener != null) {
2302 try {
2303 listener.onMeteredIfacesChanged(meteredIfaces);
2304 } catch (RemoteException e) {
2305 }
2306 }
2307 }
2308 mListeners.finishBroadcast();
2309 return true;
2310 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002311 case MSG_LIMIT_REACHED: {
2312 final String iface = (String) msg.obj;
2313
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002314 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002315 synchronized (mRulesLock) {
2316 if (mMeteredIfaces.contains(iface)) {
2317 try {
2318 // force stats update to make sure we have
2319 // numbers that caused alert to trigger.
2320 mNetworkStats.forceUpdate();
2321 } catch (RemoteException e) {
2322 // ignored; service lives in system_server
2323 }
2324
2325 updateNetworkEnabledLocked();
2326 updateNotificationsLocked();
2327 }
2328 }
2329 return true;
2330 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002331 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2332 final boolean restrictBackground = msg.arg1 != 0;
2333 final int length = mListeners.beginBroadcast();
2334 for (int i = 0; i < length; i++) {
2335 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2336 if (listener != null) {
2337 try {
2338 listener.onRestrictBackgroundChanged(restrictBackground);
2339 } catch (RemoteException e) {
2340 }
2341 }
2342 }
2343 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002344 return true;
2345 }
2346 case MSG_ADVISE_PERSIST_THRESHOLD: {
2347 final long lowestRule = (Long) msg.obj;
2348 try {
2349 // make sure stats are recorded frequently enough; we aim
2350 // for 2MB threshold for 2GB/month rules.
2351 final long persistThreshold = lowestRule / 1000;
2352 mNetworkStats.advisePersistThreshold(persistThreshold);
2353 } catch (RemoteException e) {
2354 // ignored; service lives in system_server
2355 }
2356 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002357 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002358 case MSG_SCREEN_ON_CHANGED: {
2359 updateScreenOn();
2360 return true;
2361 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002362 default: {
2363 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002364 }
2365 }
2366 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002367 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002368
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002369 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002370 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002371 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002372 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002373 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002374 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002375 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002376 }
2377 }
2378
2379 private void removeInterfaceQuota(String iface) {
2380 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002381 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002382 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002383 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002384 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002385 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002386 }
2387 }
2388
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002389 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2390 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002391 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002392 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002393 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002394 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002395 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002396 }
2397 }
2398
Amith Yamasani15e472352015-04-24 19:06:07 -07002399 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002400 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
2401 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
2402 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07002403 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002404 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002405 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002406 int size = uidRules.size();
2407 int[] uids = new int[size];
2408 int[] rules = new int[size];
2409 for(int index = size - 1; index >= 0; --index) {
2410 uids[index] = uidRules.keyAt(index);
2411 rules[index] = uidRules.valueAt(index);
2412 }
2413 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002414 } catch (IllegalStateException e) {
2415 Log.wtf(TAG, "problem setting firewall uid rules", e);
2416 } catch (RemoteException e) {
2417 // ignored; service lives in system_server
2418 }
2419 }
2420
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002421 /**
2422 * Add or remove a uid to the firewall blacklist for all network ifaces.
2423 */
2424 private void setUidFirewallRule(int chain, int uid, boolean rejectOnAll) {
2425 try {
2426 mNetworkManager.setFirewallUidRule(chain, uid,
2427 rejectOnAll ? FIREWALL_RULE_DENY : FIREWALL_RULE_ALLOW);
2428 } catch (IllegalStateException e) {
2429 Log.wtf(TAG, "problem setting firewall uid rules", e);
2430 } catch (RemoteException e) {
2431 // ignored; service lives in system_server
2432 }
2433 }
2434
2435 /**
2436 * Add or remove a uid to the firewall blacklist for all network ifaces.
2437 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002438 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002439 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
2440 mFirewallChainStates.get(chain) == enable) {
2441 // All is the same, nothing to do.
2442 return;
2443 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002444 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002445 try {
2446 mNetworkManager.setFirewallChainEnabled(chain, enable);
2447 } catch (IllegalStateException e) {
2448 Log.wtf(TAG, "problem enable firewall chain", e);
2449 } catch (RemoteException e) {
2450 // ignored; service lives in system_server
2451 }
2452 }
2453
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002454 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2455 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002456 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002457 } catch (RuntimeException e) {
2458 Slog.w(TAG, "problem reading network stats: " + e);
2459 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002460 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002461 // ignored; service lives in system_server
2462 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002463 }
2464 }
2465
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002466 private boolean isBandwidthControlEnabled() {
2467 final long token = Binder.clearCallingIdentity();
2468 try {
2469 return mNetworkManager.isBandwidthControlEnabled();
2470 } catch (RemoteException e) {
2471 // ignored; service lives in system_server
2472 return false;
2473 } finally {
2474 Binder.restoreCallingIdentity(token);
2475 }
2476 }
2477
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002478 /**
2479 * Try refreshing {@link #mTime} when stale.
2480 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002481 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002482 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002483 mTime.forceRefresh();
2484 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002485 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002486
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002487 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002488 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2489 }
2490
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002491 private static Intent buildAllowBackgroundDataIntent() {
2492 return new Intent(ACTION_ALLOW_BACKGROUND);
2493 }
2494
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002495 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2496 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2497 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2498 return intent;
2499 }
2500
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002501 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2502 final Intent intent = new Intent();
2503 intent.setComponent(new ComponentName(
2504 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2505 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2506 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2507 return intent;
2508 }
2509
2510 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2511 final Intent intent = new Intent();
2512 intent.setComponent(new ComponentName(
2513 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2514 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2515 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2516 return intent;
2517 }
2518
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002519 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002520 public void addIdleHandler(IdleHandler handler) {
2521 mHandler.getLooper().getQueue().addIdleHandler(handler);
2522 }
2523
Jeff Sharkey1b861272011-05-22 00:34:52 -07002524 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2525 final int size = source.size();
2526 for (int i = 0; i < size; i++) {
2527 target.put(source.keyAt(i), true);
2528 }
2529 }
2530
Stuart Scottf1fb3972015-04-02 18:00:02 -07002531 @Override
2532 public void factoryReset(String subscriber) {
2533 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2534
Stuart Scotte3e314d2015-04-20 14:07:45 -07002535 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
2536 return;
2537 }
2538
Stuart Scottf1fb3972015-04-02 18:00:02 -07002539 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07002540 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07002541 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
2542 for (NetworkPolicy policy : policies) {
2543 if (policy.template.equals(template)) {
2544 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2545 policy.inferred = false;
2546 policy.clearSnooze();
2547 }
2548 }
2549 setNetworkPolicies(policies);
2550
2551 // Turn restrict background data off
2552 setRestrictBackground(false);
2553
Stuart Scotte3e314d2015-04-20 14:07:45 -07002554 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
2555 // Remove app's "restrict background data" flag
2556 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
2557 setUidPolicy(uid, POLICY_NONE);
2558 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07002559 }
2560 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002561}