blob: 395aa275f412bb9267aa5e0cba7ad1b874e7347e [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) {
1523 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1524 if (oldPolicy != policy) {
1525 setUidPolicyUncheckedLocked(uid, policy, true);
1526 }
1527 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001528 }
1529
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001530 @Override
1531 public void addUidPolicy(int uid, int policy) {
1532 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001533
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001534 if (!UserHandle.isApp(uid)) {
1535 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1536 }
1537
1538 synchronized (mRulesLock) {
1539 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1540 policy |= oldPolicy;
1541 if (oldPolicy != policy) {
1542 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001543 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001544 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001545 }
1546
1547 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001548 public void removeUidPolicy(int uid, int policy) {
1549 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1550
1551 if (!UserHandle.isApp(uid)) {
1552 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1553 }
1554
1555 synchronized (mRulesLock) {
1556 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1557 policy = oldPolicy & ~policy;
1558 if (oldPolicy != policy) {
1559 setUidPolicyUncheckedLocked(uid, policy, true);
1560 }
1561 }
1562 }
1563
1564 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1565 mUidPolicy.put(uid, policy);
1566
1567 // uid policy changed, recompute rules and persist policy.
1568 updateRulesForUidLocked(uid);
1569 if (persist) {
1570 writePolicyLocked();
1571 }
1572 }
1573
1574 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001575 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001576 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1577
Jeff Sharkeya4620792011-05-20 15:29:23 -07001578 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001579 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001580 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001581 }
1582
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001583 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001584 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001585 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1586
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001587 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001588 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001589 for (int i = 0; i < mUidPolicy.size(); i++) {
1590 final int uid = mUidPolicy.keyAt(i);
1591 final int uidPolicy = mUidPolicy.valueAt(i);
1592 if (uidPolicy == policy) {
1593 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001594 }
1595 }
1596 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001597 return uids;
1598 }
1599
1600 /**
1601 * Remove any policies associated with given {@link UserHandle}, persisting
1602 * if any changes are made.
1603 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001604 void removePoliciesForUserLocked(int userId) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001605 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1606
1607 int[] uids = new int[0];
1608 for (int i = 0; i < mUidPolicy.size(); i++) {
1609 final int uid = mUidPolicy.keyAt(i);
1610 if (UserHandle.getUserId(uid) == userId) {
1611 uids = appendInt(uids, uid);
1612 }
1613 }
1614
1615 if (uids.length > 0) {
1616 for (int uid : uids) {
1617 mUidPolicy.delete(uid);
1618 updateRulesForUidLocked(uid);
1619 }
1620 writePolicyLocked();
1621 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001622 }
1623
1624 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001625 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001626 // TODO: create permission for observing network policy
1627 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1628
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001629 mListeners.register(listener);
1630
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001631 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001632 }
1633
1634 @Override
1635 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001636 // TODO: create permission for observing network policy
1637 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1638
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001639 mListeners.unregister(listener);
1640 }
1641
Jeff Sharkey1b861272011-05-22 00:34:52 -07001642 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001643 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001644 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1645
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001646 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001647 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001648 normalizePoliciesLocked(policies);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001649 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001650 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001651 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001652 writePolicyLocked();
1653 }
1654 }
1655
Dianne Hackborn497175b2014-07-01 12:56:08 -07001656 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001657 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001658 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1659 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001660 }
1661
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001662 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001663 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001664 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001665 try {
1666 mContext.enforceCallingPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1667 // SKIP checking run-time OP_READ_PHONE_STATE since using PRIVILEGED
1668 } catch (SecurityException e) {
1669 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001670
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001671 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1672 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1673 return new NetworkPolicy[0];
1674 }
Svet Ganov16a16892015-04-16 10:32:04 -07001675 }
1676
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001677 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001678 final int size = mNetworkPolicy.size();
1679 final NetworkPolicy[] policies = new NetworkPolicy[size];
1680 for (int i = 0; i < size; i++) {
1681 policies[i] = mNetworkPolicy.valueAt(i);
1682 }
1683 return policies;
1684 }
1685 }
1686
1687 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001688 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001689 }
1690
1691 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1692 final TelephonyManager tele = TelephonyManager.from(mContext);
1693 final String[] merged = tele.getMergedSubscriberIds();
1694
1695 mNetworkPolicy.clear();
1696 for (NetworkPolicy policy : policies) {
1697 // When two normalized templates conflict, prefer the most
1698 // restrictive policy
1699 policy.template = NetworkTemplate.normalize(policy.template, merged);
1700 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1701 if (existing == null || existing.compareTo(policy) > 0) {
1702 if (existing != null) {
1703 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1704 }
1705 mNetworkPolicy.put(policy.template, policy);
1706 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001707 }
1708 }
1709
1710 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001711 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001712 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001713
1714 final long token = Binder.clearCallingIdentity();
1715 try {
1716 performSnooze(template, TYPE_LIMIT);
1717 } finally {
1718 Binder.restoreCallingIdentity(token);
1719 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001720 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001721
Dianne Hackborn497175b2014-07-01 12:56:08 -07001722 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001723 maybeRefreshTrustedTime();
1724 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001725 synchronized (mRulesLock) {
1726 // find and snooze local policy that matches
1727 final NetworkPolicy policy = mNetworkPolicy.get(template);
1728 if (policy == null) {
1729 throw new IllegalArgumentException("unable to find policy for " + template);
1730 }
1731
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001732 switch (type) {
1733 case TYPE_WARNING:
1734 policy.lastWarningSnooze = currentTime;
1735 break;
1736 case TYPE_LIMIT:
1737 policy.lastLimitSnooze = currentTime;
1738 break;
1739 default:
1740 throw new IllegalArgumentException("unexpected type");
1741 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001742
Jeff Sharkey32566012014-12-02 18:30:14 -08001743 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001744 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001745 updateNetworkRulesLocked();
1746 updateNotificationsLocked();
1747 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001748 }
1749 }
1750
1751 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001752 public void setRestrictBackground(boolean restrictBackground) {
1753 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1754
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001755 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001756 synchronized (mRulesLock) {
1757 mRestrictBackground = restrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001758 updateRulesForGlobalChangeLocked(false);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001759 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001760 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001761 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001762
1763 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1764 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001765 }
1766
1767 @Override
1768 public boolean getRestrictBackground() {
1769 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1770
1771 synchronized (mRulesLock) {
1772 return mRestrictBackground;
1773 }
1774 }
1775
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001776 @Override
1777 public void setDeviceIdleMode(boolean enabled) {
1778 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1779
1780 synchronized (mRulesLock) {
1781 if (mDeviceIdleMode != enabled) {
1782 mDeviceIdleMode = enabled;
1783 if (mSystemReady) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001784 updateRulesForDeviceIdleLocked();
1785 }
1786 if (enabled) {
1787 EventLogTags.writeDeviceIdleOnPhase("net");
1788 } else {
1789 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001790 }
1791 }
1792 }
1793 }
1794
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001795 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001796 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1797 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001798 if (policy.template.matches(ident)) {
1799 return policy;
1800 }
1801 }
1802 return null;
1803 }
1804
1805 @Override
1806 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1807 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1808
1809 // only returns usage summary, so we don't require caller to have
1810 // READ_NETWORK_USAGE_HISTORY.
1811 final long token = Binder.clearCallingIdentity();
1812 try {
1813 return getNetworkQuotaInfoUnchecked(state);
1814 } finally {
1815 Binder.restoreCallingIdentity(token);
1816 }
1817 }
1818
1819 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1820 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1821
1822 final NetworkPolicy policy;
1823 synchronized (mRulesLock) {
1824 policy = findPolicyForNetworkLocked(ident);
1825 }
1826
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001827 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001828 // missing policy means we can't derive useful quota info
1829 return null;
1830 }
1831
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001832 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001833
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001834 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001835 final long start = computeLastCycleBoundary(currentTime, policy);
1836 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001837 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001838
1839 // report soft and hard limits under policy
1840 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1841 : NetworkQuotaInfo.NO_LIMIT;
1842 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1843 : NetworkQuotaInfo.NO_LIMIT;
1844
1845 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1846 }
1847
Jeff Sharkey46645002011-07-27 21:11:21 -07001848 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001849 public boolean isNetworkMetered(NetworkState state) {
1850 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1851
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001852 // roaming networks are always considered metered
1853 if (ident.getRoaming()) {
1854 return true;
1855 }
1856
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001857 final NetworkPolicy policy;
1858 synchronized (mRulesLock) {
1859 policy = findPolicyForNetworkLocked(ident);
1860 }
1861
1862 if (policy != null) {
1863 return policy.metered;
1864 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001865 final int type = state.networkInfo.getType();
1866 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1867 return true;
1868 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001869 return false;
1870 }
1871 }
1872
1873 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001874 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001875 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001876
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001877 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1878
Dianne Hackborn497175b2014-07-01 12:56:08 -07001879 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001880 for (String arg : args) {
1881 argSet.add(arg);
1882 }
1883
Jeff Sharkey1b861272011-05-22 00:34:52 -07001884 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001885 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001886 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1887 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001888 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001889
Jeff Sharkey32566012014-12-02 18:30:14 -08001890 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001891 updateNetworkEnabledLocked();
1892 updateNetworkRulesLocked();
1893 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001894 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001895
1896 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001897 return;
1898 }
1899
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001900 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07001901 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001902 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001903 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001904 fout.print("Current foreground state: "); fout.println(mCurForegroundState);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001905 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001906 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001907 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1908 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001909 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001910 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001911
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001912 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
1913
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001914 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001915 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001916 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001917 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001918 final int uid = mUidPolicy.keyAt(i);
1919 final int policy = mUidPolicy.valueAt(i);
1920 fout.print("UID=");
1921 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001922 fout.print(" policy=");
1923 dumpPolicy(fout, policy);
1924 fout.println();
1925 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001926 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001927
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001928 size = mPowerSaveWhitelistAppIds.size();
1929 if (size > 0) {
1930 fout.println("Power save whitelist app ids:");
1931 fout.increaseIndent();
1932 for (int i = 0; i < size; i++) {
1933 fout.print("UID=");
1934 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
1935 fout.print(": ");
1936 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
1937 fout.println();
1938 }
1939 fout.decreaseIndent();
1940 }
1941
Jeff Sharkey1b861272011-05-22 00:34:52 -07001942 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07001943 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001944 collectKeys(mUidRules, knownUids);
1945
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001946 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001947 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001948 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001949 for (int i = 0; i < size; i++) {
1950 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001951 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001952 fout.print(uid);
1953
Dianne Hackborn497175b2014-07-01 12:56:08 -07001954 int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1955 fout.print(" state=");
1956 fout.print(state);
1957 fout.print(state <= mCurForegroundState ? " (fg)" : " (bg)");
1958
Jeff Sharkey1b861272011-05-22 00:34:52 -07001959 fout.print(" rules=");
1960 final int rulesIndex = mUidRules.indexOfKey(uid);
1961 if (rulesIndex < 0) {
1962 fout.print("UNKNOWN");
1963 } else {
1964 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1965 }
1966
1967 fout.println();
1968 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001969 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001970 }
1971 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001972
1973 @Override
1974 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001975 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1976
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001977 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001978 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001979 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001980 }
1981
Dianne Hackborn497175b2014-07-01 12:56:08 -07001982 boolean isUidForegroundLocked(int uid) {
1983 // only really in foreground when screen is also on
1984 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
1985 <= mCurForegroundState;
1986 }
1987
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001988 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07001989 * Process state of UID changed; if needed, will trigger
1990 * {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001991 */
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07001992 void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001993 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1994 if (oldUidState != uidState) {
1995 // state changed, push updated rules
1996 mUidState.put(uid, uidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07001997 updateRulesForUidStateChangeLocked(uid, oldUidState, uidState);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001998 if (mDeviceIdleMode && isProcStateAllowedWhileIdle(oldUidState)
1999 != isProcStateAllowedWhileIdle(uidState)) {
2000 updateRulesForDeviceIdleLocked();
2001 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002002 }
2003 }
2004
2005 void removeUidStateLocked(int uid) {
2006 final int index = mUidState.indexOfKey(uid);
2007 if (index >= 0) {
2008 final int oldUidState = mUidState.valueAt(index);
2009 mUidState.removeAt(index);
2010 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
2011 updateRulesForUidStateChangeLocked(uid, oldUidState,
2012 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002013 if (mDeviceIdleMode) {
2014 updateRulesForDeviceIdleLocked();
2015 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002016 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002017 }
2018 }
2019
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002020 void updateRulesForUidStateChangeLocked(int uid, int oldUidState, int newUidState) {
2021 final boolean oldForeground = oldUidState <= mCurForegroundState;
2022 final boolean newForeground = newUidState <= mCurForegroundState;
2023 if (oldForeground != newForeground) {
2024 updateRulesForUidLocked(uid);
2025 }
2026 }
2027
Jeff Sharkeya4620792011-05-20 15:29:23 -07002028 private void updateScreenOn() {
2029 synchronized (mRulesLock) {
2030 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002031 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002032 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002033 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002034 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002035 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002036 }
2037 }
2038
2039 /**
2040 * Update rules that might be changed by {@link #mScreenOn} value.
2041 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002042 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002043 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002044 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002045 for (int i = 0; i < size; i++) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002046 if (mUidState.valueAt(i) <= mCurForegroundState) {
2047 final int uid = mUidState.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002048 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002049 }
2050 }
2051 }
2052
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002053 static boolean isProcStateAllowedWhileIdle(int procState) {
2054 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2055 }
2056
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002057 void updateRulesForDeviceIdleLocked() {
2058 if (mDeviceIdleMode) {
2059 // sync the whitelists before enable dozable chain. We don't care about the rules if
2060 // we are disabling the chain.
2061 SparseIntArray uidRules = new SparseIntArray();
2062 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002063 for (int ui = users.size() - 1; ui >= 0; ui--) {
2064 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002065 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
2066 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2067 int uid = UserHandle.getUid(user.id, appId);
2068 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2069 }
2070 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2071 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2072 int uid = UserHandle.getUid(user.id, appId);
2073 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2074 }
2075 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002076 for (int i = mUidState.size() - 1; i >= 0; i--) {
2077 if (isProcStateAllowedWhileIdle(mUidState.valueAt(i))) {
2078 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2079 }
2080 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002081 setUidFirewallRules(FIREWALL_CHAIN_DOZABLE, uidRules);
2082 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002083 enableFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, mDeviceIdleMode);
2084 }
2085
2086 void updateRulesForAppIdleParoleLocked() {
2087 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2088 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002089 }
2090
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002091 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002092 * Update rules that might be changed by {@link #mRestrictBackground},
2093 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002094 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002095 void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002096 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002097
Dianne Hackborn497175b2014-07-01 12:56:08 -07002098 // If we are in restrict power mode, we allow all important apps
2099 // to have data access. Otherwise, we restrict data access to only
2100 // the top apps.
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002101 mCurForegroundState = (!mRestrictBackground && mRestrictPower)
Dianne Hackbornd69e4c12015-04-24 09:54:54 -07002102 ? ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
Dianne Hackborn497175b2014-07-01 12:56:08 -07002103 : ActivityManager.PROCESS_STATE_TOP;
2104
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002105 updateRulesForDeviceIdleLocked();
2106
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002107 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002108 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002109 final List<ApplicationInfo> apps = pm.getInstalledApplications(
2110 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
2111
2112 for (UserInfo user : users) {
2113 for (ApplicationInfo app : apps) {
2114 final int uid = UserHandle.getUid(user.id, app.uid);
2115 updateRulesForUidLocked(uid);
2116 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002117 }
2118
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002119 // limit data usage for some internal system services
2120 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
2121 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002122
2123 // If the set of restricted networks may have changed, re-evaluate those.
2124 if (restrictedNetworksChanged) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002125 normalizePoliciesLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002126 updateNetworkRulesLocked();
2127 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002128 }
2129
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002130 void updateRulesForTempWhitelistChangeLocked() {
2131 final List<UserInfo> users = mUserManager.getUsers();
2132 for (UserInfo user : users) {
2133 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
2134 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
Xiaohui Chenc915eeb2015-06-26 16:20:48 -07002135 boolean isAllow = mPowerSaveTempWhitelistAppIds.valueAt(i);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002136 int uid = UserHandle.getUid(user.id, appId);
2137 updateRulesForUidLocked(uid);
Xiaohui Chenc915eeb2015-06-26 16:20:48 -07002138 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, !isAllow);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002139 }
2140 }
2141 }
2142
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002143 private static boolean isUidValidForRules(int uid) {
2144 // allow rules on specific system services, and any apps
2145 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002146 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002147 return true;
2148 }
2149
2150 return false;
2151 }
2152
Amith Yamasani15e472352015-04-24 19:06:07 -07002153 private boolean isUidIdle(int uid) {
2154 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2155 final int userId = UserHandle.getUserId(uid);
2156
2157 for (String packageName : packages) {
2158 if (!mUsageStats.isAppIdle(packageName, userId)) {
2159 return false;
2160 }
2161 }
2162 return true;
2163 }
2164
2165 /**
2166 * Applies network rules to bandwidth and firewall controllers based on uid policy.
2167 * @param uid The uid for which to apply the latest policy
2168 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002169 void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002170 if (!isUidValidForRules(uid)) return;
2171
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002172 // quick check: if this uid doesn't have INTERNET permission, it doesn't have
2173 // network access anyway, so it is a waste to mess with it here.
2174 final IPackageManager ipm = AppGlobals.getPackageManager();
2175 try {
2176 if (ipm.checkUidPermission(Manifest.permission.INTERNET, uid)
2177 != PackageManager.PERMISSION_GRANTED) {
2178 return;
2179 }
2180 } catch (RemoteException e) {
2181 }
2182
Dianne Hackborn497175b2014-07-01 12:56:08 -07002183 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2184 final boolean uidForeground = isUidForegroundLocked(uid);
Amith Yamasani15e472352015-04-24 19:06:07 -07002185 final boolean uidIdle = isUidIdle(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002186
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002187 // derive active rules based on policy and active state
Amith Yamasani15e472352015-04-24 19:06:07 -07002188
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002189 int appId = UserHandle.getAppId(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002190 int uidRules = RULE_ALLOW_ALL;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002191 if (uidIdle && !mPowerSaveWhitelistAppIds.get(appId)
2192 && !mPowerSaveTempWhitelistAppIds.get(appId)) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002193 uidRules = RULE_REJECT_ALL;
2194 } else if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002195 // uid in background, and policy says to block metered data
2196 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002197 } else if (mRestrictBackground) {
2198 if (!uidForeground) {
2199 // uid in background, and global background disabled
2200 uidRules = RULE_REJECT_METERED;
2201 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002202 } else if (mRestrictPower) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002203 final boolean whitelisted = mPowerSaveWhitelistAppIds.get(appId)
2204 || mPowerSaveTempWhitelistAppIds.get(appId);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002205 if (!whitelisted && !uidForeground
2206 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
2207 // uid is in background, restrict power use mode is on (so we want to
2208 // restrict all background network access), and this uid is not on the
2209 // white list of those allowed background access.
2210 uidRules = RULE_REJECT_METERED;
2211 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002212 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002213
Amith Yamasani15e472352015-04-24 19:06:07 -07002214 final int oldRules = mUidRules.get(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002215
Jeff Sharkey350083e2011-06-29 10:45:16 -07002216 if (uidRules == RULE_ALLOW_ALL) {
2217 mUidRules.delete(uid);
2218 } else {
2219 mUidRules.put(uid, uidRules);
2220 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002221
Amith Yamasani15e472352015-04-24 19:06:07 -07002222 // Update bandwidth rules if necessary
2223 final boolean oldRejectMetered = (oldRules & RULE_REJECT_METERED) != 0;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002224 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Amith Yamasani15e472352015-04-24 19:06:07 -07002225 if (oldRejectMetered != rejectMetered) {
2226 setUidNetworkRules(uid, rejectMetered);
2227 }
2228
2229 // Update firewall rules if necessary
2230 final boolean oldFirewallReject = (oldRules & RULE_REJECT_ALL) != 0;
2231 final boolean firewallReject = (uidRules & RULE_REJECT_ALL) != 0;
2232 if (oldFirewallReject != firewallReject) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002233 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, firewallReject);
Amith Yamasani15e472352015-04-24 19:06:07 -07002234 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002235
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002236 // dispatch changed rule to existing listeners
Amith Yamasani15e472352015-04-24 19:06:07 -07002237 if (oldRules != uidRules) {
2238 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
2239 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002240
2241 try {
2242 // adjust stats accounting based on foreground status
2243 mNetworkStats.setUidForeground(uid, uidForeground);
2244 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002245 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002246 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002247 }
2248
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002249 private class AppIdleStateChangeListener
2250 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2251
2252 @Override
2253 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2254 try {
2255 int uid = mContext.getPackageManager().getPackageUid(packageName, userId);
2256 synchronized (mRulesLock) {
2257 updateRulesForUidLocked(uid);
2258 }
2259 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002260 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002261 }
2262
2263 @Override
2264 public void onParoleStateChanged(boolean isParoleOn) {
2265 synchronized (mRulesLock) {
2266 updateRulesForAppIdleParoleLocked();
2267 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002268 }
2269 }
2270
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002271 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002272 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002273 public boolean handleMessage(Message msg) {
2274 switch (msg.what) {
2275 case MSG_RULES_CHANGED: {
2276 final int uid = msg.arg1;
2277 final int uidRules = msg.arg2;
2278 final int length = mListeners.beginBroadcast();
2279 for (int i = 0; i < length; i++) {
2280 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2281 if (listener != null) {
2282 try {
2283 listener.onUidRulesChanged(uid, uidRules);
2284 } catch (RemoteException e) {
2285 }
2286 }
2287 }
2288 mListeners.finishBroadcast();
2289 return true;
2290 }
2291 case MSG_METERED_IFACES_CHANGED: {
2292 final String[] meteredIfaces = (String[]) msg.obj;
2293 final int length = mListeners.beginBroadcast();
2294 for (int i = 0; i < length; i++) {
2295 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2296 if (listener != null) {
2297 try {
2298 listener.onMeteredIfacesChanged(meteredIfaces);
2299 } catch (RemoteException e) {
2300 }
2301 }
2302 }
2303 mListeners.finishBroadcast();
2304 return true;
2305 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002306 case MSG_LIMIT_REACHED: {
2307 final String iface = (String) msg.obj;
2308
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002309 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002310 synchronized (mRulesLock) {
2311 if (mMeteredIfaces.contains(iface)) {
2312 try {
2313 // force stats update to make sure we have
2314 // numbers that caused alert to trigger.
2315 mNetworkStats.forceUpdate();
2316 } catch (RemoteException e) {
2317 // ignored; service lives in system_server
2318 }
2319
2320 updateNetworkEnabledLocked();
2321 updateNotificationsLocked();
2322 }
2323 }
2324 return true;
2325 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002326 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2327 final boolean restrictBackground = msg.arg1 != 0;
2328 final int length = mListeners.beginBroadcast();
2329 for (int i = 0; i < length; i++) {
2330 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2331 if (listener != null) {
2332 try {
2333 listener.onRestrictBackgroundChanged(restrictBackground);
2334 } catch (RemoteException e) {
2335 }
2336 }
2337 }
2338 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002339 return true;
2340 }
2341 case MSG_ADVISE_PERSIST_THRESHOLD: {
2342 final long lowestRule = (Long) msg.obj;
2343 try {
2344 // make sure stats are recorded frequently enough; we aim
2345 // for 2MB threshold for 2GB/month rules.
2346 final long persistThreshold = lowestRule / 1000;
2347 mNetworkStats.advisePersistThreshold(persistThreshold);
2348 } catch (RemoteException e) {
2349 // ignored; service lives in system_server
2350 }
2351 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002352 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002353 case MSG_SCREEN_ON_CHANGED: {
2354 updateScreenOn();
2355 return true;
2356 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002357 default: {
2358 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002359 }
2360 }
2361 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002362 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002363
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002364 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002365 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002366 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002367 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002368 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002369 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002370 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002371 }
2372 }
2373
2374 private void removeInterfaceQuota(String iface) {
2375 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002376 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002377 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002378 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002379 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002380 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002381 }
2382 }
2383
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002384 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2385 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002386 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002387 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002388 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002389 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002390 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002391 }
2392 }
2393
Amith Yamasani15e472352015-04-24 19:06:07 -07002394 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002395 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
2396 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
2397 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07002398 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002399 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002400 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002401 int size = uidRules.size();
2402 int[] uids = new int[size];
2403 int[] rules = new int[size];
2404 for(int index = size - 1; index >= 0; --index) {
2405 uids[index] = uidRules.keyAt(index);
2406 rules[index] = uidRules.valueAt(index);
2407 }
2408 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002409 } catch (IllegalStateException e) {
2410 Log.wtf(TAG, "problem setting firewall uid rules", e);
2411 } catch (RemoteException e) {
2412 // ignored; service lives in system_server
2413 }
2414 }
2415
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002416 /**
2417 * Add or remove a uid to the firewall blacklist for all network ifaces.
2418 */
2419 private void setUidFirewallRule(int chain, int uid, boolean rejectOnAll) {
2420 try {
2421 mNetworkManager.setFirewallUidRule(chain, uid,
2422 rejectOnAll ? FIREWALL_RULE_DENY : FIREWALL_RULE_ALLOW);
2423 } catch (IllegalStateException e) {
2424 Log.wtf(TAG, "problem setting firewall uid rules", e);
2425 } catch (RemoteException e) {
2426 // ignored; service lives in system_server
2427 }
2428 }
2429
2430 /**
2431 * Add or remove a uid to the firewall blacklist for all network ifaces.
2432 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002433 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002434 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
2435 mFirewallChainStates.get(chain) == enable) {
2436 // All is the same, nothing to do.
2437 return;
2438 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002439 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002440 try {
2441 mNetworkManager.setFirewallChainEnabled(chain, enable);
2442 } catch (IllegalStateException e) {
2443 Log.wtf(TAG, "problem enable firewall chain", e);
2444 } catch (RemoteException e) {
2445 // ignored; service lives in system_server
2446 }
2447 }
2448
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002449 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2450 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002451 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002452 } catch (RuntimeException e) {
2453 Slog.w(TAG, "problem reading network stats: " + e);
2454 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002455 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002456 // ignored; service lives in system_server
2457 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002458 }
2459 }
2460
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002461 private boolean isBandwidthControlEnabled() {
2462 final long token = Binder.clearCallingIdentity();
2463 try {
2464 return mNetworkManager.isBandwidthControlEnabled();
2465 } catch (RemoteException e) {
2466 // ignored; service lives in system_server
2467 return false;
2468 } finally {
2469 Binder.restoreCallingIdentity(token);
2470 }
2471 }
2472
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002473 /**
2474 * Try refreshing {@link #mTime} when stale.
2475 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002476 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002477 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002478 mTime.forceRefresh();
2479 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002480 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002481
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002482 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002483 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2484 }
2485
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002486 private static Intent buildAllowBackgroundDataIntent() {
2487 return new Intent(ACTION_ALLOW_BACKGROUND);
2488 }
2489
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002490 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2491 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2492 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2493 return intent;
2494 }
2495
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002496 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2497 final Intent intent = new Intent();
2498 intent.setComponent(new ComponentName(
2499 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2500 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2501 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2502 return intent;
2503 }
2504
2505 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2506 final Intent intent = new Intent();
2507 intent.setComponent(new ComponentName(
2508 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2509 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2510 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2511 return intent;
2512 }
2513
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002514 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002515 public void addIdleHandler(IdleHandler handler) {
2516 mHandler.getLooper().getQueue().addIdleHandler(handler);
2517 }
2518
Jeff Sharkey1b861272011-05-22 00:34:52 -07002519 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2520 final int size = source.size();
2521 for (int i = 0; i < size; i++) {
2522 target.put(source.keyAt(i), true);
2523 }
2524 }
2525
Stuart Scottf1fb3972015-04-02 18:00:02 -07002526 @Override
2527 public void factoryReset(String subscriber) {
2528 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2529
Stuart Scotte3e314d2015-04-20 14:07:45 -07002530 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
2531 return;
2532 }
2533
Stuart Scottf1fb3972015-04-02 18:00:02 -07002534 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07002535 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07002536 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
2537 for (NetworkPolicy policy : policies) {
2538 if (policy.template.equals(template)) {
2539 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2540 policy.inferred = false;
2541 policy.clearSnooze();
2542 }
2543 }
2544 setNetworkPolicies(policies);
2545
2546 // Turn restrict background data off
2547 setRestrictBackground(false);
2548
Stuart Scotte3e314d2015-04-20 14:07:45 -07002549 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
2550 // Remove app's "restrict background data" flag
2551 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
2552 setUidPolicy(uid, POLICY_NONE);
2553 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07002554 }
2555 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002556}