blob: 39914897a2a134b13c15c5079226e43cf8e1ee04 [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;
Dianne Hackborn4a503b12015-08-06 22:19:06 -070042import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Amith Yamasani15e472352015-04-24 19:06:07 -070044import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -070045import static android.net.NetworkPolicyManager.POLICY_ALLOW_BACKGROUND_BATTERY_SAVE;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070046import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070047import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070048import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070049import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
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();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700282
Jeff Sharkey32566012014-12-02 18:30:14 -0800283 /**
284 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700285 * in power save mode, except device idle (doze) still applies.
286 * TODO: An int array might be sufficient
287 */
288 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
289
290 /**
291 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800292 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700293 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800294 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700295 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700296
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700297 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
298
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700299 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800300 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700301 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800302 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700303
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700304 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700305 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700306
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700307 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800308 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700309
Jeff Sharkey32566012014-12-02 18:30:14 -0800310 private final RemoteCallbackList<INetworkPolicyListener>
311 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700312
Dianne Hackborn497175b2014-07-01 12:56:08 -0700313 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700314
315 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700316
Svet Ganov16a16892015-04-16 10:32:04 -0700317 private final AppOpsManager mAppOps;
318
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700319 // TODO: keep whitelist of system-critical services that should never have
320 // rules enforced, such as system, phone, and radio UIDs.
321
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700322 // TODO: migrate notifications to SystemUI
323
Jeff Sharkey75279902011-05-24 18:39:45 -0700324 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700325 IPowerManager powerManager, INetworkStatsService networkStats,
326 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700327 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700328 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700329 }
330
331 private static File getSystemDir() {
332 return new File(Environment.getDataDirectory(), "system");
333 }
334
335 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700336 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700337 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
338 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700339 mContext = checkNotNull(context, "missing context");
340 mActivityManager = checkNotNull(activityManager, "missing activityManager");
341 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700342 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700343 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700344 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700345 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700346 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700347 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700348
Amith Yamasani450a16b2013-09-18 16:28:50 -0700349 HandlerThread thread = new HandlerThread(TAG);
350 thread.start();
351 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700352
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700353 mSuppressDefaultPolicy = suppressDefaultPolicy;
354
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700355 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700356
357 mAppOps = context.getSystemService(AppOpsManager.class);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700358 }
359
360 public void bindConnectivityManager(IConnectivityManager connManager) {
361 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700362 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700363
Jeff Sharkey497e4432011-06-14 17:27:29 -0700364 public void bindNotificationManager(INotificationManager notifManager) {
365 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
366 }
367
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700368 void updatePowerSaveWhitelistLocked() {
369 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700370 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
371 mPowerSaveWhitelistExceptIdleAppIds.clear();
372 if (whitelist != null) {
373 for (int uid : whitelist) {
374 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
375 }
376 }
377 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700378 mPowerSaveWhitelistAppIds.clear();
379 if (whitelist != null) {
380 for (int uid : whitelist) {
381 mPowerSaveWhitelistAppIds.put(uid, true);
382 }
383 }
384 } catch (RemoteException e) {
385 }
386 }
387
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700388 void updatePowerSaveTempWhitelistLocked() {
389 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700390 // Clear the states of the current whitelist
391 final int N = mPowerSaveTempWhitelistAppIds.size();
392 for (int i = 0; i < N; i++) {
393 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
394 }
395 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700396 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700397 if (whitelist != null) {
398 for (int uid : whitelist) {
399 mPowerSaveTempWhitelistAppIds.put(uid, true);
400 }
401 }
402 } catch (RemoteException e) {
403 }
404 }
405
Amith Yamasani06f08062015-06-12 13:23:33 -0700406 /**
407 * Remove unnecessary entries in the temp whitelist
408 */
409 void purgePowerSaveTempWhitelistLocked() {
410 final int N = mPowerSaveTempWhitelistAppIds.size();
411 for (int i = N - 1; i >= 0; i--) {
412 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
413 mPowerSaveTempWhitelistAppIds.removeAt(i);
414 }
415 }
416 }
417
Jeff Sharkeya4620792011-05-20 15:29:23 -0700418 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700419 if (!isBandwidthControlEnabled()) {
420 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
421 return;
422 }
423
Amith Yamasani15e472352015-04-24 19:06:07 -0700424 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
425
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700426 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700427 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700428 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
429 mPowerManagerInternal.registerLowPowerModeObserver(
430 new PowerManagerInternal.LowPowerModeListener() {
431 @Override
432 public void onLowPowerModeChanged(boolean enabled) {
433 synchronized (mRulesLock) {
434 if (mRestrictPower != enabled) {
435 mRestrictPower = enabled;
436 updateRulesForGlobalChangeLocked(true);
437 }
438 }
439 }
440 });
441 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700442 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700443
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700444 // read policy from disk
445 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700446
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700447 if (mRestrictBackground || mRestrictPower || mDeviceIdleMode) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700448 updateRulesForGlobalChangeLocked(false);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700449 updateNotificationsLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700450 } else {
451 // If we are not in any special mode, we just need to make sure the current
452 // app idle state is updated.
453 updateRulesForAppIdleLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700454 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700455 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700456
Jeff Sharkeya4620792011-05-20 15:29:23 -0700457 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700458
Jeff Sharkeya4620792011-05-20 15:29:23 -0700459 try {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700460 mActivityManager.registerUidObserver(mUidObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700461 mNetworkManager.registerObserver(mAlertObserver);
462 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700463 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700464 }
465
Jeff Sharkeya4620792011-05-20 15:29:23 -0700466 // TODO: traverse existing processes to know foreground state, or have
467 // activitymanager dispatch current state when new observer attached.
468
469 final IntentFilter screenFilter = new IntentFilter();
470 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
471 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700472 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700473
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700474 // listen for changes to power save whitelist
475 final IntentFilter whitelistFilter = new IntentFilter(
476 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
477 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
478
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700479 DeviceIdleController.LocalService deviceIdleService
480 = LocalServices.getService(DeviceIdleController.LocalService.class);
481 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
482
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700483 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900484 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700485 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
486
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700487 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700488 final IntentFilter packageFilter = new IntentFilter();
489 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700490 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700491 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700492
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700493 // listen for UID changes to update policy
494 mContext.registerReceiver(
495 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
496
497 // listen for user changes to update policy
498 final IntentFilter userFilter = new IntentFilter();
499 userFilter.addAction(ACTION_USER_ADDED);
500 userFilter.addAction(ACTION_USER_REMOVED);
501 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
502
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700503 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700504 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
505 mContext.registerReceiver(
506 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
507
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700508 // listen for restrict background changes from notifications
509 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
510 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
511
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800512 // listen for snooze warning from notifications
513 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
514 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
515 MANAGE_NETWORK_POLICY, mHandler);
516
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700517 // listen for configured wifi networks to be removed
518 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700519 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700520
521 // listen for wifi state changes to catch metered hint
522 final IntentFilter wifiStateFilter = new IntentFilter(
523 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700524 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700525
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700526 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700527
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700528 }
529
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700530 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700531 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700532 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700533 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700534 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700535 }
536
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700537 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700538 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700539 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700540 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700541 }
542 };
543
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700544 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700545 @Override
546 public void onReceive(Context context, Intent intent) {
547 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
548 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700549 updatePowerSaveWhitelistLocked();
550 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700551 }
552 }
553 };
554
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700555 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
556 @Override
557 public void run() {
558 synchronized (mRulesLock) {
559 updatePowerSaveTempWhitelistLocked();
560 updateRulesForTempWhitelistChangeLocked();
561 purgePowerSaveTempWhitelistLocked();
562 }
563 }
564 };
565
566 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700567 @Override
568 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800569 // screen-related broadcasts are protected by system, no need
570 // for permissions check.
571 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700572 }
573 };
574
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700575 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700576 @Override
577 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700578 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700579
580 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700581 final int uid = intent.getIntExtra(EXTRA_UID, -1);
582 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700583
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700584 if (ACTION_PACKAGE_ADDED.equals(action)) {
585 // update rules for UID, since it might be subject to
586 // global background data policy
587 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
588 synchronized (mRulesLock) {
589 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700590 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700591 }
592 }
593 };
594
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700595 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700596 @Override
597 public void onReceive(Context context, Intent intent) {
598 // on background handler thread, and UID_REMOVED is protected
599
600 final int uid = intent.getIntExtra(EXTRA_UID, -1);
601 if (uid == -1) return;
602
603 // remove any policy and update rules to clean up
604 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
605 synchronized (mRulesLock) {
606 mUidPolicy.delete(uid);
607 updateRulesForUidLocked(uid);
608 writePolicyLocked();
609 }
610 }
611 };
612
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700613 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700614 @Override
615 public void onReceive(Context context, Intent intent) {
616 // on background handler thread, and USER_ADDED and USER_REMOVED
617 // broadcasts are protected
618
619 final String action = intent.getAction();
620 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
621 if (userId == -1) return;
622
Amith Yamasani15e472352015-04-24 19:06:07 -0700623 switch (action) {
624 case ACTION_USER_REMOVED:
625 case ACTION_USER_ADDED:
626 synchronized (mRulesLock) {
627 // Remove any policies for given user; both cleaning up after a
628 // USER_REMOVED, and one last sanity check during USER_ADDED
629 removePoliciesForUserLocked(userId);
630 // Update global restrict for new user
631 updateRulesForGlobalChangeLocked(true);
632 }
633 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700634 }
635 }
636 };
637
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700638 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700639 * Receiver that watches for {@link INetworkStatsService} updates, which we
640 * use to check against {@link NetworkPolicy#warningBytes}.
641 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700642 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700643 @Override
644 public void onReceive(Context context, Intent intent) {
645 // on background handler thread, and verified
646 // READ_NETWORK_USAGE_HISTORY permission above.
647
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800648 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700649 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700650 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700651 updateNotificationsLocked();
652 }
653 }
654 };
655
656 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700657 * Receiver that watches for {@link Notification} control of
658 * {@link #mRestrictBackground}.
659 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700660 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700661 @Override
662 public void onReceive(Context context, Intent intent) {
663 // on background handler thread, and verified MANAGE_NETWORK_POLICY
664 // permission above.
665
666 setRestrictBackground(false);
667 }
668 };
669
670 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800671 * Receiver that watches for {@link Notification} control of
672 * {@link NetworkPolicy#lastWarningSnooze}.
673 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700674 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800675 @Override
676 public void onReceive(Context context, Intent intent) {
677 // on background handler thread, and verified MANAGE_NETWORK_POLICY
678 // permission above.
679
680 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
681 performSnooze(template, TYPE_WARNING);
682 }
683 };
684
685 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700686 * Receiver that watches for {@link WifiConfiguration} to be changed.
687 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700688 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700689 @Override
690 public void onReceive(Context context, Intent intent) {
691 // on background handler thread, and verified CONNECTIVITY_INTERNAL
692 // permission above.
693
694 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
695 if (reason == CHANGE_REASON_REMOVED) {
696 final WifiConfiguration config = intent.getParcelableExtra(
697 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700698 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800699 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700700 synchronized (mRulesLock) {
701 if (mNetworkPolicy.containsKey(template)) {
702 mNetworkPolicy.remove(template);
703 writePolicyLocked();
704 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700705 }
706 }
707 }
708 }
709 };
710
711 /**
712 * Receiver that watches {@link WifiInfo} state changes to infer metered
713 * state. Ignores hints when policy is user-defined.
714 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700715 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700716 @Override
717 public void onReceive(Context context, Intent intent) {
718 // on background handler thread, and verified CONNECTIVITY_INTERNAL
719 // permission above.
720
721 // ignore when not connected
722 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
723 if (!netInfo.isConnected()) return;
724
725 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
726 final boolean meteredHint = info.getMeteredHint();
727
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800728 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700729 synchronized (mRulesLock) {
730 NetworkPolicy policy = mNetworkPolicy.get(template);
731 if (policy == null && meteredHint) {
732 // policy doesn't exist, and AP is hinting that it's
733 // metered: create an inferred policy.
734 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
735 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
736 meteredHint, true);
737 addNetworkPolicyLocked(policy);
738
739 } else if (policy != null && policy.inferred) {
740 // policy exists, and was inferred: update its current
741 // metered state.
742 policy.metered = meteredHint;
743
744 // since this is inferred for each wifi session, just update
745 // rules without persisting.
746 updateNetworkRulesLocked();
747 }
748 }
749 }
750 };
751
752 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700753 * Observer that watches for {@link INetworkManagementService} alerts.
754 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700755 final private INetworkManagementEventObserver mAlertObserver
756 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700757 @Override
758 public void limitReached(String limitName, String iface) {
759 // only someone like NMS should be calling us
760 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
761
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800762 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
763 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700764 }
765 }
766 };
767
768 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700769 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
770 * to show visible notifications as needed.
771 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700772 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700773 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
774
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700775 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700776 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700777 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700778
779 // TODO: when switching to kernel notifications, compute next future
780 // cycle boundary to recompute notifications.
781
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700782 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800783 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700784 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
785 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700786 // ignore policies that aren't relevant to user
787 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700788 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700789
Jeff Sharkey497e4432011-06-14 17:27:29 -0700790 final long start = computeLastCycleBoundary(currentTime, policy);
791 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700792 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700793
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700794 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800795 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700796 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
797 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700798 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
799 notifyOverLimitLocked(policy.template);
800 }
801
Jeff Sharkey497e4432011-06-14 17:27:29 -0700802 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700803 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700804
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800805 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700806 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700807 }
808 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700809 }
810
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700811 // ongoing notification when restricting background data
812 if (mRestrictBackground) {
813 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700814 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700815
816 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700817 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
818 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700819 if (!mActiveNotifs.contains(tag)) {
820 cancelNotification(tag);
821 }
822 }
823 }
824
825 /**
826 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700827 * current device state, such as when
828 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
829 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700830 */
831 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800832 if (template.isMatchRuleMobile()) {
833 final TelephonyManager tele = TelephonyManager.from(mContext);
834 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700835
Jeff Sharkey32566012014-12-02 18:30:14 -0800836 // Mobile template is relevant when any active subscriber matches
837 final int[] subIds = sub.getActiveSubscriptionIdList();
838 for (int subId : subIds) {
839 final String subscriberId = tele.getSubscriberId(subId);
840 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
841 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
842 if (template.matches(probeIdent)) {
843 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700844 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800845 }
846 return false;
847 } else {
848 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700849 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700850 }
851
852 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700853 * Notify that given {@link NetworkTemplate} is over
854 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
855 */
856 private void notifyOverLimitLocked(NetworkTemplate template) {
857 if (!mOverLimitNotified.contains(template)) {
858 mContext.startActivity(buildNetworkOverLimitIntent(template));
859 mOverLimitNotified.add(template);
860 }
861 }
862
863 private void notifyUnderLimitLocked(NetworkTemplate template) {
864 mOverLimitNotified.remove(template);
865 }
866
867 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700868 * Build unique tag that identifies an active {@link NetworkPolicy}
869 * notification of a specific type, like {@link #TYPE_LIMIT}.
870 */
871 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700872 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700873 }
874
875 /**
876 * Show notification for combined {@link NetworkPolicy} and specific type,
877 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
878 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700879 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700880 final String tag = buildNotificationTag(policy, type);
881 final Notification.Builder builder = new Notification.Builder(mContext);
882 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800883 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700884 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200885 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700886
887 final Resources res = mContext.getResources();
888 switch (type) {
889 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700890 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700891 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700892
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700893 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700894 builder.setTicker(title);
895 builder.setContentTitle(title);
896 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700897
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800898 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
899 builder.setDeleteIntent(PendingIntent.getBroadcast(
900 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
901
902 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700903 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800904 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
905
Jeff Sharkey497e4432011-06-14 17:27:29 -0700906 break;
907 }
908 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700909 final CharSequence body = res.getText(R.string.data_usage_limit_body);
910
911 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -0400912 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700913 switch (policy.template.getMatchRule()) {
914 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700915 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700916 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700917 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700918 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700919 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700920 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700921 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700922 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700923 case MATCH_WIFI:
924 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -0400925 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700926 break;
927 default:
928 title = null;
929 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700930 }
931
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800932 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -0400933 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700934 builder.setTicker(title);
935 builder.setContentTitle(title);
936 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700937
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700938 final Intent intent = buildNetworkOverLimitIntent(policy.template);
939 builder.setContentIntent(PendingIntent.getActivity(
940 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
941 break;
942 }
943 case TYPE_LIMIT_SNOOZED: {
944 final long overBytes = totalBytes - policy.limitBytes;
945 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
946 Formatter.formatFileSize(mContext, overBytes));
947
948 final CharSequence title;
949 switch (policy.template.getMatchRule()) {
950 case MATCH_MOBILE_3G_LOWER:
951 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
952 break;
953 case MATCH_MOBILE_4G:
954 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
955 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700956 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700957 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
958 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700959 case MATCH_WIFI:
960 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
961 break;
962 default:
963 title = null;
964 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700965 }
966
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800967 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700968 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700969 builder.setTicker(title);
970 builder.setContentTitle(title);
971 builder.setContentText(body);
972
973 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700974 builder.setContentIntent(PendingIntent.getActivity(
975 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700976 break;
977 }
978 }
979
980 // TODO: move to NotificationManager once we can mock it
981 try {
982 final String packageName = mContext.getPackageName();
983 final int[] idReceived = new int[1];
984 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800985 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -0700986 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700987 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700988 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700989 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700990 }
991 }
992
993 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700994 * Show ongoing notification to reflect that {@link #mRestrictBackground}
995 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700996 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700997 private void enqueueRestrictedNotification(String tag) {
998 final Resources res = mContext.getResources();
999 final Notification.Builder builder = new Notification.Builder(mContext);
1000
1001 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
1002 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
1003
1004 builder.setOnlyAlertOnce(true);
1005 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001006 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001007 builder.setTicker(title);
1008 builder.setContentTitle(title);
1009 builder.setContentText(body);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001010 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001011 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001012
1013 final Intent intent = buildAllowBackgroundDataIntent();
1014 builder.setContentIntent(
1015 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001016
1017 // TODO: move to NotificationManager once we can mock it
1018 try {
1019 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001020 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001021 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001022 0x0, builder.getNotification(), idReceived, UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001023 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001024 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001025 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001026 }
1027 }
1028
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001029 private void cancelNotification(String tag) {
1030 // TODO: move to NotificationManager once we can mock it
1031 try {
1032 final String packageName = mContext.getPackageName();
1033 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001034 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001035 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001036 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001037 }
1038 }
1039
1040 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001041 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001042 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001043 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001044 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001045 @Override
1046 public void onReceive(Context context, Intent intent) {
1047 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1048 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001049
1050 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001051 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001052 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001053 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001054 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001055 updateNetworkRulesLocked();
1056 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001057 }
1058 }
1059 };
1060
1061 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001062 * Proactively control network data connections when they exceed
1063 * {@link NetworkPolicy#limitBytes}.
1064 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001065 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001066 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1067
1068 // TODO: reset any policy-disabled networks when any policy is removed
1069 // completely, which is currently rare case.
1070
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001071 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001072 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1073 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001074 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001075 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001076 setNetworkTemplateEnabled(policy.template, true);
1077 continue;
1078 }
1079
1080 final long start = computeLastCycleBoundary(currentTime, policy);
1081 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001082 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001083
1084 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001085 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1086 && policy.lastLimitSnooze < start;
1087 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001088
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001089 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001090 }
1091 }
1092
1093 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001094 * Proactively disable networks that match the given
1095 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001096 */
1097 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001098 // TODO: reach into ConnectivityManager to proactively disable bringing
1099 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001100 }
1101
1102 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001103 * Examine all connected {@link NetworkState}, looking for
1104 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1105 * remaining quota based on usage cycle and historical stats.
1106 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001107 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001108 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001109
1110 final NetworkState[] states;
1111 try {
1112 states = mConnManager.getAllNetworkState();
1113 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001114 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001115 return;
1116 }
1117
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001118 // If we are in restrict power mode, we want to treat all interfaces
1119 // as metered, to restrict access to the network by uid. However, we
1120 // will not have a bandwidth limit. Also only do this if restrict
1121 // background data use is *not* enabled, since that takes precendence
1122 // use over those networks can have a cost associated with it).
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001123 final boolean powerSave = mRestrictPower && !mRestrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001124
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001125 // First, generate identities of all connected networks so we can
1126 // quickly compare them against all defined policies below.
1127 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001128 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001129 for (NetworkState state : states) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001130 if (state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001131 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001132
1133 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001134 if (baseIface != null) {
1135 connIdents.add(Pair.create(baseIface, ident));
1136 if (powerSave) {
1137 connIfaces.add(baseIface);
1138 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001139 }
1140
1141 // Stacked interfaces are considered to have same identity as
1142 // their parent network.
1143 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1144 for (LinkProperties stackedLink : stackedLinks) {
1145 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001146 if (stackedIface != null) {
1147 connIdents.add(Pair.create(stackedIface, ident));
1148 if (powerSave) {
1149 connIfaces.add(stackedIface);
1150 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001151 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001152 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001153 }
1154 }
1155
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001156 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001157 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001158 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001159 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001160 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001161
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001162 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001163 for (int j = connIdents.size() - 1; j >= 0; j--) {
1164 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1165 if (policy.template.matches(ident.second)) {
1166 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001167 }
1168 }
1169
1170 if (ifaceList.size() > 0) {
1171 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001172 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001173 }
1174 }
1175
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001176 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001177 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001178
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001179 // apply each policy that we found ifaces for; compute remaining data
1180 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001181 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001182 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1183 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1184 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001185
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001186 final long start;
1187 final long totalBytes;
1188 if (policy.hasCycle()) {
1189 start = computeLastCycleBoundary(currentTime, policy);
1190 totalBytes = getTotalBytes(policy.template, start, currentTime);
1191 } else {
1192 start = Long.MAX_VALUE;
1193 totalBytes = 0;
1194 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001195
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001196 if (LOGD) {
1197 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001198 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001199 }
1200
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001201 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001202 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001203 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001204 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001205 if (!hasLimit) {
1206 // metered network, but no policy limit; we still need to
1207 // restrict apps, so push really high quota.
1208 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001209 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001210 // snoozing past quota, but we still need to restrict apps,
1211 // so push really high quota.
1212 quotaBytes = Long.MAX_VALUE;
1213 } else {
1214 // remaining "quota" bytes are based on total usage in
1215 // current cycle. kernel doesn't like 0-byte rules, so we
1216 // set 1-byte quota and disable the radio later.
1217 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1218 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001219
1220 if (ifaces.length > 1) {
1221 // TODO: switch to shared quota once NMS supports
1222 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001223 }
1224
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001225 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001226 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001227 setInterfaceQuota(iface, quotaBytes);
1228 newMeteredIfaces.add(iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001229 if (powerSave) {
1230 connIfaces.remove(iface);
1231 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001232 }
1233 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001234
1235 // keep track of lowest warning or limit of active policies
1236 if (hasWarning && policy.warningBytes < lowestRule) {
1237 lowestRule = policy.warningBytes;
1238 }
1239 if (hasLimit && policy.limitBytes < lowestRule) {
1240 lowestRule = policy.limitBytes;
1241 }
1242 }
1243
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001244 for (int i = connIfaces.size()-1; i >= 0; i--) {
1245 String iface = connIfaces.valueAt(i);
1246 removeInterfaceQuota(iface);
1247 setInterfaceQuota(iface, Long.MAX_VALUE);
1248 newMeteredIfaces.add(iface);
1249 }
1250
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001251 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001252
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001253 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001254 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1255 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001256 if (!newMeteredIfaces.contains(iface)) {
1257 removeInterfaceQuota(iface);
1258 }
1259 }
1260 mMeteredIfaces = newMeteredIfaces;
1261
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001262 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001263 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001264 }
1265
1266 /**
1267 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1268 * have at least a default mobile policy defined.
1269 */
1270 private void ensureActiveMobilePolicyLocked() {
1271 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001272 if (mSuppressDefaultPolicy) return;
1273
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001274 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001275 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001276
Jeff Sharkey32566012014-12-02 18:30:14 -08001277 final int[] subIds = sub.getActiveSubscriptionIdList();
1278 for (int subId : subIds) {
1279 final String subscriberId = tele.getSubscriberId(subId);
1280 ensureActiveMobilePolicyLocked(subscriberId);
1281 }
1282 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001283
Jeff Sharkey32566012014-12-02 18:30:14 -08001284 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1285 // Poke around to see if we already have a policy
1286 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1287 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1288 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1289 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1290 if (template.matches(probeIdent)) {
1291 if (LOGD) {
1292 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1293 + NetworkIdentity.scrubSubscriberId(subscriberId));
1294 }
1295 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001296 }
1297 }
1298
Jeff Sharkey32566012014-12-02 18:30:14 -08001299 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1300 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001301
Jeff Sharkey32566012014-12-02 18:30:14 -08001302 // Build default mobile policy, and assume usage cycle starts today
1303 final long warningBytes = mContext.getResources().getInteger(
1304 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001305
Jeff Sharkey32566012014-12-02 18:30:14 -08001306 final Time time = new Time();
1307 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001308
Jeff Sharkey32566012014-12-02 18:30:14 -08001309 final int cycleDay = time.monthDay;
1310 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001311
Jeff Sharkey32566012014-12-02 18:30:14 -08001312 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1313 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1314 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1315 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001316 }
1317
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001318 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001319 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001320
1321 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001322 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001323 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001324
1325 FileInputStream fis = null;
1326 try {
1327 fis = mPolicyFile.openRead();
1328 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001329 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001330
1331 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001332 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001333 while ((type = in.next()) != END_DOCUMENT) {
1334 final String tag = in.getName();
1335 if (type == START_TAG) {
1336 if (TAG_POLICY_LIST.equals(tag)) {
1337 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001338 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1339 mRestrictBackground = readBooleanAttribute(
1340 in, ATTR_RESTRICT_BACKGROUND);
1341 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001342 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001343 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001344
1345 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1346 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1347 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001348 final String networkId;
1349 if (version >= VERSION_ADDED_NETWORK_ID) {
1350 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1351 } else {
1352 networkId = null;
1353 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001354 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001355 final String cycleTimezone;
1356 if (version >= VERSION_ADDED_TIMEZONE) {
1357 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1358 } else {
1359 cycleTimezone = Time.TIMEZONE_UTC;
1360 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001361 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1362 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001363 final long lastLimitSnooze;
1364 if (version >= VERSION_SPLIT_SNOOZE) {
1365 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1366 } else if (version >= VERSION_ADDED_SNOOZE) {
1367 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001368 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001369 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001370 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001371 final boolean metered;
1372 if (version >= VERSION_ADDED_METERED) {
1373 metered = readBooleanAttribute(in, ATTR_METERED);
1374 } else {
1375 switch (networkTemplate) {
1376 case MATCH_MOBILE_3G_LOWER:
1377 case MATCH_MOBILE_4G:
1378 case MATCH_MOBILE_ALL:
1379 metered = true;
1380 break;
1381 default:
1382 metered = false;
1383 }
1384 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001385 final long lastWarningSnooze;
1386 if (version >= VERSION_SPLIT_SNOOZE) {
1387 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1388 } else {
1389 lastWarningSnooze = SNOOZE_NEVER;
1390 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001391 final boolean inferred;
1392 if (version >= VERSION_ADDED_INFERRED) {
1393 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1394 } else {
1395 inferred = false;
1396 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001397
Jeff Sharkey32566012014-12-02 18:30:14 -08001398 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1399 subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001400 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001401 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001402 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001403
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001404 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001405 final int uid = readIntAttribute(in, ATTR_UID);
1406 final int policy = readIntAttribute(in, ATTR_POLICY);
1407
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001408 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001409 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001410 } else {
1411 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1412 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001413 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001414 final int appId = readIntAttribute(in, ATTR_APP_ID);
1415 final int policy = readIntAttribute(in, ATTR_POLICY);
1416
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001417 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001418 // app policy is deprecated so this is only used in pre system user split.
1419 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001420 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001421 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001422 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001423 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001424 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001425 }
1426 }
1427 }
1428
1429 } catch (FileNotFoundException e) {
1430 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001431 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001432 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001433 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001434 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001435 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001436 } finally {
1437 IoUtils.closeQuietly(fis);
1438 }
1439 }
1440
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001441 /**
1442 * Upgrade legacy background data flags, notifying listeners of one last
1443 * change to always-true.
1444 */
1445 private void upgradeLegacyBackgroundData() {
1446 mRestrictBackground = Settings.Secure.getInt(
1447 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1448
1449 // kick off one last broadcast if restricted
1450 if (mRestrictBackground) {
1451 final Intent broadcast = new Intent(
1452 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001453 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001454 }
1455 }
1456
Dianne Hackborn497175b2014-07-01 12:56:08 -07001457 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001458 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001459
1460 FileOutputStream fos = null;
1461 try {
1462 fos = mPolicyFile.startWrite();
1463
1464 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001465 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001466 out.startDocument(null, true);
1467
1468 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001469 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001470 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001471
1472 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001473 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1474 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001475 final NetworkTemplate template = policy.template;
1476
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001477 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001478 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1479 final String subscriberId = template.getSubscriberId();
1480 if (subscriberId != null) {
1481 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001482 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001483 final String networkId = template.getNetworkId();
1484 if (networkId != null) {
1485 out.attribute(null, ATTR_NETWORK_ID, networkId);
1486 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001487 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001488 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001489 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1490 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001491 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1492 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001493 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001494 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001495 out.endTag(null, TAG_NETWORK_POLICY);
1496 }
1497
1498 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001499 for (int i = 0; i < mUidPolicy.size(); i++) {
1500 final int uid = mUidPolicy.keyAt(i);
1501 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001502
Jeff Sharkey497e4432011-06-14 17:27:29 -07001503 // skip writing empty policies
1504 if (policy == POLICY_NONE) continue;
1505
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001506 out.startTag(null, TAG_UID_POLICY);
1507 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001508 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001509 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001510 }
1511
1512 out.endTag(null, TAG_POLICY_LIST);
1513 out.endDocument();
1514
1515 mPolicyFile.finishWrite(fos);
1516 } catch (IOException e) {
1517 if (fos != null) {
1518 mPolicyFile.failWrite(fos);
1519 }
1520 }
1521 }
1522
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001523 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001524 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001525 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001526
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001527 if (!UserHandle.isApp(uid)) {
1528 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001529 }
1530
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001531 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001532 final long token = Binder.clearCallingIdentity();
1533 try {
1534 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1535 if (oldPolicy != policy) {
1536 setUidPolicyUncheckedLocked(uid, policy, true);
1537 }
1538 } finally {
1539 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001540 }
1541 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001542 }
1543
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001544 @Override
1545 public void addUidPolicy(int uid, int policy) {
1546 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001547
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001548 if (!UserHandle.isApp(uid)) {
1549 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1550 }
1551
1552 synchronized (mRulesLock) {
1553 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1554 policy |= oldPolicy;
1555 if (oldPolicy != policy) {
1556 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001557 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001558 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001559 }
1560
1561 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001562 public void removeUidPolicy(int uid, int policy) {
1563 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1564
1565 if (!UserHandle.isApp(uid)) {
1566 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1567 }
1568
1569 synchronized (mRulesLock) {
1570 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1571 policy = oldPolicy & ~policy;
1572 if (oldPolicy != policy) {
1573 setUidPolicyUncheckedLocked(uid, policy, true);
1574 }
1575 }
1576 }
1577
1578 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1579 mUidPolicy.put(uid, policy);
1580
1581 // uid policy changed, recompute rules and persist policy.
1582 updateRulesForUidLocked(uid);
1583 if (persist) {
1584 writePolicyLocked();
1585 }
1586 }
1587
1588 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001589 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001590 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1591
Jeff Sharkeya4620792011-05-20 15:29:23 -07001592 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001593 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001594 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001595 }
1596
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001597 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001598 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001599 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1600
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001601 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001602 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001603 for (int i = 0; i < mUidPolicy.size(); i++) {
1604 final int uid = mUidPolicy.keyAt(i);
1605 final int uidPolicy = mUidPolicy.valueAt(i);
1606 if (uidPolicy == policy) {
1607 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001608 }
1609 }
1610 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001611 return uids;
1612 }
1613
1614 /**
1615 * Remove any policies associated with given {@link UserHandle}, persisting
1616 * if any changes are made.
1617 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001618 void removePoliciesForUserLocked(int userId) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001619 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1620
1621 int[] uids = new int[0];
1622 for (int i = 0; i < mUidPolicy.size(); i++) {
1623 final int uid = mUidPolicy.keyAt(i);
1624 if (UserHandle.getUserId(uid) == userId) {
1625 uids = appendInt(uids, uid);
1626 }
1627 }
1628
1629 if (uids.length > 0) {
1630 for (int uid : uids) {
1631 mUidPolicy.delete(uid);
1632 updateRulesForUidLocked(uid);
1633 }
1634 writePolicyLocked();
1635 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001636 }
1637
1638 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001639 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001640 // TODO: create permission for observing network policy
1641 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1642
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001643 mListeners.register(listener);
1644
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001645 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001646 }
1647
1648 @Override
1649 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001650 // TODO: create permission for observing network policy
1651 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1652
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001653 mListeners.unregister(listener);
1654 }
1655
Jeff Sharkey1b861272011-05-22 00:34:52 -07001656 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001657 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001658 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1659
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001660 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001661 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001662 normalizePoliciesLocked(policies);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001663 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001664 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001665 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001666 writePolicyLocked();
1667 }
1668 }
1669
Dianne Hackborn497175b2014-07-01 12:56:08 -07001670 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001671 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001672 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1673 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001674 }
1675
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001676 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001677 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001678 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001679 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001680 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1681 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1682 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001683 } catch (SecurityException e) {
1684 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001685
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001686 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1687 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1688 return new NetworkPolicy[0];
1689 }
Svet Ganov16a16892015-04-16 10:32:04 -07001690 }
1691
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001692 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001693 final int size = mNetworkPolicy.size();
1694 final NetworkPolicy[] policies = new NetworkPolicy[size];
1695 for (int i = 0; i < size; i++) {
1696 policies[i] = mNetworkPolicy.valueAt(i);
1697 }
1698 return policies;
1699 }
1700 }
1701
1702 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001703 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001704 }
1705
1706 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1707 final TelephonyManager tele = TelephonyManager.from(mContext);
1708 final String[] merged = tele.getMergedSubscriberIds();
1709
1710 mNetworkPolicy.clear();
1711 for (NetworkPolicy policy : policies) {
1712 // When two normalized templates conflict, prefer the most
1713 // restrictive policy
1714 policy.template = NetworkTemplate.normalize(policy.template, merged);
1715 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1716 if (existing == null || existing.compareTo(policy) > 0) {
1717 if (existing != null) {
1718 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1719 }
1720 mNetworkPolicy.put(policy.template, policy);
1721 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001722 }
1723 }
1724
1725 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001726 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001727 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001728
1729 final long token = Binder.clearCallingIdentity();
1730 try {
1731 performSnooze(template, TYPE_LIMIT);
1732 } finally {
1733 Binder.restoreCallingIdentity(token);
1734 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001735 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001736
Dianne Hackborn497175b2014-07-01 12:56:08 -07001737 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001738 maybeRefreshTrustedTime();
1739 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001740 synchronized (mRulesLock) {
1741 // find and snooze local policy that matches
1742 final NetworkPolicy policy = mNetworkPolicy.get(template);
1743 if (policy == null) {
1744 throw new IllegalArgumentException("unable to find policy for " + template);
1745 }
1746
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001747 switch (type) {
1748 case TYPE_WARNING:
1749 policy.lastWarningSnooze = currentTime;
1750 break;
1751 case TYPE_LIMIT:
1752 policy.lastLimitSnooze = currentTime;
1753 break;
1754 default:
1755 throw new IllegalArgumentException("unexpected type");
1756 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001757
Jeff Sharkey32566012014-12-02 18:30:14 -08001758 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001759 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001760 updateNetworkRulesLocked();
1761 updateNotificationsLocked();
1762 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001763 }
1764 }
1765
1766 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001767 public void setRestrictBackground(boolean restrictBackground) {
1768 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1769
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001770 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001771 synchronized (mRulesLock) {
1772 mRestrictBackground = restrictBackground;
Jeff Sharkey9d142062015-08-12 16:46:05 -07001773 updateRulesForGlobalChangeLocked(true);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001774 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001775 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001776 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001777
1778 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1779 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001780 }
1781
1782 @Override
1783 public boolean getRestrictBackground() {
1784 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1785
1786 synchronized (mRulesLock) {
1787 return mRestrictBackground;
1788 }
1789 }
1790
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001791 @Override
1792 public void setDeviceIdleMode(boolean enabled) {
1793 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1794
1795 synchronized (mRulesLock) {
1796 if (mDeviceIdleMode != enabled) {
1797 mDeviceIdleMode = enabled;
1798 if (mSystemReady) {
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001799 updateRulesForDeviceIdleLocked();
1800 }
1801 if (enabled) {
1802 EventLogTags.writeDeviceIdleOnPhase("net");
1803 } else {
1804 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001805 }
1806 }
1807 }
1808 }
1809
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001810 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001811 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1812 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001813 if (policy.template.matches(ident)) {
1814 return policy;
1815 }
1816 }
1817 return null;
1818 }
1819
1820 @Override
1821 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1822 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1823
1824 // only returns usage summary, so we don't require caller to have
1825 // READ_NETWORK_USAGE_HISTORY.
1826 final long token = Binder.clearCallingIdentity();
1827 try {
1828 return getNetworkQuotaInfoUnchecked(state);
1829 } finally {
1830 Binder.restoreCallingIdentity(token);
1831 }
1832 }
1833
1834 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1835 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1836
1837 final NetworkPolicy policy;
1838 synchronized (mRulesLock) {
1839 policy = findPolicyForNetworkLocked(ident);
1840 }
1841
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001842 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001843 // missing policy means we can't derive useful quota info
1844 return null;
1845 }
1846
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001847 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001848
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001849 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001850 final long start = computeLastCycleBoundary(currentTime, policy);
1851 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001852 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001853
1854 // report soft and hard limits under policy
1855 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1856 : NetworkQuotaInfo.NO_LIMIT;
1857 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1858 : NetworkQuotaInfo.NO_LIMIT;
1859
1860 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1861 }
1862
Jeff Sharkey46645002011-07-27 21:11:21 -07001863 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001864 public boolean isNetworkMetered(NetworkState state) {
1865 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1866
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001867 // roaming networks are always considered metered
1868 if (ident.getRoaming()) {
1869 return true;
1870 }
1871
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001872 final NetworkPolicy policy;
1873 synchronized (mRulesLock) {
1874 policy = findPolicyForNetworkLocked(ident);
1875 }
1876
1877 if (policy != null) {
1878 return policy.metered;
1879 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001880 final int type = state.networkInfo.getType();
1881 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1882 return true;
1883 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001884 return false;
1885 }
1886 }
1887
1888 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001889 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001890 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001891
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001892 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1893
Dianne Hackborn497175b2014-07-01 12:56:08 -07001894 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001895 for (String arg : args) {
1896 argSet.add(arg);
1897 }
1898
Jeff Sharkey1b861272011-05-22 00:34:52 -07001899 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001900 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001901 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1902 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001903 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001904
Jeff Sharkey32566012014-12-02 18:30:14 -08001905 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001906 updateNetworkEnabledLocked();
1907 updateNetworkRulesLocked();
1908 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001909 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001910
1911 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001912 return;
1913 }
1914
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001915 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07001916 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001917 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001918 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001919 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001920 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001921 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1922 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001923 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001924 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001925
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001926 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
1927
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001928 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001929 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001930 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001931 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001932 final int uid = mUidPolicy.keyAt(i);
1933 final int policy = mUidPolicy.valueAt(i);
1934 fout.print("UID=");
1935 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001936 fout.print(" policy=");
1937 dumpPolicy(fout, policy);
1938 fout.println();
1939 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001940 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001941
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001942 size = mPowerSaveWhitelistExceptIdleAppIds.size();
1943 if (size > 0) {
1944 fout.println("Power save whitelist (except idle) app ids:");
1945 fout.increaseIndent();
1946 for (int i = 0; i < size; i++) {
1947 fout.print("UID=");
1948 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
1949 fout.print(": ");
1950 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
1951 fout.println();
1952 }
1953 fout.decreaseIndent();
1954 }
1955
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001956 size = mPowerSaveWhitelistAppIds.size();
1957 if (size > 0) {
1958 fout.println("Power save whitelist app ids:");
1959 fout.increaseIndent();
1960 for (int i = 0; i < size; i++) {
1961 fout.print("UID=");
1962 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
1963 fout.print(": ");
1964 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
1965 fout.println();
1966 }
1967 fout.decreaseIndent();
1968 }
1969
Jeff Sharkey1b861272011-05-22 00:34:52 -07001970 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07001971 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001972 collectKeys(mUidRules, knownUids);
1973
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001974 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001975 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001976 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001977 for (int i = 0; i < size; i++) {
1978 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001979 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001980 fout.print(uid);
1981
Dianne Hackborn497175b2014-07-01 12:56:08 -07001982 int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1983 fout.print(" state=");
1984 fout.print(state);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07001985 fout.print(state <= ActivityManager.PROCESS_STATE_TOP ? " (fg)" : " (bg)");
Dianne Hackborn497175b2014-07-01 12:56:08 -07001986
Jeff Sharkey1b861272011-05-22 00:34:52 -07001987 fout.print(" rules=");
1988 final int rulesIndex = mUidRules.indexOfKey(uid);
1989 if (rulesIndex < 0) {
1990 fout.print("UNKNOWN");
1991 } else {
1992 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1993 }
1994
1995 fout.println();
1996 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001997 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001998 }
1999 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002000
2001 @Override
2002 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002003 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2004
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002005 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002006 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002007 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002008 }
2009
Dianne Hackborn497175b2014-07-01 12:56:08 -07002010 boolean isUidForegroundLocked(int uid) {
2011 // only really in foreground when screen is also on
2012 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002013 <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002014 }
2015
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002016 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002017 * Process state of UID changed; if needed, will trigger
2018 * {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002019 */
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002020 void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002021 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2022 if (oldUidState != uidState) {
2023 // state changed, push updated rules
2024 mUidState.put(uid, uidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002025 updateRulesForUidStateChangeLocked(uid, oldUidState, uidState);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002026 if (mDeviceIdleMode && isProcStateAllowedWhileIdle(oldUidState)
2027 != isProcStateAllowedWhileIdle(uidState)) {
2028 updateRulesForDeviceIdleLocked();
2029 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002030 }
2031 }
2032
2033 void removeUidStateLocked(int uid) {
2034 final int index = mUidState.indexOfKey(uid);
2035 if (index >= 0) {
2036 final int oldUidState = mUidState.valueAt(index);
2037 mUidState.removeAt(index);
2038 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
2039 updateRulesForUidStateChangeLocked(uid, oldUidState,
2040 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002041 if (mDeviceIdleMode) {
2042 updateRulesForDeviceIdleLocked();
2043 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002044 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002045 }
2046 }
2047
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002048 void updateRulesForUidStateChangeLocked(int uid, int oldUidState, int newUidState) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002049 final boolean oldForeground = oldUidState <= ActivityManager.PROCESS_STATE_TOP;
2050 final boolean newForeground = newUidState <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002051 if (oldForeground != newForeground) {
2052 updateRulesForUidLocked(uid);
2053 }
2054 }
2055
Jeff Sharkeya4620792011-05-20 15:29:23 -07002056 private void updateScreenOn() {
2057 synchronized (mRulesLock) {
2058 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002059 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002060 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002061 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002062 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002063 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002064 }
2065 }
2066
2067 /**
2068 * Update rules that might be changed by {@link #mScreenOn} value.
2069 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002070 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002071 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002072 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002073 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002074 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002075 final int uid = mUidState.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002076 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002077 }
2078 }
2079 }
2080
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002081 static boolean isProcStateAllowedWhileIdle(int procState) {
2082 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2083 }
2084
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002085 void updateRulesForDeviceIdleLocked() {
2086 if (mDeviceIdleMode) {
2087 // sync the whitelists before enable dozable chain. We don't care about the rules if
2088 // we are disabling the chain.
2089 SparseIntArray uidRules = new SparseIntArray();
2090 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002091 for (int ui = users.size() - 1; ui >= 0; ui--) {
2092 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002093 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002094 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2095 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2096 int uid = UserHandle.getUid(user.id, appId);
2097 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2098 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002099 }
2100 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2101 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2102 int uid = UserHandle.getUid(user.id, appId);
2103 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2104 }
2105 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002106 for (int i = mUidState.size() - 1; i >= 0; i--) {
2107 if (isProcStateAllowedWhileIdle(mUidState.valueAt(i))) {
2108 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2109 }
2110 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002111 setUidFirewallRules(FIREWALL_CHAIN_DOZABLE, uidRules);
2112 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002113 enableFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, mDeviceIdleMode);
2114 }
2115
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002116 void updateRuleForDeviceIdleLocked(int uid) {
2117 if (mDeviceIdleMode) {
2118 int appId = UserHandle.getAppId(uid);
2119 if (mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId)
2120 || isProcStateAllowedWhileIdle(mUidState.get(uid))) {
2121 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_ALLOW);
2122 } else {
2123 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
2124 }
2125 }
2126 }
2127
2128 void updateRulesForAppIdleLocked() {
2129 // Fully update the app idle firewall chain.
2130 SparseIntArray uidRules = new SparseIntArray();
2131 final List<UserInfo> users = mUserManager.getUsers();
2132 for (int ui = users.size() - 1; ui >= 0; ui--) {
2133 UserInfo user = users.get(ui);
2134 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2135 for (int uid : idleUids) {
2136 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2137 uidRules.put(uid, FIREWALL_RULE_DENY);
2138 }
2139 }
2140 }
2141 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2142 }
2143
2144 void updateRuleForAppIdleLocked(int uid) {
2145 if (!isUidValidForRules(uid)) return;
2146
2147 int appId = UserHandle.getAppId(uid);
2148 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)) {
2149 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2150 } else {
2151 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2152 }
2153 }
2154
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002155 void updateRulesForAppIdleParoleLocked() {
2156 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2157 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002158 }
2159
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002160 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002161 * Update rules that might be changed by {@link #mRestrictBackground},
2162 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002163 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002164 void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002165 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002166
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002167 updateRulesForDeviceIdleLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002168 updateRulesForAppIdleLocked();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002169
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002170 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002171 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002172 final List<ApplicationInfo> apps = pm.getInstalledApplications(
2173 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
2174
2175 for (UserInfo user : users) {
2176 for (ApplicationInfo app : apps) {
2177 final int uid = UserHandle.getUid(user.id, app.uid);
2178 updateRulesForUidLocked(uid);
2179 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002180 }
2181
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002182 // limit data usage for some internal system services
2183 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
2184 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002185
2186 // If the set of restricted networks may have changed, re-evaluate those.
2187 if (restrictedNetworksChanged) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002188 normalizePoliciesLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002189 updateNetworkRulesLocked();
2190 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002191 }
2192
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002193 void updateRulesForTempWhitelistChangeLocked() {
2194 final List<UserInfo> users = mUserManager.getUsers();
2195 for (UserInfo user : users) {
2196 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
2197 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2198 int uid = UserHandle.getUid(user.id, appId);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002199 updateRuleForAppIdleLocked(uid);
2200 updateRuleForDeviceIdleLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002201 }
2202 }
2203 }
2204
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002205 private static boolean isUidValidForRules(int uid) {
2206 // allow rules on specific system services, and any apps
2207 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002208 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002209 return true;
2210 }
2211
2212 return false;
2213 }
2214
Amith Yamasani15e472352015-04-24 19:06:07 -07002215 private boolean isUidIdle(int uid) {
2216 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2217 final int userId = UserHandle.getUserId(uid);
2218
2219 for (String packageName : packages) {
2220 if (!mUsageStats.isAppIdle(packageName, userId)) {
2221 return false;
2222 }
2223 }
2224 return true;
2225 }
2226
2227 /**
2228 * Applies network rules to bandwidth and firewall controllers based on uid policy.
2229 * @param uid The uid for which to apply the latest policy
2230 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002231 void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002232 if (!isUidValidForRules(uid)) return;
2233
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002234 // quick check: if this uid doesn't have INTERNET permission, it doesn't have
2235 // network access anyway, so it is a waste to mess with it here.
2236 final IPackageManager ipm = AppGlobals.getPackageManager();
2237 try {
2238 if (ipm.checkUidPermission(Manifest.permission.INTERNET, uid)
2239 != PackageManager.PERMISSION_GRANTED) {
2240 return;
2241 }
2242 } catch (RemoteException e) {
2243 }
2244
Dianne Hackborn497175b2014-07-01 12:56:08 -07002245 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2246 final boolean uidForeground = isUidForegroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002247
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002248 // derive active rules based on policy and active state
Amith Yamasani15e472352015-04-24 19:06:07 -07002249
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002250 int appId = UserHandle.getAppId(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002251 int uidRules = RULE_ALLOW_ALL;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002252 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002253 // uid in background, and policy says to block metered data
2254 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002255 } else if (mRestrictBackground) {
2256 if (!uidForeground) {
2257 // uid in background, and global background disabled
2258 uidRules = RULE_REJECT_METERED;
2259 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002260 } else if (mRestrictPower) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002261 final boolean whitelisted = mPowerSaveWhitelistExceptIdleAppIds.get(appId)
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002262 || mPowerSaveTempWhitelistAppIds.get(appId);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002263 if (!whitelisted && !uidForeground
2264 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
2265 // uid is in background, restrict power use mode is on (so we want to
2266 // restrict all background network access), and this uid is not on the
2267 // white list of those allowed background access.
2268 uidRules = RULE_REJECT_METERED;
2269 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002270 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002271
Amith Yamasani15e472352015-04-24 19:06:07 -07002272 final int oldRules = mUidRules.get(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002273
Jeff Sharkey350083e2011-06-29 10:45:16 -07002274 if (uidRules == RULE_ALLOW_ALL) {
2275 mUidRules.delete(uid);
2276 } else {
2277 mUidRules.put(uid, uidRules);
2278 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002279
Amith Yamasani15e472352015-04-24 19:06:07 -07002280 // Update bandwidth rules if necessary
2281 final boolean oldRejectMetered = (oldRules & RULE_REJECT_METERED) != 0;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002282 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Amith Yamasani15e472352015-04-24 19:06:07 -07002283 if (oldRejectMetered != rejectMetered) {
2284 setUidNetworkRules(uid, rejectMetered);
2285 }
2286
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002287 // dispatch changed rule to existing listeners
Amith Yamasani15e472352015-04-24 19:06:07 -07002288 if (oldRules != uidRules) {
2289 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
2290 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002291
2292 try {
2293 // adjust stats accounting based on foreground status
2294 mNetworkStats.setUidForeground(uid, uidForeground);
2295 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002296 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002297 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002298 }
2299
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002300 private class AppIdleStateChangeListener
2301 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2302
2303 @Override
2304 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2305 try {
2306 int uid = mContext.getPackageManager().getPackageUid(packageName, userId);
2307 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002308 updateRuleForAppIdleLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002309 }
2310 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002311 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002312 }
2313
2314 @Override
2315 public void onParoleStateChanged(boolean isParoleOn) {
2316 synchronized (mRulesLock) {
2317 updateRulesForAppIdleParoleLocked();
2318 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002319 }
2320 }
2321
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002322 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002323 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002324 public boolean handleMessage(Message msg) {
2325 switch (msg.what) {
2326 case MSG_RULES_CHANGED: {
2327 final int uid = msg.arg1;
2328 final int uidRules = msg.arg2;
2329 final int length = mListeners.beginBroadcast();
2330 for (int i = 0; i < length; i++) {
2331 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2332 if (listener != null) {
2333 try {
2334 listener.onUidRulesChanged(uid, uidRules);
2335 } catch (RemoteException e) {
2336 }
2337 }
2338 }
2339 mListeners.finishBroadcast();
2340 return true;
2341 }
2342 case MSG_METERED_IFACES_CHANGED: {
2343 final String[] meteredIfaces = (String[]) msg.obj;
2344 final int length = mListeners.beginBroadcast();
2345 for (int i = 0; i < length; i++) {
2346 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2347 if (listener != null) {
2348 try {
2349 listener.onMeteredIfacesChanged(meteredIfaces);
2350 } catch (RemoteException e) {
2351 }
2352 }
2353 }
2354 mListeners.finishBroadcast();
2355 return true;
2356 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002357 case MSG_LIMIT_REACHED: {
2358 final String iface = (String) msg.obj;
2359
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002360 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002361 synchronized (mRulesLock) {
2362 if (mMeteredIfaces.contains(iface)) {
2363 try {
2364 // force stats update to make sure we have
2365 // numbers that caused alert to trigger.
2366 mNetworkStats.forceUpdate();
2367 } catch (RemoteException e) {
2368 // ignored; service lives in system_server
2369 }
2370
2371 updateNetworkEnabledLocked();
2372 updateNotificationsLocked();
2373 }
2374 }
2375 return true;
2376 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002377 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2378 final boolean restrictBackground = msg.arg1 != 0;
2379 final int length = mListeners.beginBroadcast();
2380 for (int i = 0; i < length; i++) {
2381 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2382 if (listener != null) {
2383 try {
2384 listener.onRestrictBackgroundChanged(restrictBackground);
2385 } catch (RemoteException e) {
2386 }
2387 }
2388 }
2389 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002390 return true;
2391 }
2392 case MSG_ADVISE_PERSIST_THRESHOLD: {
2393 final long lowestRule = (Long) msg.obj;
2394 try {
2395 // make sure stats are recorded frequently enough; we aim
2396 // for 2MB threshold for 2GB/month rules.
2397 final long persistThreshold = lowestRule / 1000;
2398 mNetworkStats.advisePersistThreshold(persistThreshold);
2399 } catch (RemoteException e) {
2400 // ignored; service lives in system_server
2401 }
2402 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002403 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002404 case MSG_SCREEN_ON_CHANGED: {
2405 updateScreenOn();
2406 return true;
2407 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002408 default: {
2409 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002410 }
2411 }
2412 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002413 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002414
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002415 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002416 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002417 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002418 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002419 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002420 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002421 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002422 }
2423 }
2424
2425 private void removeInterfaceQuota(String iface) {
2426 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002427 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002428 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002429 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002430 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002431 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002432 }
2433 }
2434
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002435 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2436 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002437 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002438 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002439 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002440 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002441 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002442 }
2443 }
2444
Amith Yamasani15e472352015-04-24 19:06:07 -07002445 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002446 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
2447 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
2448 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07002449 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002450 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002451 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002452 int size = uidRules.size();
2453 int[] uids = new int[size];
2454 int[] rules = new int[size];
2455 for(int index = size - 1; index >= 0; --index) {
2456 uids[index] = uidRules.keyAt(index);
2457 rules[index] = uidRules.valueAt(index);
2458 }
2459 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002460 } catch (IllegalStateException e) {
2461 Log.wtf(TAG, "problem setting firewall uid rules", e);
2462 } catch (RemoteException e) {
2463 // ignored; service lives in system_server
2464 }
2465 }
2466
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002467 /**
2468 * Add or remove a uid to the firewall blacklist for all network ifaces.
2469 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002470 private void setUidFirewallRule(int chain, int uid, int rule) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002471 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002472 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002473 } catch (IllegalStateException e) {
2474 Log.wtf(TAG, "problem setting firewall uid rules", e);
2475 } catch (RemoteException e) {
2476 // ignored; service lives in system_server
2477 }
2478 }
2479
2480 /**
2481 * Add or remove a uid to the firewall blacklist for all network ifaces.
2482 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002483 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002484 try {
2485 mNetworkManager.setFirewallChainEnabled(chain, enable);
2486 } catch (IllegalStateException e) {
2487 Log.wtf(TAG, "problem enable firewall chain", e);
2488 } catch (RemoteException e) {
2489 // ignored; service lives in system_server
2490 }
2491 }
2492
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002493 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2494 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002495 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002496 } catch (RuntimeException e) {
2497 Slog.w(TAG, "problem reading network stats: " + e);
2498 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002499 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002500 // ignored; service lives in system_server
2501 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002502 }
2503 }
2504
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002505 private boolean isBandwidthControlEnabled() {
2506 final long token = Binder.clearCallingIdentity();
2507 try {
2508 return mNetworkManager.isBandwidthControlEnabled();
2509 } catch (RemoteException e) {
2510 // ignored; service lives in system_server
2511 return false;
2512 } finally {
2513 Binder.restoreCallingIdentity(token);
2514 }
2515 }
2516
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002517 /**
2518 * Try refreshing {@link #mTime} when stale.
2519 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002520 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002521 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002522 mTime.forceRefresh();
2523 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002524 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002525
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002526 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002527 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2528 }
2529
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002530 private static Intent buildAllowBackgroundDataIntent() {
2531 return new Intent(ACTION_ALLOW_BACKGROUND);
2532 }
2533
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002534 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2535 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2536 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2537 return intent;
2538 }
2539
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002540 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2541 final Intent intent = new Intent();
2542 intent.setComponent(new ComponentName(
2543 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2544 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2545 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2546 return intent;
2547 }
2548
2549 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2550 final Intent intent = new Intent();
2551 intent.setComponent(new ComponentName(
2552 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2553 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2554 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2555 return intent;
2556 }
2557
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002558 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002559 public void addIdleHandler(IdleHandler handler) {
2560 mHandler.getLooper().getQueue().addIdleHandler(handler);
2561 }
2562
Jeff Sharkey1b861272011-05-22 00:34:52 -07002563 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2564 final int size = source.size();
2565 for (int i = 0; i < size; i++) {
2566 target.put(source.keyAt(i), true);
2567 }
2568 }
2569
Stuart Scottf1fb3972015-04-02 18:00:02 -07002570 @Override
2571 public void factoryReset(String subscriber) {
2572 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2573
Stuart Scotte3e314d2015-04-20 14:07:45 -07002574 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
2575 return;
2576 }
2577
Stuart Scottf1fb3972015-04-02 18:00:02 -07002578 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07002579 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07002580 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
2581 for (NetworkPolicy policy : policies) {
2582 if (policy.template.equals(template)) {
2583 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2584 policy.inferred = false;
2585 policy.clearSnooze();
2586 }
2587 }
2588 setNetworkPolicies(policies);
2589
2590 // Turn restrict background data off
2591 setRestrictBackground(false);
2592
Stuart Scotte3e314d2015-04-20 14:07:45 -07002593 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
2594 // Remove app's "restrict background data" flag
2595 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
2596 setUidPolicy(uid, POLICY_NONE);
2597 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07002598 }
2599 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002600}