blob: 142094f46a869bb7b53d24a5fbc27827ea8626a1 [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;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070025import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070026import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070027import static android.content.Intent.ACTION_USER_ADDED;
28import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070029import static android.content.Intent.EXTRA_UID;
Jeff Sharkey961e3042011-08-29 16:02:57 -070030import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070031import static android.net.ConnectivityManager.TYPE_ETHERNET;
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_WIFI;
34import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070035import static android.net.ConnectivityManager.isNetworkTypeMobile;
36import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070037import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070038import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070039import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070040import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070041import static android.net.NetworkPolicyManager.POLICY_NONE;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -070042import static android.net.NetworkPolicyManager.POLICY_ALLOW_BACKGROUND_BATTERY_SAVE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070043import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070044import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070045import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070046import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Jeff Sharkey1b861272011-05-22 00:34:52 -070047import static android.net.NetworkPolicyManager.dumpPolicy;
48import static android.net.NetworkPolicyManager.dumpRules;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070049import static android.net.NetworkTemplate.MATCH_ETHERNET;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070050import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
51import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070052import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
53import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070054import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080055import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070056import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
57import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
58import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
59import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
60import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
61import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
62import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070063import static android.telephony.TelephonyManager.SIM_STATE_READY;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070064import static android.text.format.DateUtils.DAY_IN_MILLIS;
Jeff Sharkey854b2b12012-04-13 16:03:40 -070065import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070066import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070067import static com.android.internal.util.XmlUtils.readBooleanAttribute;
68import static com.android.internal.util.XmlUtils.readIntAttribute;
69import static com.android.internal.util.XmlUtils.readLongAttribute;
70import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
71import static com.android.internal.util.XmlUtils.writeIntAttribute;
72import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070073import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070074import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070075import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
76import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070077
Jeff Sharkeya4620792011-05-20 15:29:23 -070078import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070079import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070080import android.app.IProcessObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070081import android.app.Notification;
82import android.app.PendingIntent;
Jeff Sharkeya4620792011-05-20 15:29:23 -070083import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070084import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070085import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070086import android.content.Intent;
87import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070088import android.content.pm.ApplicationInfo;
89import android.content.pm.PackageManager;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -070090import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -070091import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070092import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070093import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070094import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070095import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070096import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -070097import android.net.INetworkStatsService;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070098import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070099import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700100import android.net.NetworkPolicy;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700101import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700102import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700103import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700104import android.net.wifi.WifiConfiguration;
105import android.net.wifi.WifiInfo;
106import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700107import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700108import android.os.Environment;
109import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700110import android.os.HandlerThread;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700111import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700112import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700113import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700114import android.os.MessageQueue.IdleHandler;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700115import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700116import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700117import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700118import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700119import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700120import android.provider.Settings;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700121import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700122import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700123import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700124import android.util.ArrayMap;
125import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700126import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700127import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700128import android.util.NtpTrustedTime;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700129import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700130import android.util.SparseArray;
131import android.util.SparseBooleanArray;
132import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700133import android.util.TrustedTime;
134import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700135
Jeff Sharkey497e4432011-06-14 17:27:29 -0700136import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800137import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700138import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700139import com.android.internal.util.IndentingPrintWriter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700140import com.android.server.LocalServices;
141import com.android.server.SystemConfig;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700142import com.google.android.collect.Lists;
143import com.google.android.collect.Maps;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700144import com.google.android.collect.Sets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700145
146import org.xmlpull.v1.XmlPullParser;
147import org.xmlpull.v1.XmlPullParserException;
148import org.xmlpull.v1.XmlSerializer;
149
150import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700151import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700152import java.io.FileInputStream;
153import java.io.FileNotFoundException;
154import java.io.FileOutputStream;
155import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700156import java.io.PrintWriter;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700157import java.util.ArrayList;
158import java.util.Arrays;
159import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700160import java.util.HashSet;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700161import java.util.List;
Kenny Roote6585b32013-12-13 12:00:26 -0800162import java.util.Objects;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700163
164import libcore.io.IoUtils;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700165
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700166/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700167 * Service that maintains low-level network policy rules, using
168 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700169 * <p>
170 * Derives active rules by combining a given policy with other system status,
171 * and delivers to listeners, such as {@link ConnectivityManager}, for
172 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700173 */
174public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
175 private static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700176 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700177 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700178
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700179 private static final int VERSION_INIT = 1;
180 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700181 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800182 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800183 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800184 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700185 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700186 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700187 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700188 private static final int VERSION_SWITCH_UID = 10;
189 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700190
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800191 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700192 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800193 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700194 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800195 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700196 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700197
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700198 private static final String TAG_POLICY_LIST = "policy-list";
199 private static final String TAG_NETWORK_POLICY = "network-policy";
200 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700201 private static final String TAG_APP_POLICY = "app-policy";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700202
203 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700204 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700205 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
206 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700207 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700208 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800209 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700210 private static final String ATTR_WARNING_BYTES = "warningBytes";
211 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700212 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800213 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
214 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800215 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700216 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700217 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700218 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700219 private static final String ATTR_POLICY = "policy";
220
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700221 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
222
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800223 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800224 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800225 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800226 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700227
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700228 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
229
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700230 private static final int MSG_RULES_CHANGED = 1;
231 private static final int MSG_METERED_IFACES_CHANGED = 2;
232 private static final int MSG_FOREGROUND_ACTIVITIES_CHANGED = 3;
233 private static final int MSG_PROCESS_DIED = 4;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800234 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800235 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700236 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700237 private static final int MSG_SCREEN_ON_CHANGED = 8;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700238
Jeff Sharkey75279902011-05-24 18:39:45 -0700239 private final Context mContext;
240 private final IActivityManager mActivityManager;
241 private final IPowerManager mPowerManager;
242 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700243 private final INetworkManagementService mNetworkManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700244 private final TrustedTime mTime;
245
246 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700247 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700248 private PowerManagerInternal mPowerManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700249
Jeff Sharkey75279902011-05-24 18:39:45 -0700250 private final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700251
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700252 private volatile boolean mScreenOn;
253 private volatile boolean mRestrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700254 private volatile boolean mRestrictPower;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700255
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700256 private final boolean mSuppressDefaultPolicy;
257
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700258 /** Defined network policies. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700259 private final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<
260 NetworkTemplate, NetworkPolicy>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700261 /** Currently active network rules for ifaces. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700262 private final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<
263 NetworkPolicy, String[]>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700264
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700265 /** Defined UID policies. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700266 private final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700267 /** Currently derived rules for each UID. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700268 private final SparseIntArray mUidRules = new SparseIntArray();
269
270 /** UIDs that have been white-listed to always be able to have network access in
271 * power save mode. */
272 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700273
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700274 /** Set of ifaces that are metered. */
275 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700276 /** Set of over-limit templates that have been notified. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700277 private final HashSet<NetworkTemplate> mOverLimitNotified = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700278
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700279 /** Set of currently active {@link Notification} tags. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700280 private final HashSet<String> mActiveNotifs = Sets.newHashSet();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700281
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700282 /** Foreground at both UID and PID granularity. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700283 private final SparseBooleanArray mUidForeground = new SparseBooleanArray();
284 private final SparseArray<SparseBooleanArray> mUidPidForeground = new SparseArray<
Jeff Sharkeya4620792011-05-20 15:29:23 -0700285 SparseBooleanArray>();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700286
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700287 private final RemoteCallbackList<INetworkPolicyListener> mListeners = new RemoteCallbackList<
288 INetworkPolicyListener>();
289
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700290 private final Handler mHandler;
291
292 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700293
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700294 // TODO: keep whitelist of system-critical services that should never have
295 // rules enforced, such as system, phone, and radio UIDs.
296
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700297 // TODO: migrate notifications to SystemUI
298
Jeff Sharkey75279902011-05-24 18:39:45 -0700299 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700300 IPowerManager powerManager, INetworkStatsService networkStats,
301 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700302 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700303 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700304 }
305
306 private static File getSystemDir() {
307 return new File(Environment.getDataDirectory(), "system");
308 }
309
310 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700311 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700312 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
313 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700314 mContext = checkNotNull(context, "missing context");
315 mActivityManager = checkNotNull(activityManager, "missing activityManager");
316 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700317 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700318 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700319 mTime = checkNotNull(time, "missing TrustedTime");
320
Amith Yamasani450a16b2013-09-18 16:28:50 -0700321 HandlerThread thread = new HandlerThread(TAG);
322 thread.start();
323 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700324
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700325 mSuppressDefaultPolicy = suppressDefaultPolicy;
326
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700327 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
328 }
329
330 public void bindConnectivityManager(IConnectivityManager connManager) {
331 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700332 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700333
Jeff Sharkey497e4432011-06-14 17:27:29 -0700334 public void bindNotificationManager(INotificationManager notifManager) {
335 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
336 }
337
Jeff Sharkeya4620792011-05-20 15:29:23 -0700338 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700339 if (!isBandwidthControlEnabled()) {
340 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
341 return;
342 }
343
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700344 final PackageManager pm = mContext.getPackageManager();
345
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700346 synchronized (mRulesLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700347 SystemConfig sysConfig = SystemConfig.getInstance();
348 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
349 for (int i=0; i<allowPower.size(); i++) {
350 String pkg = allowPower.valueAt(i);
351 try {
352 ApplicationInfo ai = pm.getApplicationInfo(pkg, 0);
353 if ((ai.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
354 mPowerSaveWhitelistAppIds.put(UserHandle.getAppId(ai.uid), true);
355 }
356 } catch (PackageManager.NameNotFoundException e) {
357 }
358 }
359
360 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
361 mPowerManagerInternal.registerLowPowerModeObserver(
362 new PowerManagerInternal.LowPowerModeListener() {
363 @Override
364 public void onLowPowerModeChanged(boolean enabled) {
365 synchronized (mRulesLock) {
366 if (mRestrictPower != enabled) {
367 mRestrictPower = enabled;
368 updateRulesForGlobalChangeLocked(true);
369 }
370 }
371 }
372 });
373 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
374
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700375 // read policy from disk
376 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700377
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700378 if (mRestrictBackground || mRestrictPower) {
379 updateRulesForGlobalChangeLocked(true);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700380 updateNotificationsLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700381 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700382 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700383
Jeff Sharkeya4620792011-05-20 15:29:23 -0700384 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700385
Jeff Sharkeya4620792011-05-20 15:29:23 -0700386 try {
387 mActivityManager.registerProcessObserver(mProcessObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700388 mNetworkManager.registerObserver(mAlertObserver);
389 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700390 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700391 }
392
Jeff Sharkeya4620792011-05-20 15:29:23 -0700393 // TODO: traverse existing processes to know foreground state, or have
394 // activitymanager dispatch current state when new observer attached.
395
396 final IntentFilter screenFilter = new IntentFilter();
397 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
398 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700399 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700400
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700401 // watch for network interfaces to be claimed
Jeff Sharkey961e3042011-08-29 16:02:57 -0700402 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION_IMMEDIATE);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700403 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
404
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700405 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700406 final IntentFilter packageFilter = new IntentFilter();
407 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700408 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700409 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700410
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700411 // listen for UID changes to update policy
412 mContext.registerReceiver(
413 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
414
415 // listen for user changes to update policy
416 final IntentFilter userFilter = new IntentFilter();
417 userFilter.addAction(ACTION_USER_ADDED);
418 userFilter.addAction(ACTION_USER_REMOVED);
419 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
420
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700421 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700422 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
423 mContext.registerReceiver(
424 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
425
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700426 // listen for restrict background changes from notifications
427 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
428 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
429
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800430 // listen for snooze warning from notifications
431 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
432 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
433 MANAGE_NETWORK_POLICY, mHandler);
434
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700435 // listen for configured wifi networks to be removed
436 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
437 mContext.registerReceiver(
438 mWifiConfigReceiver, wifiConfigFilter, CONNECTIVITY_INTERNAL, mHandler);
439
440 // listen for wifi state changes to catch metered hint
441 final IntentFilter wifiStateFilter = new IntentFilter(
442 WifiManager.NETWORK_STATE_CHANGED_ACTION);
443 mContext.registerReceiver(
444 mWifiStateReceiver, wifiStateFilter, CONNECTIVITY_INTERNAL, mHandler);
445
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700446 }
447
Jeff Sharkeya4620792011-05-20 15:29:23 -0700448 private IProcessObserver mProcessObserver = new IProcessObserver.Stub() {
449 @Override
450 public void onForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700451 mHandler.obtainMessage(MSG_FOREGROUND_ACTIVITIES_CHANGED,
452 pid, uid, foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700453 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700454
455 @Override
Dianne Hackborn684bf342014-04-29 17:56:57 -0700456 public void onProcessStateChanged(int pid, int uid, int procState) {
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700457 }
458
459 @Override
Jeff Sharkeya4620792011-05-20 15:29:23 -0700460 public void onProcessDied(int pid, int uid) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700461 mHandler.obtainMessage(MSG_PROCESS_DIED, pid, uid).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700462 }
463 };
464
465 private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
466 @Override
467 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800468 // screen-related broadcasts are protected by system, no need
469 // for permissions check.
470 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700471 }
472 };
473
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700474 private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700475 @Override
476 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700477 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700478
479 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700480 final int uid = intent.getIntExtra(EXTRA_UID, -1);
481 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700482
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700483 if (ACTION_PACKAGE_ADDED.equals(action)) {
484 // update rules for UID, since it might be subject to
485 // global background data policy
486 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
487 synchronized (mRulesLock) {
488 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700489 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700490 }
491 }
492 };
493
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700494 private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
495 @Override
496 public void onReceive(Context context, Intent intent) {
497 // on background handler thread, and UID_REMOVED is protected
498
499 final int uid = intent.getIntExtra(EXTRA_UID, -1);
500 if (uid == -1) return;
501
502 // remove any policy and update rules to clean up
503 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
504 synchronized (mRulesLock) {
505 mUidPolicy.delete(uid);
506 updateRulesForUidLocked(uid);
507 writePolicyLocked();
508 }
509 }
510 };
511
512 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
513 @Override
514 public void onReceive(Context context, Intent intent) {
515 // on background handler thread, and USER_ADDED and USER_REMOVED
516 // broadcasts are protected
517
518 final String action = intent.getAction();
519 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
520 if (userId == -1) return;
521
522 // Remove any policies for given user; both cleaning up after a
523 // USER_REMOVED, and one last sanity check during USER_ADDED
524 removePoliciesForUserLocked(userId);
525
526 // Update global restrict for new user
527 synchronized (mRulesLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700528 updateRulesForGlobalChangeLocked(true);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700529 }
530 }
531 };
532
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700533 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700534 * Receiver that watches for {@link INetworkStatsService} updates, which we
535 * use to check against {@link NetworkPolicy#warningBytes}.
536 */
537 private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
538 @Override
539 public void onReceive(Context context, Intent intent) {
540 // on background handler thread, and verified
541 // READ_NETWORK_USAGE_HISTORY permission above.
542
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800543 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700544 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700545 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700546 updateNotificationsLocked();
547 }
548 }
549 };
550
551 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700552 * Receiver that watches for {@link Notification} control of
553 * {@link #mRestrictBackground}.
554 */
555 private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
556 @Override
557 public void onReceive(Context context, Intent intent) {
558 // on background handler thread, and verified MANAGE_NETWORK_POLICY
559 // permission above.
560
561 setRestrictBackground(false);
562 }
563 };
564
565 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800566 * Receiver that watches for {@link Notification} control of
567 * {@link NetworkPolicy#lastWarningSnooze}.
568 */
569 private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
570 @Override
571 public void onReceive(Context context, Intent intent) {
572 // on background handler thread, and verified MANAGE_NETWORK_POLICY
573 // permission above.
574
575 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
576 performSnooze(template, TYPE_WARNING);
577 }
578 };
579
580 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700581 * Receiver that watches for {@link WifiConfiguration} to be changed.
582 */
583 private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
584 @Override
585 public void onReceive(Context context, Intent intent) {
586 // on background handler thread, and verified CONNECTIVITY_INTERNAL
587 // permission above.
588
589 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
590 if (reason == CHANGE_REASON_REMOVED) {
591 final WifiConfiguration config = intent.getParcelableExtra(
592 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700593 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800594 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700595 synchronized (mRulesLock) {
596 if (mNetworkPolicy.containsKey(template)) {
597 mNetworkPolicy.remove(template);
598 writePolicyLocked();
599 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700600 }
601 }
602 }
603 }
604 };
605
606 /**
607 * Receiver that watches {@link WifiInfo} state changes to infer metered
608 * state. Ignores hints when policy is user-defined.
609 */
610 private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
611 @Override
612 public void onReceive(Context context, Intent intent) {
613 // on background handler thread, and verified CONNECTIVITY_INTERNAL
614 // permission above.
615
616 // ignore when not connected
617 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
618 if (!netInfo.isConnected()) return;
619
620 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
621 final boolean meteredHint = info.getMeteredHint();
622
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800623 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700624 synchronized (mRulesLock) {
625 NetworkPolicy policy = mNetworkPolicy.get(template);
626 if (policy == null && meteredHint) {
627 // policy doesn't exist, and AP is hinting that it's
628 // metered: create an inferred policy.
629 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
630 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
631 meteredHint, true);
632 addNetworkPolicyLocked(policy);
633
634 } else if (policy != null && policy.inferred) {
635 // policy exists, and was inferred: update its current
636 // metered state.
637 policy.metered = meteredHint;
638
639 // since this is inferred for each wifi session, just update
640 // rules without persisting.
641 updateNetworkRulesLocked();
642 }
643 }
644 }
645 };
646
647 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700648 * Observer that watches for {@link INetworkManagementService} alerts.
649 */
Jeff Sharkey216c1812012-08-05 14:29:23 -0700650 private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700651 @Override
652 public void limitReached(String limitName, String iface) {
653 // only someone like NMS should be calling us
654 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
655
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800656 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
657 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700658 }
659 }
660 };
661
662 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700663 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
664 * to show visible notifications as needed.
665 */
666 private void updateNotificationsLocked() {
667 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
668
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700669 // keep track of previously active notifications
670 final HashSet<String> beforeNotifs = Sets.newHashSet();
671 beforeNotifs.addAll(mActiveNotifs);
672 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700673
674 // TODO: when switching to kernel notifications, compute next future
675 // cycle boundary to recompute notifications.
676
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700677 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800678 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700679 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
680 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700681 // ignore policies that aren't relevant to user
682 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700683 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700684
Jeff Sharkey497e4432011-06-14 17:27:29 -0700685 final long start = computeLastCycleBoundary(currentTime, policy);
686 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700687 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700688
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700689 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800690 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700691 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
692 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700693 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
694 notifyOverLimitLocked(policy.template);
695 }
696
Jeff Sharkey497e4432011-06-14 17:27:29 -0700697 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700698 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700699
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800700 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700701 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700702 }
703 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700704 }
705
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700706 // ongoing notification when restricting background data
707 if (mRestrictBackground) {
708 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700709 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700710
711 // cancel stale notifications that we didn't renew above
712 for (String tag : beforeNotifs) {
713 if (!mActiveNotifs.contains(tag)) {
714 cancelNotification(tag);
715 }
716 }
717 }
718
719 /**
720 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700721 * current device state, such as when
722 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
723 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700724 */
725 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700726 final TelephonyManager tele = TelephonyManager.from(mContext);
727
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700728 switch (template.getMatchRule()) {
729 case MATCH_MOBILE_3G_LOWER:
730 case MATCH_MOBILE_4G:
731 case MATCH_MOBILE_ALL:
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700732 // mobile templates are relevant when SIM is ready and
733 // subscriberId matches.
734 if (tele.getSimState() == SIM_STATE_READY) {
Kenny Roote6585b32013-12-13 12:00:26 -0800735 return Objects.equals(tele.getSubscriberId(), template.getSubscriberId());
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700736 } else {
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700737 return false;
738 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700739 }
740 return true;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700741 }
742
743 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700744 * Notify that given {@link NetworkTemplate} is over
745 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
746 */
747 private void notifyOverLimitLocked(NetworkTemplate template) {
748 if (!mOverLimitNotified.contains(template)) {
749 mContext.startActivity(buildNetworkOverLimitIntent(template));
750 mOverLimitNotified.add(template);
751 }
752 }
753
754 private void notifyUnderLimitLocked(NetworkTemplate template) {
755 mOverLimitNotified.remove(template);
756 }
757
758 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700759 * Build unique tag that identifies an active {@link NetworkPolicy}
760 * notification of a specific type, like {@link #TYPE_LIMIT}.
761 */
762 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700763 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700764 }
765
766 /**
767 * Show notification for combined {@link NetworkPolicy} and specific type,
768 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
769 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700770 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700771 final String tag = buildNotificationTag(policy, type);
772 final Notification.Builder builder = new Notification.Builder(mContext);
773 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800774 builder.setWhen(0L);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700775
776 final Resources res = mContext.getResources();
777 switch (type) {
778 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700779 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700780 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700781
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700782 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700783 builder.setTicker(title);
784 builder.setContentTitle(title);
785 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700786
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800787 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
788 builder.setDeleteIntent(PendingIntent.getBroadcast(
789 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
790
791 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700792 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800793 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
794
Jeff Sharkey497e4432011-06-14 17:27:29 -0700795 break;
796 }
797 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700798 final CharSequence body = res.getText(R.string.data_usage_limit_body);
799
800 final CharSequence title;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700801 switch (policy.template.getMatchRule()) {
802 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700803 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700804 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700805 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700806 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700807 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700808 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700809 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700810 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700811 case MATCH_WIFI:
812 title = res.getText(R.string.data_usage_wifi_limit_title);
813 break;
814 default:
815 title = null;
816 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700817 }
818
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800819 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700820 builder.setSmallIcon(R.drawable.stat_notify_disabled);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700821 builder.setTicker(title);
822 builder.setContentTitle(title);
823 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700824
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700825 final Intent intent = buildNetworkOverLimitIntent(policy.template);
826 builder.setContentIntent(PendingIntent.getActivity(
827 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
828 break;
829 }
830 case TYPE_LIMIT_SNOOZED: {
831 final long overBytes = totalBytes - policy.limitBytes;
832 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
833 Formatter.formatFileSize(mContext, overBytes));
834
835 final CharSequence title;
836 switch (policy.template.getMatchRule()) {
837 case MATCH_MOBILE_3G_LOWER:
838 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
839 break;
840 case MATCH_MOBILE_4G:
841 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
842 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700843 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700844 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
845 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700846 case MATCH_WIFI:
847 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
848 break;
849 default:
850 title = null;
851 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700852 }
853
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800854 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700855 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700856 builder.setTicker(title);
857 builder.setContentTitle(title);
858 builder.setContentText(body);
859
860 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700861 builder.setContentIntent(PendingIntent.getActivity(
862 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700863 break;
864 }
865 }
866
867 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700868 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700869 try {
870 final String packageName = mContext.getPackageName();
871 final int[] idReceived = new int[1];
872 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800873 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Dianne Hackborn41203752012-08-31 14:05:51 -0700874 UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700875 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700876 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700877 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700878 }
879 }
880
881 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700882 * Show ongoing notification to reflect that {@link #mRestrictBackground}
883 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700884 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700885 private void enqueueRestrictedNotification(String tag) {
886 final Resources res = mContext.getResources();
887 final Notification.Builder builder = new Notification.Builder(mContext);
888
889 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
890 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
891
892 builder.setOnlyAlertOnce(true);
893 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700894 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700895 builder.setTicker(title);
896 builder.setContentTitle(title);
897 builder.setContentText(body);
898
899 final Intent intent = buildAllowBackgroundDataIntent();
900 builder.setContentIntent(
901 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700902
903 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700904 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700905 try {
906 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700907 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800908 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Dianne Hackborn41203752012-08-31 14:05:51 -0700909 0x0, builder.getNotification(), idReceived, UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700910 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700911 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700912 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700913 }
914 }
915
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700916 private void cancelNotification(String tag) {
917 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700918 // XXX what to do about multi-user?
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700919 try {
920 final String packageName = mContext.getPackageName();
921 mNotifManager.cancelNotificationWithTag(
Dianne Hackborn41203752012-08-31 14:05:51 -0700922 packageName, tag, 0x0, UserHandle.USER_OWNER);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700923 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700924 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700925 }
926 }
927
928 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700929 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700930 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700931 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700932 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700933 @Override
934 public void onReceive(Context context, Intent intent) {
935 // on background handler thread, and verified CONNECTIVITY_INTERNAL
936 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800937
938 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700939 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700940 ensureActiveMobilePolicyLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700941 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700942 updateNetworkRulesLocked();
943 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700944 }
945 }
946 };
947
948 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700949 * Proactively control network data connections when they exceed
950 * {@link NetworkPolicy#limitBytes}.
951 */
952 private void updateNetworkEnabledLocked() {
953 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
954
955 // TODO: reset any policy-disabled networks when any policy is removed
956 // completely, which is currently rare case.
957
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800958 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700959 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
960 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700961 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700962 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700963 setNetworkTemplateEnabled(policy.template, true);
964 continue;
965 }
966
967 final long start = computeLastCycleBoundary(currentTime, policy);
968 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700969 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700970
971 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800972 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
973 && policy.lastLimitSnooze < start;
974 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700975
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800976 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700977 }
978 }
979
980 /**
981 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}
982 * for the given {@link NetworkTemplate}.
983 */
984 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700985 final TelephonyManager tele = TelephonyManager.from(mContext);
986
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700987 switch (template.getMatchRule()) {
988 case MATCH_MOBILE_3G_LOWER:
989 case MATCH_MOBILE_4G:
990 case MATCH_MOBILE_ALL:
991 // TODO: offer more granular control over radio states once
992 // 4965893 is available.
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700993 if (tele.getSimState() == SIM_STATE_READY
Kenny Roote6585b32013-12-13 12:00:26 -0800994 && Objects.equals(tele.getSubscriberId(), template.getSubscriberId())) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700995 setPolicyDataEnable(TYPE_MOBILE, enabled);
996 setPolicyDataEnable(TYPE_WIMAX, enabled);
997 }
998 break;
999 case MATCH_WIFI:
1000 setPolicyDataEnable(TYPE_WIFI, enabled);
1001 break;
1002 case MATCH_ETHERNET:
1003 setPolicyDataEnable(TYPE_ETHERNET, enabled);
1004 break;
1005 default:
1006 throw new IllegalArgumentException("unexpected template");
1007 }
1008 }
1009
1010 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001011 * Examine all connected {@link NetworkState}, looking for
1012 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1013 * remaining quota based on usage cycle and historical stats.
1014 */
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001015 private void updateNetworkRulesLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001016 if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001017
1018 final NetworkState[] states;
1019 try {
1020 states = mConnManager.getAllNetworkState();
1021 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001022 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001023 return;
1024 }
1025
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001026 // If we are in restrict power mode, we want to treat all interfaces
1027 // as metered, to restrict access to the network by uid. However, we
1028 // will not have a bandwidth limit. Also only do this if restrict
1029 // background data use is *not* enabled, since that takes precendence
1030 // use over those networks can have a cost associated with it).
1031 final boolean powerSave = mRestrictPower && !mRestrictBackground;
1032
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001033 // first, derive identity for all connected networks, which can be used
1034 // to match against templates.
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001035 final ArrayMap<NetworkIdentity, String> networks = new ArrayMap();
1036 final ArraySet<String> connIfaces = new ArraySet<String>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001037 for (NetworkState state : states) {
1038 // stash identity and iface away for later use
1039 if (state.networkInfo.isConnected()) {
1040 final String iface = state.linkProperties.getInterfaceName();
1041 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1042 networks.put(ident, iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001043 if (powerSave) {
1044 connIfaces.add(iface);
1045 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001046 }
1047 }
1048
1049 // build list of rules and ifaces to enforce them against
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001050 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001051 final ArrayList<String> ifaceList = Lists.newArrayList();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001052 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1053 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001054
1055 // collect all active ifaces that match this template
1056 ifaceList.clear();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001057 for (int j = networks.size()-1; j >= 0; j--) {
1058 final NetworkIdentity ident = networks.keyAt(j);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001059 if (policy.template.matches(ident)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001060 final String iface = networks.valueAt(j);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001061 ifaceList.add(iface);
1062 }
1063 }
1064
1065 if (ifaceList.size() > 0) {
1066 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001067 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001068 }
1069 }
1070
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001071 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001072 final HashSet<String> newMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001073
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001074 // apply each policy that we found ifaces for; compute remaining data
1075 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001076 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001077 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1078 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1079 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001080
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001081 final long start;
1082 final long totalBytes;
1083 if (policy.hasCycle()) {
1084 start = computeLastCycleBoundary(currentTime, policy);
1085 totalBytes = getTotalBytes(policy.template, start, currentTime);
1086 } else {
1087 start = Long.MAX_VALUE;
1088 totalBytes = 0;
1089 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001090
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001091 if (LOGD) {
1092 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001093 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001094 }
1095
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001096 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001097 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001098 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001099 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001100 if (!hasLimit) {
1101 // metered network, but no policy limit; we still need to
1102 // restrict apps, so push really high quota.
1103 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001104 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001105 // snoozing past quota, but we still need to restrict apps,
1106 // so push really high quota.
1107 quotaBytes = Long.MAX_VALUE;
1108 } else {
1109 // remaining "quota" bytes are based on total usage in
1110 // current cycle. kernel doesn't like 0-byte rules, so we
1111 // set 1-byte quota and disable the radio later.
1112 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1113 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001114
1115 if (ifaces.length > 1) {
1116 // TODO: switch to shared quota once NMS supports
1117 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001118 }
1119
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001120 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001121 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001122 setInterfaceQuota(iface, quotaBytes);
1123 newMeteredIfaces.add(iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001124 if (powerSave) {
1125 connIfaces.remove(iface);
1126 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001127 }
1128 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001129
1130 // keep track of lowest warning or limit of active policies
1131 if (hasWarning && policy.warningBytes < lowestRule) {
1132 lowestRule = policy.warningBytes;
1133 }
1134 if (hasLimit && policy.limitBytes < lowestRule) {
1135 lowestRule = policy.limitBytes;
1136 }
1137 }
1138
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001139 for (int i = connIfaces.size()-1; i >= 0; i--) {
1140 String iface = connIfaces.valueAt(i);
1141 removeInterfaceQuota(iface);
1142 setInterfaceQuota(iface, Long.MAX_VALUE);
1143 newMeteredIfaces.add(iface);
1144 }
1145
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001146 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001147
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001148 // remove quota on any trailing interfaces
1149 for (String iface : mMeteredIfaces) {
1150 if (!newMeteredIfaces.contains(iface)) {
1151 removeInterfaceQuota(iface);
1152 }
1153 }
1154 mMeteredIfaces = newMeteredIfaces;
1155
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001156 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001157 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001158 }
1159
1160 /**
1161 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1162 * have at least a default mobile policy defined.
1163 */
1164 private void ensureActiveMobilePolicyLocked() {
1165 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001166 if (mSuppressDefaultPolicy) return;
1167
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001168 final TelephonyManager tele = TelephonyManager.from(mContext);
1169
1170 // avoid creating policy when SIM isn't ready
1171 if (tele.getSimState() != SIM_STATE_READY) return;
1172
1173 final String subscriberId = tele.getSubscriberId();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001174 final NetworkIdentity probeIdent = new NetworkIdentity(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001175 TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001176
1177 // examine to see if any policy is defined for active mobile
1178 boolean mobileDefined = false;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001179 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1180 if (mNetworkPolicy.valueAt(i).template.matches(probeIdent)) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001181 mobileDefined = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001182 break;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001183 }
1184 }
1185
1186 if (!mobileDefined) {
1187 Slog.i(TAG, "no policy for active mobile network; generating default policy");
1188
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001189 // build default mobile policy, and assume usage cycle starts today
1190 final long warningBytes = mContext.getResources().getInteger(
1191 com.android.internal.R.integer.config_networkPolicyDefaultWarning)
1192 * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001193
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001194 final Time time = new Time();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001195 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001196
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001197 final int cycleDay = time.monthDay;
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001198 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001199
Jeff Sharkey4e814c32011-07-14 20:37:37 -07001200 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001201 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1202 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1203 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001204 }
1205 }
1206
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001207 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001208 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001209
1210 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001211 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001212 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001213
1214 FileInputStream fis = null;
1215 try {
1216 fis = mPolicyFile.openRead();
1217 final XmlPullParser in = Xml.newPullParser();
1218 in.setInput(fis, null);
1219
1220 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001221 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001222 while ((type = in.next()) != END_DOCUMENT) {
1223 final String tag = in.getName();
1224 if (type == START_TAG) {
1225 if (TAG_POLICY_LIST.equals(tag)) {
1226 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001227 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1228 mRestrictBackground = readBooleanAttribute(
1229 in, ATTR_RESTRICT_BACKGROUND);
1230 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001231 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001232 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001233
1234 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1235 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1236 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001237 final String networkId;
1238 if (version >= VERSION_ADDED_NETWORK_ID) {
1239 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1240 } else {
1241 networkId = null;
1242 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001243 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001244 final String cycleTimezone;
1245 if (version >= VERSION_ADDED_TIMEZONE) {
1246 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1247 } else {
1248 cycleTimezone = Time.TIMEZONE_UTC;
1249 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001250 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1251 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001252 final long lastLimitSnooze;
1253 if (version >= VERSION_SPLIT_SNOOZE) {
1254 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1255 } else if (version >= VERSION_ADDED_SNOOZE) {
1256 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001257 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001258 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001259 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001260 final boolean metered;
1261 if (version >= VERSION_ADDED_METERED) {
1262 metered = readBooleanAttribute(in, ATTR_METERED);
1263 } else {
1264 switch (networkTemplate) {
1265 case MATCH_MOBILE_3G_LOWER:
1266 case MATCH_MOBILE_4G:
1267 case MATCH_MOBILE_ALL:
1268 metered = true;
1269 break;
1270 default:
1271 metered = false;
1272 }
1273 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001274 final long lastWarningSnooze;
1275 if (version >= VERSION_SPLIT_SNOOZE) {
1276 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1277 } else {
1278 lastWarningSnooze = SNOOZE_NEVER;
1279 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001280 final boolean inferred;
1281 if (version >= VERSION_ADDED_INFERRED) {
1282 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1283 } else {
1284 inferred = false;
1285 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001286
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001287 final NetworkTemplate template = new NetworkTemplate(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001288 networkTemplate, subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001289 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001290 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001291 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001292
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001293 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001294 final int uid = readIntAttribute(in, ATTR_UID);
1295 final int policy = readIntAttribute(in, ATTR_POLICY);
1296
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001297 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001298 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001299 } else {
1300 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1301 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001302 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001303 final int appId = readIntAttribute(in, ATTR_APP_ID);
1304 final int policy = readIntAttribute(in, ATTR_POLICY);
1305
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001306 // TODO: set for other users during upgrade
1307 final int uid = UserHandle.getUid(UserHandle.USER_OWNER, appId);
1308 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001309 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001310 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001311 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001312 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001313 }
1314 }
1315 }
1316
1317 } catch (FileNotFoundException e) {
1318 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001319 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001320 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001321 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001322 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001323 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001324 } finally {
1325 IoUtils.closeQuietly(fis);
1326 }
1327 }
1328
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001329 /**
1330 * Upgrade legacy background data flags, notifying listeners of one last
1331 * change to always-true.
1332 */
1333 private void upgradeLegacyBackgroundData() {
1334 mRestrictBackground = Settings.Secure.getInt(
1335 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1336
1337 // kick off one last broadcast if restricted
1338 if (mRestrictBackground) {
1339 final Intent broadcast = new Intent(
1340 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001341 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001342 }
1343 }
1344
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001345 private void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001346 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001347
1348 FileOutputStream fos = null;
1349 try {
1350 fos = mPolicyFile.startWrite();
1351
1352 XmlSerializer out = new FastXmlSerializer();
1353 out.setOutput(fos, "utf-8");
1354 out.startDocument(null, true);
1355
1356 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001357 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001358 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001359
1360 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001361 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1362 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001363 final NetworkTemplate template = policy.template;
1364
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001365 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001366 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1367 final String subscriberId = template.getSubscriberId();
1368 if (subscriberId != null) {
1369 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001370 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001371 final String networkId = template.getNetworkId();
1372 if (networkId != null) {
1373 out.attribute(null, ATTR_NETWORK_ID, networkId);
1374 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001375 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001376 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001377 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1378 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001379 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1380 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001381 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001382 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001383 out.endTag(null, TAG_NETWORK_POLICY);
1384 }
1385
1386 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001387 for (int i = 0; i < mUidPolicy.size(); i++) {
1388 final int uid = mUidPolicy.keyAt(i);
1389 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001390
Jeff Sharkey497e4432011-06-14 17:27:29 -07001391 // skip writing empty policies
1392 if (policy == POLICY_NONE) continue;
1393
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001394 out.startTag(null, TAG_UID_POLICY);
1395 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001396 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001397 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001398 }
1399
1400 out.endTag(null, TAG_POLICY_LIST);
1401 out.endDocument();
1402
1403 mPolicyFile.finishWrite(fos);
1404 } catch (IOException e) {
1405 if (fos != null) {
1406 mPolicyFile.failWrite(fos);
1407 }
1408 }
1409 }
1410
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001411 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001412 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001413 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001414
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001415 if (!UserHandle.isApp(uid)) {
1416 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001417 }
1418
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001419 synchronized (mRulesLock) {
1420 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1421 if (oldPolicy != policy) {
1422 setUidPolicyUncheckedLocked(uid, policy, true);
1423 }
1424 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001425 }
1426
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001427 @Override
1428 public void addUidPolicy(int uid, int policy) {
1429 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001430
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001431 if (!UserHandle.isApp(uid)) {
1432 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1433 }
1434
1435 synchronized (mRulesLock) {
1436 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1437 policy |= oldPolicy;
1438 if (oldPolicy != policy) {
1439 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001440 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001441 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001442 }
1443
1444 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001445 public void removeUidPolicy(int uid, int policy) {
1446 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1447
1448 if (!UserHandle.isApp(uid)) {
1449 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1450 }
1451
1452 synchronized (mRulesLock) {
1453 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1454 policy = oldPolicy & ~policy;
1455 if (oldPolicy != policy) {
1456 setUidPolicyUncheckedLocked(uid, policy, true);
1457 }
1458 }
1459 }
1460
1461 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1462 mUidPolicy.put(uid, policy);
1463
1464 // uid policy changed, recompute rules and persist policy.
1465 updateRulesForUidLocked(uid);
1466 if (persist) {
1467 writePolicyLocked();
1468 }
1469 }
1470
1471 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001472 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001473 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1474
Jeff Sharkeya4620792011-05-20 15:29:23 -07001475 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001476 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001477 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001478 }
1479
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001480 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001481 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001482 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1483
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001484 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001485 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001486 for (int i = 0; i < mUidPolicy.size(); i++) {
1487 final int uid = mUidPolicy.keyAt(i);
1488 final int uidPolicy = mUidPolicy.valueAt(i);
1489 if (uidPolicy == policy) {
1490 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001491 }
1492 }
1493 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001494 return uids;
1495 }
1496
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001497 @Override
1498 public int[] getPowerSaveAppIdWhitelist() {
1499 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1500
1501 synchronized (mRulesLock) {
1502 int size = mPowerSaveWhitelistAppIds.size();
1503 int[] appids = new int[size];
1504 for (int i = 0; i < size; i++) {
1505 appids[i] = mPowerSaveWhitelistAppIds.keyAt(i);
1506 }
1507 return appids;
1508 }
1509 }
1510
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001511 /**
1512 * Remove any policies associated with given {@link UserHandle}, persisting
1513 * if any changes are made.
1514 */
1515 private void removePoliciesForUserLocked(int userId) {
1516 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1517
1518 int[] uids = new int[0];
1519 for (int i = 0; i < mUidPolicy.size(); i++) {
1520 final int uid = mUidPolicy.keyAt(i);
1521 if (UserHandle.getUserId(uid) == userId) {
1522 uids = appendInt(uids, uid);
1523 }
1524 }
1525
1526 if (uids.length > 0) {
1527 for (int uid : uids) {
1528 mUidPolicy.delete(uid);
1529 updateRulesForUidLocked(uid);
1530 }
1531 writePolicyLocked();
1532 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001533 }
1534
1535 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001536 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001537 // TODO: create permission for observing network policy
1538 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1539
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001540 mListeners.register(listener);
1541
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001542 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001543 }
1544
1545 @Override
1546 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001547 // TODO: create permission for observing network policy
1548 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1549
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001550 mListeners.unregister(listener);
1551 }
1552
Jeff Sharkey1b861272011-05-22 00:34:52 -07001553 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001554 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001555 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1556
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001557 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001558 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001559 mNetworkPolicy.clear();
1560 for (NetworkPolicy policy : policies) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001561 mNetworkPolicy.put(policy.template, policy);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001562 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001563
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001564 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001565 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001566 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001567 writePolicyLocked();
1568 }
1569 }
1570
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001571 private void addNetworkPolicyLocked(NetworkPolicy policy) {
1572 mNetworkPolicy.put(policy.template, policy);
1573
1574 updateNetworkEnabledLocked();
1575 updateNetworkRulesLocked();
1576 updateNotificationsLocked();
1577 writePolicyLocked();
1578 }
1579
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001580 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001581 public NetworkPolicy[] getNetworkPolicies() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001582 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001583 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001584
1585 synchronized (mRulesLock) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001586 return mNetworkPolicy.values().toArray(new NetworkPolicy[mNetworkPolicy.size()]);
1587 }
1588 }
1589
1590 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001591 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001592 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001593
1594 final long token = Binder.clearCallingIdentity();
1595 try {
1596 performSnooze(template, TYPE_LIMIT);
1597 } finally {
1598 Binder.restoreCallingIdentity(token);
1599 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001600 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001601
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001602 private void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001603 maybeRefreshTrustedTime();
1604 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001605 synchronized (mRulesLock) {
1606 // find and snooze local policy that matches
1607 final NetworkPolicy policy = mNetworkPolicy.get(template);
1608 if (policy == null) {
1609 throw new IllegalArgumentException("unable to find policy for " + template);
1610 }
1611
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001612 switch (type) {
1613 case TYPE_WARNING:
1614 policy.lastWarningSnooze = currentTime;
1615 break;
1616 case TYPE_LIMIT:
1617 policy.lastLimitSnooze = currentTime;
1618 break;
1619 default:
1620 throw new IllegalArgumentException("unexpected type");
1621 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001622
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001623 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001624 updateNetworkRulesLocked();
1625 updateNotificationsLocked();
1626 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001627 }
1628 }
1629
1630 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001631 public void setRestrictBackground(boolean restrictBackground) {
1632 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1633
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001634 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001635 synchronized (mRulesLock) {
1636 mRestrictBackground = restrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001637 updateRulesForGlobalChangeLocked(false);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001638 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001639 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001640 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001641
1642 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1643 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001644 }
1645
1646 @Override
1647 public boolean getRestrictBackground() {
1648 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1649
1650 synchronized (mRulesLock) {
1651 return mRestrictBackground;
1652 }
1653 }
1654
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001655 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001656 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1657 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001658 if (policy.template.matches(ident)) {
1659 return policy;
1660 }
1661 }
1662 return null;
1663 }
1664
1665 @Override
1666 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1667 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1668
1669 // only returns usage summary, so we don't require caller to have
1670 // READ_NETWORK_USAGE_HISTORY.
1671 final long token = Binder.clearCallingIdentity();
1672 try {
1673 return getNetworkQuotaInfoUnchecked(state);
1674 } finally {
1675 Binder.restoreCallingIdentity(token);
1676 }
1677 }
1678
1679 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1680 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1681
1682 final NetworkPolicy policy;
1683 synchronized (mRulesLock) {
1684 policy = findPolicyForNetworkLocked(ident);
1685 }
1686
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001687 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001688 // missing policy means we can't derive useful quota info
1689 return null;
1690 }
1691
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001692 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001693
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001694 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001695 final long start = computeLastCycleBoundary(currentTime, policy);
1696 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001697 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001698
1699 // report soft and hard limits under policy
1700 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1701 : NetworkQuotaInfo.NO_LIMIT;
1702 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1703 : NetworkQuotaInfo.NO_LIMIT;
1704
1705 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1706 }
1707
Jeff Sharkey46645002011-07-27 21:11:21 -07001708 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001709 public boolean isNetworkMetered(NetworkState state) {
1710 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1711
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001712 // roaming networks are always considered metered
1713 if (ident.getRoaming()) {
1714 return true;
1715 }
1716
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001717 final NetworkPolicy policy;
1718 synchronized (mRulesLock) {
1719 policy = findPolicyForNetworkLocked(ident);
1720 }
1721
1722 if (policy != null) {
1723 return policy.metered;
1724 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001725 final int type = state.networkInfo.getType();
1726 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1727 return true;
1728 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001729 return false;
1730 }
1731 }
1732
1733 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001734 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001735 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001736
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001737 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1738
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001739 final HashSet<String> argSet = new HashSet<String>();
1740 for (String arg : args) {
1741 argSet.add(arg);
1742 }
1743
Jeff Sharkey1b861272011-05-22 00:34:52 -07001744 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001745 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001746 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1747 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001748 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001749
1750 updateNetworkEnabledLocked();
1751 updateNetworkRulesLocked();
1752 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001753 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001754
1755 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001756 return;
1757 }
1758
Jeff Sharkey46645002011-07-27 21:11:21 -07001759 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001760 fout.print("Restrict power: "); fout.println(mRestrictPower);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001761 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001762 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001763 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1764 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001765 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001766 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001767
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001768 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001769 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001770 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001771 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001772 final int uid = mUidPolicy.keyAt(i);
1773 final int policy = mUidPolicy.valueAt(i);
1774 fout.print("UID=");
1775 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001776 fout.print(" policy=");
1777 dumpPolicy(fout, policy);
1778 fout.println();
1779 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001780 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001781
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001782 size = mPowerSaveWhitelistAppIds.size();
1783 if (size > 0) {
1784 fout.println("Power save whitelist app ids:");
1785 fout.increaseIndent();
1786 for (int i = 0; i < size; i++) {
1787 fout.print("UID=");
1788 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
1789 fout.print(": ");
1790 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
1791 fout.println();
1792 }
1793 fout.decreaseIndent();
1794 }
1795
Jeff Sharkey1b861272011-05-22 00:34:52 -07001796 final SparseBooleanArray knownUids = new SparseBooleanArray();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001797 collectKeys(mUidForeground, knownUids);
1798 collectKeys(mUidRules, knownUids);
1799
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001800 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001801 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001802 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001803 for (int i = 0; i < size; i++) {
1804 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001805 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001806 fout.print(uid);
1807
Jeff Sharkey1b861272011-05-22 00:34:52 -07001808 fout.print(" foreground=");
1809 final int foregroundIndex = mUidPidForeground.indexOfKey(uid);
1810 if (foregroundIndex < 0) {
1811 fout.print("UNKNOWN");
1812 } else {
1813 dumpSparseBooleanArray(fout, mUidPidForeground.valueAt(foregroundIndex));
1814 }
1815
1816 fout.print(" rules=");
1817 final int rulesIndex = mUidRules.indexOfKey(uid);
1818 if (rulesIndex < 0) {
1819 fout.print("UNKNOWN");
1820 } else {
1821 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1822 }
1823
1824 fout.println();
1825 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001826 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001827 }
1828 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001829
1830 @Override
1831 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001832 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1833
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001834 synchronized (mRulesLock) {
1835 // only really in foreground when screen is also on
1836 return mUidForeground.get(uid, false) && mScreenOn;
1837 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001838 }
1839
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001840 /**
1841 * Foreground for PID changed; recompute foreground at UID level. If
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001842 * changed, will trigger {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001843 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001844 private void computeUidForegroundLocked(int uid) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001845 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1846
1847 // current pid is dropping foreground; examine other pids
1848 boolean uidForeground = false;
1849 final int size = pidForeground.size();
1850 for (int i = 0; i < size; i++) {
1851 if (pidForeground.valueAt(i)) {
1852 uidForeground = true;
1853 break;
1854 }
1855 }
1856
1857 final boolean oldUidForeground = mUidForeground.get(uid, false);
1858 if (oldUidForeground != uidForeground) {
1859 // foreground changed, push updated rules
1860 mUidForeground.put(uid, uidForeground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001861 updateRulesForUidLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001862 }
1863 }
1864
Jeff Sharkeya4620792011-05-20 15:29:23 -07001865 private void updateScreenOn() {
1866 synchronized (mRulesLock) {
1867 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07001868 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001869 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001870 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07001871 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001872 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001873 }
1874 }
1875
1876 /**
1877 * Update rules that might be changed by {@link #mScreenOn} value.
1878 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001879 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07001880 // only update rules for anyone with foreground activities
1881 final int size = mUidForeground.size();
1882 for (int i = 0; i < size; i++) {
1883 if (mUidForeground.valueAt(i)) {
1884 final int uid = mUidForeground.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001885 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001886 }
1887 }
1888 }
1889
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001890 /**
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001891 * Update rules that might be changed by {@link #mRestrictBackground}
1892 * or {@link #mRestrictPower} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001893 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001894 private void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001895 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001896 final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1897
1898 // update rules for all installed applications
1899 final List<UserInfo> users = um.getUsers();
1900 final List<ApplicationInfo> apps = pm.getInstalledApplications(
1901 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
1902
1903 for (UserInfo user : users) {
1904 for (ApplicationInfo app : apps) {
1905 final int uid = UserHandle.getUid(user.id, app.uid);
1906 updateRulesForUidLocked(uid);
1907 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001908 }
1909
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001910 // limit data usage for some internal system services
1911 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
1912 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001913
1914 // If the set of restricted networks may have changed, re-evaluate those.
1915 if (restrictedNetworksChanged) {
1916 updateNetworkRulesLocked();
1917 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001918 }
1919
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001920 private static boolean isUidValidForRules(int uid) {
1921 // allow rules on specific system services, and any apps
1922 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001923 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001924 return true;
1925 }
1926
1927 return false;
1928 }
1929
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001930 private void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001931 if (!isUidValidForRules(uid)) return;
1932
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001933 final int uidPolicy = getUidPolicy(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001934 final boolean uidForeground = isUidForeground(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001935
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001936 // derive active rules based on policy and active state
1937 int uidRules = RULE_ALLOW_ALL;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001938 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001939 // uid in background, and policy says to block metered data
1940 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001941 } else if (mRestrictBackground) {
1942 if (!uidForeground) {
1943 // uid in background, and global background disabled
1944 uidRules = RULE_REJECT_METERED;
1945 }
1946 } else if (mRestrictPower) {
1947 final boolean whitelisted = mPowerSaveWhitelistAppIds.get(UserHandle.getAppId(uid));
1948 if (!whitelisted && !uidForeground
1949 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
1950 // uid is in background, restrict power use mode is on (so we want to
1951 // restrict all background network access), and this uid is not on the
1952 // white list of those allowed background access.
1953 uidRules = RULE_REJECT_METERED;
1954 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001955 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001956
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001957 // TODO: only dispatch when rules actually change
1958
Jeff Sharkey350083e2011-06-29 10:45:16 -07001959 if (uidRules == RULE_ALLOW_ALL) {
1960 mUidRules.delete(uid);
1961 } else {
1962 mUidRules.put(uid, uidRules);
1963 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001964
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001965 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001966 setUidNetworkRules(uid, rejectMetered);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001967
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001968 // dispatch changed rule to existing listeners
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001969 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001970
1971 try {
1972 // adjust stats accounting based on foreground status
1973 mNetworkStats.setUidForeground(uid, uidForeground);
1974 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001975 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001976 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001977 }
1978
1979 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001980 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001981 public boolean handleMessage(Message msg) {
1982 switch (msg.what) {
1983 case MSG_RULES_CHANGED: {
1984 final int uid = msg.arg1;
1985 final int uidRules = msg.arg2;
1986 final int length = mListeners.beginBroadcast();
1987 for (int i = 0; i < length; i++) {
1988 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1989 if (listener != null) {
1990 try {
1991 listener.onUidRulesChanged(uid, uidRules);
1992 } catch (RemoteException e) {
1993 }
1994 }
1995 }
1996 mListeners.finishBroadcast();
1997 return true;
1998 }
1999 case MSG_METERED_IFACES_CHANGED: {
2000 final String[] meteredIfaces = (String[]) msg.obj;
2001 final int length = mListeners.beginBroadcast();
2002 for (int i = 0; i < length; i++) {
2003 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2004 if (listener != null) {
2005 try {
2006 listener.onMeteredIfacesChanged(meteredIfaces);
2007 } catch (RemoteException e) {
2008 }
2009 }
2010 }
2011 mListeners.finishBroadcast();
2012 return true;
2013 }
Jeff Sharkey6f7af032011-11-01 18:25:15 -07002014 case MSG_FOREGROUND_ACTIVITIES_CHANGED: {
2015 final int pid = msg.arg1;
2016 final int uid = msg.arg2;
2017 final boolean foregroundActivities = (Boolean) msg.obj;
2018
2019 synchronized (mRulesLock) {
2020 // because a uid can have multiple pids running inside, we need to
2021 // remember all pid states and summarize foreground at uid level.
2022
2023 // record foreground for this specific pid
2024 SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
2025 if (pidForeground == null) {
2026 pidForeground = new SparseBooleanArray(2);
2027 mUidPidForeground.put(uid, pidForeground);
2028 }
2029 pidForeground.put(pid, foregroundActivities);
2030 computeUidForegroundLocked(uid);
2031 }
2032 return true;
2033 }
2034 case MSG_PROCESS_DIED: {
2035 final int pid = msg.arg1;
2036 final int uid = msg.arg2;
2037
2038 synchronized (mRulesLock) {
2039 // clear records and recompute, when they exist
2040 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
2041 if (pidForeground != null) {
2042 pidForeground.delete(pid);
2043 computeUidForegroundLocked(uid);
2044 }
2045 }
2046 return true;
2047 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002048 case MSG_LIMIT_REACHED: {
2049 final String iface = (String) msg.obj;
2050
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002051 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002052 synchronized (mRulesLock) {
2053 if (mMeteredIfaces.contains(iface)) {
2054 try {
2055 // force stats update to make sure we have
2056 // numbers that caused alert to trigger.
2057 mNetworkStats.forceUpdate();
2058 } catch (RemoteException e) {
2059 // ignored; service lives in system_server
2060 }
2061
2062 updateNetworkEnabledLocked();
2063 updateNotificationsLocked();
2064 }
2065 }
2066 return true;
2067 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002068 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2069 final boolean restrictBackground = msg.arg1 != 0;
2070 final int length = mListeners.beginBroadcast();
2071 for (int i = 0; i < length; i++) {
2072 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2073 if (listener != null) {
2074 try {
2075 listener.onRestrictBackgroundChanged(restrictBackground);
2076 } catch (RemoteException e) {
2077 }
2078 }
2079 }
2080 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002081 return true;
2082 }
2083 case MSG_ADVISE_PERSIST_THRESHOLD: {
2084 final long lowestRule = (Long) msg.obj;
2085 try {
2086 // make sure stats are recorded frequently enough; we aim
2087 // for 2MB threshold for 2GB/month rules.
2088 final long persistThreshold = lowestRule / 1000;
2089 mNetworkStats.advisePersistThreshold(persistThreshold);
2090 } catch (RemoteException e) {
2091 // ignored; service lives in system_server
2092 }
2093 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002094 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002095 case MSG_SCREEN_ON_CHANGED: {
2096 updateScreenOn();
2097 return true;
2098 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002099 default: {
2100 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002101 }
2102 }
2103 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002104 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002105
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002106 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002107 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002108 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002109 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002110 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002111 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002112 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002113 }
2114 }
2115
2116 private void removeInterfaceQuota(String iface) {
2117 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002118 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002119 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002120 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002121 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002122 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002123 }
2124 }
2125
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002126 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2127 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002128 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002129 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002130 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002131 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002132 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002133 }
2134 }
2135
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002136 /**
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08002137 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002138 */
2139 private void setPolicyDataEnable(int networkType, boolean enabled) {
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08002140 try {
2141 mConnManager.setPolicyDataEnable(networkType, enabled);
2142 } catch (RemoteException e) {
2143 // ignored; service lives in system_server
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002144 }
2145 }
2146
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002147 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2148 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002149 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002150 } catch (RuntimeException e) {
2151 Slog.w(TAG, "problem reading network stats: " + e);
2152 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002153 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002154 // ignored; service lives in system_server
2155 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002156 }
2157 }
2158
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002159 private boolean isBandwidthControlEnabled() {
2160 final long token = Binder.clearCallingIdentity();
2161 try {
2162 return mNetworkManager.isBandwidthControlEnabled();
2163 } catch (RemoteException e) {
2164 // ignored; service lives in system_server
2165 return false;
2166 } finally {
2167 Binder.restoreCallingIdentity(token);
2168 }
2169 }
2170
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002171 /**
2172 * Try refreshing {@link #mTime} when stale.
2173 */
2174 private void maybeRefreshTrustedTime() {
2175 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002176 mTime.forceRefresh();
2177 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002178 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002179
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002180 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002181 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2182 }
2183
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002184 private static Intent buildAllowBackgroundDataIntent() {
2185 return new Intent(ACTION_ALLOW_BACKGROUND);
2186 }
2187
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002188 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2189 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2190 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2191 return intent;
2192 }
2193
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002194 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2195 final Intent intent = new Intent();
2196 intent.setComponent(new ComponentName(
2197 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2198 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2199 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2200 return intent;
2201 }
2202
2203 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2204 final Intent intent = new Intent();
2205 intent.setComponent(new ComponentName(
2206 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2207 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2208 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2209 return intent;
2210 }
2211
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002212 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002213 public void addIdleHandler(IdleHandler handler) {
2214 mHandler.getLooper().getQueue().addIdleHandler(handler);
2215 }
2216
Jeff Sharkey1b861272011-05-22 00:34:52 -07002217 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2218 final int size = source.size();
2219 for (int i = 0; i < size; i++) {
2220 target.put(source.keyAt(i), true);
2221 }
2222 }
2223
2224 private static void collectKeys(SparseBooleanArray source, SparseBooleanArray target) {
2225 final int size = source.size();
2226 for (int i = 0; i < size; i++) {
2227 target.put(source.keyAt(i), true);
2228 }
2229 }
2230
2231 private static void dumpSparseBooleanArray(PrintWriter fout, SparseBooleanArray value) {
2232 fout.print("[");
2233 final int size = value.size();
2234 for (int i = 0; i < size; i++) {
2235 fout.print(value.keyAt(i) + "=" + value.valueAt(i));
2236 if (i < size - 1) fout.print(",");
2237 }
2238 fout.print("]");
2239 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002240}