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