blob: 289ea1fe1019349248ce5e03975b92a944db5f3b [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;
27import static android.content.Intent.EXTRA_UID;
Jeff Sharkey961e3042011-08-29 16:02:57 -070028import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070029import static android.net.ConnectivityManager.TYPE_ETHERNET;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070030import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070031import static android.net.ConnectivityManager.TYPE_WIFI;
32import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070033import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070034import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070035import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070036import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070037import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070038import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070039import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070040import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070041import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Jeff Sharkey1b861272011-05-22 00:34:52 -070042import static android.net.NetworkPolicyManager.dumpPolicy;
43import static android.net.NetworkPolicyManager.dumpRules;
Jeff Sharkey497e4432011-06-14 17:27:29 -070044import static android.net.NetworkPolicyManager.isUidValidForPolicy;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070045import static android.net.NetworkTemplate.MATCH_ETHERNET;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070046import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
47import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070048import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
49import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070050import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070051import static android.text.format.DateUtils.DAY_IN_MILLIS;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070052import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey961e3042011-08-29 16:02:57 -070053import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey46645002011-07-27 21:11:21 -070054import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.readBooleanAttribute;
55import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.readIntAttribute;
56import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.readLongAttribute;
57import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.writeBooleanAttribute;
58import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.writeIntAttribute;
59import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.writeLongAttribute;
Jeff Sharkey497e4432011-06-14 17:27:29 -070060import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070061import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
62import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070063
Jeff Sharkeya4620792011-05-20 15:29:23 -070064import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070065import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070066import android.app.IProcessObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070067import android.app.Notification;
68import android.app.PendingIntent;
Jeff Sharkeya4620792011-05-20 15:29:23 -070069import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070070import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070071import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070072import android.content.Intent;
73import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070074import android.content.pm.ApplicationInfo;
75import android.content.pm.PackageManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070076import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070077import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070078import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070079import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070080import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070081import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -070082import android.net.INetworkStatsService;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070083import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070084import android.net.NetworkPolicy;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070085import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070086import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070087import android.net.NetworkTemplate;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070088import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070089import android.os.Environment;
90import android.os.Handler;
91import android.os.HandlerThread;
Ashish Sharma50fd36d2011-06-15 19:34:53 -070092import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -070093import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070094import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -070095import android.os.MessageQueue.IdleHandler;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070096import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -070097import android.os.RemoteException;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -070098import android.provider.Settings;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070099import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700100import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700101import android.text.format.Time;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700102import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700103import android.util.NtpTrustedTime;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700104import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700105import android.util.SparseArray;
106import android.util.SparseBooleanArray;
107import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700108import android.util.TrustedTime;
109import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700110
Jeff Sharkey497e4432011-06-14 17:27:29 -0700111import com.android.internal.R;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700112import com.android.internal.os.AtomicFile;
113import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700114import com.android.internal.util.Objects;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700115import com.google.android.collect.Lists;
116import com.google.android.collect.Maps;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700117import com.google.android.collect.Sets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700118
119import org.xmlpull.v1.XmlPullParser;
120import org.xmlpull.v1.XmlPullParserException;
121import org.xmlpull.v1.XmlSerializer;
122
123import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700124import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700125import java.io.FileInputStream;
126import java.io.FileNotFoundException;
127import java.io.FileOutputStream;
128import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700129import java.io.PrintWriter;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700130import java.net.ProtocolException;
131import java.util.ArrayList;
132import java.util.Arrays;
133import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700134import java.util.HashSet;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700135import java.util.List;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700136import java.util.Map;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700137
138import libcore.io.IoUtils;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700139
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700140/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700141 * Service that maintains low-level network policy rules, using
142 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700143 * <p>
144 * Derives active rules by combining a given policy with other system status,
145 * and delivers to listeners, such as {@link ConnectivityManager}, for
146 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700147 */
148public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
149 private static final String TAG = "NetworkPolicy";
150 private static final boolean LOGD = true;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700151 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700152
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700153 private static final int VERSION_INIT = 1;
154 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700155 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700156
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700157 private static final long KB_IN_BYTES = 1024;
158 private static final long MB_IN_BYTES = KB_IN_BYTES * 1024;
159 private static final long GB_IN_BYTES = MB_IN_BYTES * 1024;
160
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700161 // @VisibleForTesting
162 public static final int TYPE_WARNING = 0x1;
163 public static final int TYPE_LIMIT = 0x2;
164 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700165
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700166 private static final String TAG_POLICY_LIST = "policy-list";
167 private static final String TAG_NETWORK_POLICY = "network-policy";
168 private static final String TAG_UID_POLICY = "uid-policy";
169
170 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700171 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700172 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
173 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
174 private static final String ATTR_CYCLE_DAY = "cycleDay";
175 private static final String ATTR_WARNING_BYTES = "warningBytes";
176 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700177 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700178 private static final String ATTR_UID = "uid";
179 private static final String ATTR_POLICY = "policy";
180
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700181 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
182
183 // @VisibleForTesting
184 public static final String ACTION_ALLOW_BACKGROUND =
185 "com.android.server.action.ACTION_ALLOW_BACKGROUND";
186
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700187 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
188
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700189 private static final int MSG_RULES_CHANGED = 1;
190 private static final int MSG_METERED_IFACES_CHANGED = 2;
191 private static final int MSG_FOREGROUND_ACTIVITIES_CHANGED = 3;
192 private static final int MSG_PROCESS_DIED = 4;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700193
Jeff Sharkey75279902011-05-24 18:39:45 -0700194 private final Context mContext;
195 private final IActivityManager mActivityManager;
196 private final IPowerManager mPowerManager;
197 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700198 private final INetworkManagementService mNetworkManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700199 private final TrustedTime mTime;
200
201 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700202 private INotificationManager mNotifManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700203
Jeff Sharkey75279902011-05-24 18:39:45 -0700204 private final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700205
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700206 private volatile boolean mScreenOn;
207 private volatile boolean mRestrictBackground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700208
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700209 private final boolean mSuppressDefaultPolicy;
210
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700211 /** Defined network policies. */
212 private HashMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = Maps.newHashMap();
213 /** Currently active network rules for ifaces. */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700214 private HashMap<NetworkPolicy, String[]> mNetworkRules = Maps.newHashMap();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700215
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700216 /** Defined UID policies. */
Jeff Sharkeya4620792011-05-20 15:29:23 -0700217 private SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700218 /** Currently derived rules for each UID. */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700219 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700220
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700221 /** Set of ifaces that are metered. */
222 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700223 /** Set of over-limit templates that have been notified. */
224 private HashSet<NetworkTemplate> mOverLimitNotified = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700225
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700226 /** Set of currently active {@link Notification} tags. */
227 private HashSet<String> mActiveNotifs = Sets.newHashSet();
228 /** Current values from {@link #setPolicyDataEnable(int, boolean)}. */
229 private SparseBooleanArray mActiveNetworkEnabled = new SparseBooleanArray();
230
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700231 /** Foreground at both UID and PID granularity. */
Jeff Sharkeya4620792011-05-20 15:29:23 -0700232 private SparseBooleanArray mUidForeground = new SparseBooleanArray();
233 private SparseArray<SparseBooleanArray> mUidPidForeground = new SparseArray<
234 SparseBooleanArray>();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700235
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700236 private final RemoteCallbackList<INetworkPolicyListener> mListeners = new RemoteCallbackList<
237 INetworkPolicyListener>();
238
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700239 private final HandlerThread mHandlerThread;
240 private final Handler mHandler;
241
242 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700243
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700244 // TODO: keep whitelist of system-critical services that should never have
245 // rules enforced, such as system, phone, and radio UIDs.
246
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700247 // TODO: migrate notifications to SystemUI
248
Jeff Sharkey75279902011-05-24 18:39:45 -0700249 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700250 IPowerManager powerManager, INetworkStatsService networkStats,
251 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700252 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700253 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700254 }
255
256 private static File getSystemDir() {
257 return new File(Environment.getDataDirectory(), "system");
258 }
259
260 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700261 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700262 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
263 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700264 mContext = checkNotNull(context, "missing context");
265 mActivityManager = checkNotNull(activityManager, "missing activityManager");
266 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700267 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700268 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700269 mTime = checkNotNull(time, "missing TrustedTime");
270
271 mHandlerThread = new HandlerThread(TAG);
272 mHandlerThread.start();
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700273 mHandler = new Handler(mHandlerThread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700274
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700275 mSuppressDefaultPolicy = suppressDefaultPolicy;
276
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700277 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
278 }
279
280 public void bindConnectivityManager(IConnectivityManager connManager) {
281 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700282 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700283
Jeff Sharkey497e4432011-06-14 17:27:29 -0700284 public void bindNotificationManager(INotificationManager notifManager) {
285 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
286 }
287
Jeff Sharkeya4620792011-05-20 15:29:23 -0700288 public void systemReady() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700289 synchronized (mRulesLock) {
290 // read policy from disk
291 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700292
293 if (mRestrictBackground) {
294 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700295 updateNotificationsLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700296 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700297 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700298
Jeff Sharkeya4620792011-05-20 15:29:23 -0700299 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700300
Jeff Sharkeya4620792011-05-20 15:29:23 -0700301 try {
302 mActivityManager.registerProcessObserver(mProcessObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700303 mNetworkManager.registerObserver(mAlertObserver);
304 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700305 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700306 }
307
Jeff Sharkeya4620792011-05-20 15:29:23 -0700308 // TODO: traverse existing processes to know foreground state, or have
309 // activitymanager dispatch current state when new observer attached.
310
311 final IntentFilter screenFilter = new IntentFilter();
312 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
313 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700314 mContext.registerReceiver(mScreenReceiver, screenFilter, null, mHandler);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700315
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700316 // watch for network interfaces to be claimed
Jeff Sharkey961e3042011-08-29 16:02:57 -0700317 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION_IMMEDIATE);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700318 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
319
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700320 // listen for package/uid changes to update policy
321 final IntentFilter packageFilter = new IntentFilter();
322 packageFilter.addAction(ACTION_PACKAGE_ADDED);
323 packageFilter.addAction(ACTION_UID_REMOVED);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700324 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700325
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700326 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700327 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
328 mContext.registerReceiver(
329 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
330
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700331 // listen for restrict background changes from notifications
332 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
333 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
334
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700335 }
336
Jeff Sharkeya4620792011-05-20 15:29:23 -0700337 private IProcessObserver mProcessObserver = new IProcessObserver.Stub() {
338 @Override
339 public void onForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700340 mHandler.obtainMessage(MSG_FOREGROUND_ACTIVITIES_CHANGED,
341 pid, uid, foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700342 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700343
344 @Override
345 public void onProcessDied(int pid, int uid) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700346 mHandler.obtainMessage(MSG_PROCESS_DIED, pid, uid).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700347 }
348 };
349
350 private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
351 @Override
352 public void onReceive(Context context, Intent intent) {
353 synchronized (mRulesLock) {
354 // screen-related broadcasts are protected by system, no need
355 // for permissions check.
356 updateScreenOn();
357 }
358 }
359 };
360
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700361 private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700362 @Override
363 public void onReceive(Context context, Intent intent) {
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700364 // on background handler thread, and PACKAGE_ADDED and UID_REMOVED
365 // are protected broadcasts.
366
367 final String action = intent.getAction();
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700368 final int uid = intent.getIntExtra(EXTRA_UID, 0);
369 synchronized (mRulesLock) {
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700370 if (ACTION_PACKAGE_ADDED.equals(action)) {
371 // update rules for UID, since it might be subject to
372 // global background data policy.
373 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
374 updateRulesForUidLocked(uid);
375
376 } else if (ACTION_UID_REMOVED.equals(action)) {
377 // remove any policy and update rules to clean up.
378 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
379 mUidPolicy.delete(uid);
380 updateRulesForUidLocked(uid);
381 writePolicyLocked();
382 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700383 }
384 }
385 };
386
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700387 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700388 * Receiver that watches for {@link INetworkStatsService} updates, which we
389 * use to check against {@link NetworkPolicy#warningBytes}.
390 */
391 private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
392 @Override
393 public void onReceive(Context context, Intent intent) {
394 // on background handler thread, and verified
395 // READ_NETWORK_USAGE_HISTORY permission above.
396
397 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700398 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700399 updateNotificationsLocked();
400 }
401 }
402 };
403
404 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700405 * Receiver that watches for {@link Notification} control of
406 * {@link #mRestrictBackground}.
407 */
408 private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
409 @Override
410 public void onReceive(Context context, Intent intent) {
411 // on background handler thread, and verified MANAGE_NETWORK_POLICY
412 // permission above.
413
414 setRestrictBackground(false);
415 }
416 };
417
418 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700419 * Observer that watches for {@link INetworkManagementService} alerts.
420 */
421 private INetworkManagementEventObserver mAlertObserver = new NetworkAlertObserver() {
422 @Override
423 public void limitReached(String limitName, String iface) {
424 // only someone like NMS should be calling us
425 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
426
427 synchronized (mRulesLock) {
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700428 if (mMeteredIfaces.contains(iface) && !LIMIT_GLOBAL_ALERT.equals(limitName)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700429 try {
430 // force stats update to make sure we have numbers that
431 // caused alert to trigger.
432 mNetworkStats.forceUpdate();
433 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700434 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700435 }
436
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700437 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700438 updateNotificationsLocked();
439 }
440 }
441 }
442 };
443
444 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700445 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
446 * to show visible notifications as needed.
447 */
448 private void updateNotificationsLocked() {
449 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
450
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700451 // keep track of previously active notifications
452 final HashSet<String> beforeNotifs = Sets.newHashSet();
453 beforeNotifs.addAll(mActiveNotifs);
454 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700455
456 // TODO: when switching to kernel notifications, compute next future
457 // cycle boundary to recompute notifications.
458
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700459 // examine stats for each active policy
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700460 final long currentTime = currentTimeMillis(true);
461 for (NetworkPolicy policy : mNetworkPolicy.values()) {
462 // ignore policies that aren't relevant to user
463 if (!isTemplateRelevant(policy.template)) continue;
464
Jeff Sharkey497e4432011-06-14 17:27:29 -0700465 final long start = computeLastCycleBoundary(currentTime, policy);
466 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700467 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700468
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700469 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700470 if (policy.lastSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700471 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
472 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700473 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
474 notifyOverLimitLocked(policy.template);
475 }
476
Jeff Sharkey497e4432011-06-14 17:27:29 -0700477 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700478 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700479
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700480 if (policy.warningBytes != WARNING_DISABLED && totalBytes >= policy.warningBytes) {
481 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700482 }
483 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700484 }
485
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700486 // ongoing notification when restricting background data
487 if (mRestrictBackground) {
488 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700489 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700490
491 // cancel stale notifications that we didn't renew above
492 for (String tag : beforeNotifs) {
493 if (!mActiveNotifs.contains(tag)) {
494 cancelNotification(tag);
495 }
496 }
497 }
498
499 /**
500 * Test if given {@link NetworkTemplate} is relevant to user based on
501 * current device state, such as when {@link #getActiveSubscriberId()}
502 * matches. This is regardless of data connection status.
503 */
504 private boolean isTemplateRelevant(NetworkTemplate template) {
505 switch (template.getMatchRule()) {
506 case MATCH_MOBILE_3G_LOWER:
507 case MATCH_MOBILE_4G:
508 case MATCH_MOBILE_ALL:
509 // mobile templates are relevant when subscriberid is active
510 return Objects.equal(getActiveSubscriberId(), template.getSubscriberId());
511 }
512 return true;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700513 }
514
515 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700516 * Notify that given {@link NetworkTemplate} is over
517 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
518 */
519 private void notifyOverLimitLocked(NetworkTemplate template) {
520 if (!mOverLimitNotified.contains(template)) {
521 mContext.startActivity(buildNetworkOverLimitIntent(template));
522 mOverLimitNotified.add(template);
523 }
524 }
525
526 private void notifyUnderLimitLocked(NetworkTemplate template) {
527 mOverLimitNotified.remove(template);
528 }
529
530 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700531 * Build unique tag that identifies an active {@link NetworkPolicy}
532 * notification of a specific type, like {@link #TYPE_LIMIT}.
533 */
534 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700535 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700536 }
537
538 /**
539 * Show notification for combined {@link NetworkPolicy} and specific type,
540 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
541 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700542 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700543 final String tag = buildNotificationTag(policy, type);
544 final Notification.Builder builder = new Notification.Builder(mContext);
545 builder.setOnlyAlertOnce(true);
546 builder.setOngoing(true);
547
548 final Resources res = mContext.getResources();
549 switch (type) {
550 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700551 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700552 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700553
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700554 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700555 builder.setTicker(title);
556 builder.setContentTitle(title);
557 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700558
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700559 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700560 builder.setContentIntent(PendingIntent.getActivity(
561 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700562 break;
563 }
564 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700565 final CharSequence body = res.getText(R.string.data_usage_limit_body);
566
567 final CharSequence title;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700568 switch (policy.template.getMatchRule()) {
569 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700570 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700571 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700572 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700573 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700574 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700575 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700576 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700577 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700578 case MATCH_WIFI:
579 title = res.getText(R.string.data_usage_wifi_limit_title);
580 break;
581 default:
582 title = null;
583 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700584 }
585
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700586 builder.setSmallIcon(R.drawable.stat_notify_disabled);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700587 builder.setTicker(title);
588 builder.setContentTitle(title);
589 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700590
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700591 final Intent intent = buildNetworkOverLimitIntent(policy.template);
592 builder.setContentIntent(PendingIntent.getActivity(
593 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
594 break;
595 }
596 case TYPE_LIMIT_SNOOZED: {
597 final long overBytes = totalBytes - policy.limitBytes;
598 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
599 Formatter.formatFileSize(mContext, overBytes));
600
601 final CharSequence title;
602 switch (policy.template.getMatchRule()) {
603 case MATCH_MOBILE_3G_LOWER:
604 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
605 break;
606 case MATCH_MOBILE_4G:
607 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
608 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700609 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700610 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
611 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700612 case MATCH_WIFI:
613 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
614 break;
615 default:
616 title = null;
617 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700618 }
619
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700620 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700621 builder.setTicker(title);
622 builder.setContentTitle(title);
623 builder.setContentText(body);
624
625 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700626 builder.setContentIntent(PendingIntent.getActivity(
627 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700628 break;
629 }
630 }
631
632 // TODO: move to NotificationManager once we can mock it
633 try {
634 final String packageName = mContext.getPackageName();
635 final int[] idReceived = new int[1];
636 mNotifManager.enqueueNotificationWithTag(
637 packageName, tag, 0x0, builder.getNotification(), idReceived);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700638 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700639 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700640 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700641 }
642 }
643
644 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700645 * Show ongoing notification to reflect that {@link #mRestrictBackground}
646 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700647 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700648 private void enqueueRestrictedNotification(String tag) {
649 final Resources res = mContext.getResources();
650 final Notification.Builder builder = new Notification.Builder(mContext);
651
652 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
653 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
654
655 builder.setOnlyAlertOnce(true);
656 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700657 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700658 builder.setTicker(title);
659 builder.setContentTitle(title);
660 builder.setContentText(body);
661
662 final Intent intent = buildAllowBackgroundDataIntent();
663 builder.setContentIntent(
664 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700665
666 // TODO: move to NotificationManager once we can mock it
667 try {
668 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700669 final int[] idReceived = new int[1];
670 mNotifManager.enqueueNotificationWithTag(packageName, tag,
671 0x0, builder.getNotification(), idReceived);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700672 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700673 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700674 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700675 }
676 }
677
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700678 private void cancelNotification(String tag) {
679 // TODO: move to NotificationManager once we can mock it
680 try {
681 final String packageName = mContext.getPackageName();
682 mNotifManager.cancelNotificationWithTag(
683 packageName, tag, 0x0);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700684 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700685 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700686 }
687 }
688
689 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700690 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700691 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700692 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700693 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700694 @Override
695 public void onReceive(Context context, Intent intent) {
696 // on background handler thread, and verified CONNECTIVITY_INTERNAL
697 // permission above.
698 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700699 ensureActiveMobilePolicyLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700700 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700701 updateNetworkRulesLocked();
702 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700703 }
704 }
705 };
706
707 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700708 * Proactively control network data connections when they exceed
709 * {@link NetworkPolicy#limitBytes}.
710 */
711 private void updateNetworkEnabledLocked() {
712 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
713
714 // TODO: reset any policy-disabled networks when any policy is removed
715 // completely, which is currently rare case.
716
717 final long currentTime = currentTimeMillis(true);
718 for (NetworkPolicy policy : mNetworkPolicy.values()) {
719 // shortcut when policy has no limit
720 if (policy.limitBytes == LIMIT_DISABLED) {
721 setNetworkTemplateEnabled(policy.template, true);
722 continue;
723 }
724
725 final long start = computeLastCycleBoundary(currentTime, policy);
726 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700727 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700728
729 // disable data connection when over limit and not snoozed
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700730 final boolean overLimit = policy.isOverLimit(totalBytes) && policy.lastSnooze < start;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700731 final boolean enabled = !overLimit;
732
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700733 setNetworkTemplateEnabled(policy.template, enabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700734 }
735 }
736
737 /**
738 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}
739 * for the given {@link NetworkTemplate}.
740 */
741 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700742 switch (template.getMatchRule()) {
743 case MATCH_MOBILE_3G_LOWER:
744 case MATCH_MOBILE_4G:
745 case MATCH_MOBILE_ALL:
746 // TODO: offer more granular control over radio states once
747 // 4965893 is available.
748 if (Objects.equal(getActiveSubscriberId(), template.getSubscriberId())) {
749 setPolicyDataEnable(TYPE_MOBILE, enabled);
750 setPolicyDataEnable(TYPE_WIMAX, enabled);
751 }
752 break;
753 case MATCH_WIFI:
754 setPolicyDataEnable(TYPE_WIFI, enabled);
755 break;
756 case MATCH_ETHERNET:
757 setPolicyDataEnable(TYPE_ETHERNET, enabled);
758 break;
759 default:
760 throw new IllegalArgumentException("unexpected template");
761 }
762 }
763
764 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700765 * Examine all connected {@link NetworkState}, looking for
766 * {@link NetworkPolicy} that need to be enforced. When matches found, set
767 * remaining quota based on usage cycle and historical stats.
768 */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700769 private void updateNetworkRulesLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700770 if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700771
772 final NetworkState[] states;
773 try {
774 states = mConnManager.getAllNetworkState();
775 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700776 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700777 return;
778 }
779
780 // first, derive identity for all connected networks, which can be used
781 // to match against templates.
782 final HashMap<NetworkIdentity, String> networks = Maps.newHashMap();
783 for (NetworkState state : states) {
784 // stash identity and iface away for later use
785 if (state.networkInfo.isConnected()) {
786 final String iface = state.linkProperties.getInterfaceName();
787 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
788 networks.put(ident, iface);
789 }
790 }
791
792 // build list of rules and ifaces to enforce them against
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700793 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700794 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700795 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700796
797 // collect all active ifaces that match this template
798 ifaceList.clear();
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700799 for (Map.Entry<NetworkIdentity, String> entry : networks.entrySet()) {
800 final NetworkIdentity ident = entry.getKey();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700801 if (policy.template.matches(ident)) {
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700802 final String iface = entry.getValue();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700803 ifaceList.add(iface);
804 }
805 }
806
807 if (ifaceList.size() > 0) {
808 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700809 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700810 }
811 }
812
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700813 final HashSet<String> newMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700814
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700815 // apply each policy that we found ifaces for; compute remaining data
816 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700817 final long currentTime = currentTimeMillis(true);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700818 for (NetworkPolicy policy : mNetworkRules.keySet()) {
819 final String[] ifaces = mNetworkRules.get(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700820
821 final long start = computeLastCycleBoundary(currentTime, policy);
822 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700823 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700824
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700825 if (LOGD) {
826 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700827 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700828 }
829
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700830 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700831 if (hasLimit) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700832 final long quotaBytes;
833 if (policy.lastSnooze >= start) {
834 // snoozing past quota, but we still need to restrict apps,
835 // so push really high quota.
836 quotaBytes = Long.MAX_VALUE;
837 } else {
838 // remaining "quota" bytes are based on total usage in
839 // current cycle. kernel doesn't like 0-byte rules, so we
840 // set 1-byte quota and disable the radio later.
841 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
842 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700843
844 if (ifaces.length > 1) {
845 // TODO: switch to shared quota once NMS supports
846 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700847 }
848
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700849 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700850 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700851 setInterfaceQuota(iface, quotaBytes);
852 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700853 }
854 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700855 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700856
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700857 // remove quota on any trailing interfaces
858 for (String iface : mMeteredIfaces) {
859 if (!newMeteredIfaces.contains(iface)) {
860 removeInterfaceQuota(iface);
861 }
862 }
863 mMeteredIfaces = newMeteredIfaces;
864
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700865 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700866 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700867 }
868
869 /**
870 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
871 * have at least a default mobile policy defined.
872 */
873 private void ensureActiveMobilePolicyLocked() {
874 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700875 if (mSuppressDefaultPolicy) return;
876
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700877 final String subscriberId = getActiveSubscriberId();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700878 final NetworkIdentity probeIdent = new NetworkIdentity(
Jeff Sharkey5dc0c262011-06-19 22:21:05 -0700879 TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, false);
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700880
881 // examine to see if any policy is defined for active mobile
882 boolean mobileDefined = false;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700883 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700884 if (policy.template.matches(probeIdent)) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700885 mobileDefined = true;
886 }
887 }
888
889 if (!mobileDefined) {
890 Slog.i(TAG, "no policy for active mobile network; generating default policy");
891
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700892 // build default mobile policy, and assume usage cycle starts today
893 final long warningBytes = mContext.getResources().getInteger(
894 com.android.internal.R.integer.config_networkPolicyDefaultWarning)
895 * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700896
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700897 final Time time = new Time(Time.TIMEZONE_UTC);
898 time.setToNow();
899 final int cycleDay = time.monthDay;
900
Jeff Sharkey4e814c32011-07-14 20:37:37 -0700901 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700902 mNetworkPolicy.put(template, new NetworkPolicy(
903 template, cycleDay, warningBytes, LIMIT_DISABLED, SNOOZE_NEVER));
Jeff Sharkeyfcc79772011-06-13 22:28:34 -0700904 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700905 }
906 }
907
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700908 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700909 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700910
911 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700912 mNetworkPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700913 mUidPolicy.clear();
914
915 FileInputStream fis = null;
916 try {
917 fis = mPolicyFile.openRead();
918 final XmlPullParser in = Xml.newPullParser();
919 in.setInput(fis, null);
920
921 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700922 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700923 while ((type = in.next()) != END_DOCUMENT) {
924 final String tag = in.getName();
925 if (type == START_TAG) {
926 if (TAG_POLICY_LIST.equals(tag)) {
927 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -0700928 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
929 mRestrictBackground = readBooleanAttribute(
930 in, ATTR_RESTRICT_BACKGROUND);
931 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700932 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -0700933 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700934
935 } else if (TAG_NETWORK_POLICY.equals(tag)) {
936 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
937 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700938 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
939 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
940 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700941 final long lastSnooze;
942 if (version >= VERSION_ADDED_SNOOZE) {
943 lastSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
944 } else {
945 lastSnooze = SNOOZE_NEVER;
946 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700947
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700948 final NetworkTemplate template = new NetworkTemplate(
949 networkTemplate, subscriberId);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700950 mNetworkPolicy.put(template, new NetworkPolicy(
951 template, cycleDay, warningBytes, limitBytes, lastSnooze));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700952
953 } else if (TAG_UID_POLICY.equals(tag)) {
954 final int uid = readIntAttribute(in, ATTR_UID);
955 final int policy = readIntAttribute(in, ATTR_POLICY);
956
Jeff Sharkey497e4432011-06-14 17:27:29 -0700957 if (isUidValidForPolicy(mContext, uid)) {
958 setUidPolicyUnchecked(uid, policy, false);
959 } else {
960 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
961 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700962 }
963 }
964 }
965
966 } catch (FileNotFoundException e) {
967 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700968 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700969 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700970 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700971 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700972 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700973 } finally {
974 IoUtils.closeQuietly(fis);
975 }
976 }
977
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700978 /**
979 * Upgrade legacy background data flags, notifying listeners of one last
980 * change to always-true.
981 */
982 private void upgradeLegacyBackgroundData() {
983 mRestrictBackground = Settings.Secure.getInt(
984 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
985
986 // kick off one last broadcast if restricted
987 if (mRestrictBackground) {
988 final Intent broadcast = new Intent(
989 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
990 mContext.sendBroadcast(broadcast);
991 }
992 }
993
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700994 private void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700995 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700996
997 FileOutputStream fos = null;
998 try {
999 fos = mPolicyFile.startWrite();
1000
1001 XmlSerializer out = new FastXmlSerializer();
1002 out.setOutput(fos, "utf-8");
1003 out.startDocument(null, true);
1004
1005 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001006 writeIntAttribute(out, ATTR_VERSION, VERSION_ADDED_RESTRICT_BACKGROUND);
1007 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001008
1009 // write all known network policies
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001010 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001011 final NetworkTemplate template = policy.template;
1012
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001013 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001014 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1015 final String subscriberId = template.getSubscriberId();
1016 if (subscriberId != null) {
1017 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001018 }
1019 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
1020 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1021 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001022 writeLongAttribute(out, ATTR_LAST_SNOOZE, policy.lastSnooze);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001023 out.endTag(null, TAG_NETWORK_POLICY);
1024 }
1025
1026 // write all known uid policies
1027 for (int i = 0; i < mUidPolicy.size(); i++) {
1028 final int uid = mUidPolicy.keyAt(i);
1029 final int policy = mUidPolicy.valueAt(i);
1030
Jeff Sharkey497e4432011-06-14 17:27:29 -07001031 // skip writing empty policies
1032 if (policy == POLICY_NONE) continue;
1033
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001034 out.startTag(null, TAG_UID_POLICY);
1035 writeIntAttribute(out, ATTR_UID, uid);
1036 writeIntAttribute(out, ATTR_POLICY, policy);
1037 out.endTag(null, TAG_UID_POLICY);
1038 }
1039
1040 out.endTag(null, TAG_POLICY_LIST);
1041 out.endDocument();
1042
1043 mPolicyFile.finishWrite(fos);
1044 } catch (IOException e) {
1045 if (fos != null) {
1046 mPolicyFile.failWrite(fos);
1047 }
1048 }
1049 }
1050
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001051 @Override
1052 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001053 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001054
Jeff Sharkey497e4432011-06-14 17:27:29 -07001055 if (!isUidValidForPolicy(mContext, uid)) {
1056 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1057 }
1058
1059 setUidPolicyUnchecked(uid, policy, true);
1060 }
1061
1062 private void setUidPolicyUnchecked(int uid, int policy, boolean persist) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001063 final int oldPolicy;
Jeff Sharkeya4620792011-05-20 15:29:23 -07001064 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001065 oldPolicy = getUidPolicy(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001066 mUidPolicy.put(uid, policy);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001067
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001068 // uid policy changed, recompute rules and persist policy.
1069 updateRulesForUidLocked(uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001070 if (persist) {
1071 writePolicyLocked();
1072 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001073 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001074 }
1075
1076 @Override
1077 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001078 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1079
Jeff Sharkeya4620792011-05-20 15:29:23 -07001080 synchronized (mRulesLock) {
1081 return mUidPolicy.get(uid, POLICY_NONE);
1082 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001083 }
1084
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001085 @Override
1086 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001087 // TODO: create permission for observing network policy
1088 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1089
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001090 mListeners.register(listener);
1091
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001092 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001093 }
1094
1095 @Override
1096 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001097 // TODO: create permission for observing network policy
1098 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1099
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001100 mListeners.unregister(listener);
1101 }
1102
Jeff Sharkey1b861272011-05-22 00:34:52 -07001103 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001104 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001105 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1106
1107 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001108 mNetworkPolicy.clear();
1109 for (NetworkPolicy policy : policies) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001110 mNetworkPolicy.put(policy.template, policy);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001111 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001112
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001113 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001114 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001115 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001116 writePolicyLocked();
1117 }
1118 }
1119
1120 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001121 public NetworkPolicy[] getNetworkPolicies() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001122 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001123 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001124
1125 synchronized (mRulesLock) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001126 return mNetworkPolicy.values().toArray(new NetworkPolicy[mNetworkPolicy.size()]);
1127 }
1128 }
1129
1130 @Override
1131 public void snoozePolicy(NetworkTemplate template) {
1132 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1133
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001134 final long currentTime = currentTimeMillis(true);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001135 synchronized (mRulesLock) {
1136 // find and snooze local policy that matches
1137 final NetworkPolicy policy = mNetworkPolicy.get(template);
1138 if (policy == null) {
1139 throw new IllegalArgumentException("unable to find policy for " + template);
1140 }
1141
1142 policy.lastSnooze = currentTime;
1143
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001144 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001145 updateNetworkRulesLocked();
1146 updateNotificationsLocked();
1147 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001148 }
1149 }
1150
1151 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001152 public void setRestrictBackground(boolean restrictBackground) {
1153 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1154
1155 synchronized (mRulesLock) {
1156 mRestrictBackground = restrictBackground;
1157 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001158 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001159 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001160 }
1161 }
1162
1163 @Override
1164 public boolean getRestrictBackground() {
1165 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1166
1167 synchronized (mRulesLock) {
1168 return mRestrictBackground;
1169 }
1170 }
1171
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001172 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
1173 for (NetworkPolicy policy : mNetworkPolicy.values()) {
1174 if (policy.template.matches(ident)) {
1175 return policy;
1176 }
1177 }
1178 return null;
1179 }
1180
1181 @Override
1182 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1183 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1184
1185 // only returns usage summary, so we don't require caller to have
1186 // READ_NETWORK_USAGE_HISTORY.
1187 final long token = Binder.clearCallingIdentity();
1188 try {
1189 return getNetworkQuotaInfoUnchecked(state);
1190 } finally {
1191 Binder.restoreCallingIdentity(token);
1192 }
1193 }
1194
1195 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1196 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1197
1198 final NetworkPolicy policy;
1199 synchronized (mRulesLock) {
1200 policy = findPolicyForNetworkLocked(ident);
1201 }
1202
1203 if (policy == null) {
1204 // missing policy means we can't derive useful quota info
1205 return null;
1206 }
1207
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001208 final long currentTime = currentTimeMillis(false);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001209
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001210 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001211 final long start = computeLastCycleBoundary(currentTime, policy);
1212 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001213 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001214
1215 // report soft and hard limits under policy
1216 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1217 : NetworkQuotaInfo.NO_LIMIT;
1218 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1219 : NetworkQuotaInfo.NO_LIMIT;
1220
1221 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1222 }
1223
Jeff Sharkey46645002011-07-27 21:11:21 -07001224 @Override
Jeff Sharkey1b861272011-05-22 00:34:52 -07001225 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001226 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001227
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001228 final HashSet<String> argSet = new HashSet<String>();
1229 for (String arg : args) {
1230 argSet.add(arg);
1231 }
1232
Jeff Sharkey1b861272011-05-22 00:34:52 -07001233 synchronized (mRulesLock) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001234 if (argSet.contains("unsnooze")) {
1235 for (NetworkPolicy policy : mNetworkPolicy.values()) {
1236 policy.lastSnooze = SNOOZE_NEVER;
1237 }
1238 writePolicyLocked();
1239 fout.println("Wiped snooze timestamps");
1240 return;
1241 }
1242
Jeff Sharkey46645002011-07-27 21:11:21 -07001243 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001244 fout.println("Network policies:");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001245 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001246 fout.print(" "); fout.println(policy.toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001247 }
1248
Jeff Sharkey1b861272011-05-22 00:34:52 -07001249 fout.println("Policy status for known UIDs:");
1250
1251 final SparseBooleanArray knownUids = new SparseBooleanArray();
1252 collectKeys(mUidPolicy, knownUids);
1253 collectKeys(mUidForeground, knownUids);
1254 collectKeys(mUidRules, knownUids);
1255
1256 final int size = knownUids.size();
1257 for (int i = 0; i < size; i++) {
1258 final int uid = knownUids.keyAt(i);
1259 fout.print(" UID=");
1260 fout.print(uid);
1261
1262 fout.print(" policy=");
1263 final int policyIndex = mUidPolicy.indexOfKey(uid);
1264 if (policyIndex < 0) {
1265 fout.print("UNKNOWN");
1266 } else {
1267 dumpPolicy(fout, mUidPolicy.valueAt(policyIndex));
1268 }
1269
1270 fout.print(" foreground=");
1271 final int foregroundIndex = mUidPidForeground.indexOfKey(uid);
1272 if (foregroundIndex < 0) {
1273 fout.print("UNKNOWN");
1274 } else {
1275 dumpSparseBooleanArray(fout, mUidPidForeground.valueAt(foregroundIndex));
1276 }
1277
1278 fout.print(" rules=");
1279 final int rulesIndex = mUidRules.indexOfKey(uid);
1280 if (rulesIndex < 0) {
1281 fout.print("UNKNOWN");
1282 } else {
1283 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1284 }
1285
1286 fout.println();
1287 }
1288 }
1289 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001290
1291 @Override
1292 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001293 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1294
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001295 synchronized (mRulesLock) {
1296 // only really in foreground when screen is also on
1297 return mUidForeground.get(uid, false) && mScreenOn;
1298 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001299 }
1300
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001301 /**
1302 * Foreground for PID changed; recompute foreground at UID level. If
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001303 * changed, will trigger {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001304 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001305 private void computeUidForegroundLocked(int uid) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001306 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1307
1308 // current pid is dropping foreground; examine other pids
1309 boolean uidForeground = false;
1310 final int size = pidForeground.size();
1311 for (int i = 0; i < size; i++) {
1312 if (pidForeground.valueAt(i)) {
1313 uidForeground = true;
1314 break;
1315 }
1316 }
1317
1318 final boolean oldUidForeground = mUidForeground.get(uid, false);
1319 if (oldUidForeground != uidForeground) {
1320 // foreground changed, push updated rules
1321 mUidForeground.put(uid, uidForeground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001322 updateRulesForUidLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001323 }
1324 }
1325
Jeff Sharkeya4620792011-05-20 15:29:23 -07001326 private void updateScreenOn() {
1327 synchronized (mRulesLock) {
1328 try {
1329 mScreenOn = mPowerManager.isScreenOn();
1330 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001331 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07001332 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001333 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001334 }
1335 }
1336
1337 /**
1338 * Update rules that might be changed by {@link #mScreenOn} value.
1339 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001340 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07001341 // only update rules for anyone with foreground activities
1342 final int size = mUidForeground.size();
1343 for (int i = 0; i < size; i++) {
1344 if (mUidForeground.valueAt(i)) {
1345 final int uid = mUidForeground.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001346 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001347 }
1348 }
1349 }
1350
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001351 /**
Jeff Sharkey46645002011-07-27 21:11:21 -07001352 * Update rules that might be changed by {@link #mRestrictBackground} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001353 */
Jeff Sharkey46645002011-07-27 21:11:21 -07001354 private void updateRulesForRestrictBackgroundLocked() {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001355 // update rules for all installed applications
1356 final PackageManager pm = mContext.getPackageManager();
1357 final List<ApplicationInfo> apps = pm.getInstalledApplications(0);
1358 for (ApplicationInfo app : apps) {
1359 updateRulesForUidLocked(app.uid);
1360 }
1361
1362 // and catch system UIDs
1363 // TODO: keep in sync with android_filesystem_config.h
1364 for (int uid = 1000; uid <= 1025; uid++) {
1365 updateRulesForUidLocked(uid);
1366 }
1367 for (int uid = 2000; uid <= 2002; uid++) {
1368 updateRulesForUidLocked(uid);
1369 }
1370 for (int uid = 3000; uid <= 3007; uid++) {
1371 updateRulesForUidLocked(uid);
1372 }
1373 for (int uid = 9998; uid <= 9999; uid++) {
1374 updateRulesForUidLocked(uid);
1375 }
1376 }
1377
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001378 private void updateRulesForUidLocked(int uid) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001379 final int uidPolicy = getUidPolicy(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001380 final boolean uidForeground = isUidForeground(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001381
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001382 // derive active rules based on policy and active state
1383 int uidRules = RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001384 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1385 // uid in background, and policy says to block metered data
1386 uidRules = RULE_REJECT_METERED;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001387 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001388 if (!uidForeground && mRestrictBackground) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001389 // uid in background, and global background disabled
1390 uidRules = RULE_REJECT_METERED;
1391 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001392
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001393 // TODO: only dispatch when rules actually change
1394
Jeff Sharkey350083e2011-06-29 10:45:16 -07001395 if (uidRules == RULE_ALLOW_ALL) {
1396 mUidRules.delete(uid);
1397 } else {
1398 mUidRules.put(uid, uidRules);
1399 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001400
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001401 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001402 setUidNetworkRules(uid, rejectMetered);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001403
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001404 // dispatch changed rule to existing listeners
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001405 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001406
1407 try {
1408 // adjust stats accounting based on foreground status
1409 mNetworkStats.setUidForeground(uid, uidForeground);
1410 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001411 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001412 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001413 }
1414
1415 private Handler.Callback mHandlerCallback = new Handler.Callback() {
1416 /** {@inheritDoc} */
1417 public boolean handleMessage(Message msg) {
1418 switch (msg.what) {
1419 case MSG_RULES_CHANGED: {
1420 final int uid = msg.arg1;
1421 final int uidRules = msg.arg2;
1422 final int length = mListeners.beginBroadcast();
1423 for (int i = 0; i < length; i++) {
1424 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1425 if (listener != null) {
1426 try {
1427 listener.onUidRulesChanged(uid, uidRules);
1428 } catch (RemoteException e) {
1429 }
1430 }
1431 }
1432 mListeners.finishBroadcast();
1433 return true;
1434 }
1435 case MSG_METERED_IFACES_CHANGED: {
1436 final String[] meteredIfaces = (String[]) msg.obj;
1437 final int length = mListeners.beginBroadcast();
1438 for (int i = 0; i < length; i++) {
1439 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1440 if (listener != null) {
1441 try {
1442 listener.onMeteredIfacesChanged(meteredIfaces);
1443 } catch (RemoteException e) {
1444 }
1445 }
1446 }
1447 mListeners.finishBroadcast();
1448 return true;
1449 }
Jeff Sharkey6f7af032011-11-01 18:25:15 -07001450 case MSG_FOREGROUND_ACTIVITIES_CHANGED: {
1451 final int pid = msg.arg1;
1452 final int uid = msg.arg2;
1453 final boolean foregroundActivities = (Boolean) msg.obj;
1454
1455 synchronized (mRulesLock) {
1456 // because a uid can have multiple pids running inside, we need to
1457 // remember all pid states and summarize foreground at uid level.
1458
1459 // record foreground for this specific pid
1460 SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1461 if (pidForeground == null) {
1462 pidForeground = new SparseBooleanArray(2);
1463 mUidPidForeground.put(uid, pidForeground);
1464 }
1465 pidForeground.put(pid, foregroundActivities);
1466 computeUidForegroundLocked(uid);
1467 }
1468 return true;
1469 }
1470 case MSG_PROCESS_DIED: {
1471 final int pid = msg.arg1;
1472 final int uid = msg.arg2;
1473
1474 synchronized (mRulesLock) {
1475 // clear records and recompute, when they exist
1476 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1477 if (pidForeground != null) {
1478 pidForeground.delete(pid);
1479 computeUidForegroundLocked(uid);
1480 }
1481 }
1482 return true;
1483 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001484 default: {
1485 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07001486 }
1487 }
1488 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001489 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001490
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001491 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001492 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001493 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001494 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001495 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001496 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001497 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001498 }
1499 }
1500
1501 private void removeInterfaceQuota(String iface) {
1502 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001503 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001504 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001505 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001506 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001507 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001508 }
1509 }
1510
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001511 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1512 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001513 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001514 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001515 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001516 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001517 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001518 }
1519 }
1520
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001521 /**
1522 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)},
1523 * dispatching only when actually changed.
1524 */
1525 private void setPolicyDataEnable(int networkType, boolean enabled) {
1526 synchronized (mActiveNetworkEnabled) {
1527 final boolean prevEnabled = mActiveNetworkEnabled.get(networkType, true);
1528 if (prevEnabled == enabled) return;
1529
1530 try {
1531 mConnManager.setPolicyDataEnable(networkType, enabled);
1532 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001533 // ignored; service lives in system_server
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001534 }
1535
1536 mActiveNetworkEnabled.put(networkType, enabled);
1537 }
1538 }
1539
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001540 private String getActiveSubscriberId() {
1541 final TelephonyManager telephony = (TelephonyManager) mContext.getSystemService(
1542 Context.TELEPHONY_SERVICE);
1543 return telephony.getSubscriberId();
1544 }
1545
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001546 private long getTotalBytes(NetworkTemplate template, long start, long end) {
1547 try {
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001548 return mNetworkStats.getSummaryForNetwork(template, start, end).getTotalBytes();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001549 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001550 // ignored; service lives in system_server
1551 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001552 }
1553 }
1554
1555 private long currentTimeMillis(boolean allowRefresh) {
1556 // try refreshing time source when stale
1557 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE && allowRefresh) {
1558 mTime.forceRefresh();
1559 }
1560
1561 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
1562 }
1563
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001564 private static Intent buildAllowBackgroundDataIntent() {
1565 return new Intent(ACTION_ALLOW_BACKGROUND);
1566 }
1567
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001568 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
1569 final Intent intent = new Intent();
1570 intent.setComponent(new ComponentName(
1571 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
1572 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1573 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
1574 return intent;
1575 }
1576
1577 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
1578 final Intent intent = new Intent();
1579 intent.setComponent(new ComponentName(
1580 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
1581 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1582 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
1583 return intent;
1584 }
1585
Jeff Sharkey163e6442011-10-31 16:37:52 -07001586 // @VisibleForTesting
1587 public void addIdleHandler(IdleHandler handler) {
1588 mHandler.getLooper().getQueue().addIdleHandler(handler);
1589 }
1590
Jeff Sharkey1b861272011-05-22 00:34:52 -07001591 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
1592 final int size = source.size();
1593 for (int i = 0; i < size; i++) {
1594 target.put(source.keyAt(i), true);
1595 }
1596 }
1597
1598 private static void collectKeys(SparseBooleanArray source, SparseBooleanArray target) {
1599 final int size = source.size();
1600 for (int i = 0; i < size; i++) {
1601 target.put(source.keyAt(i), true);
1602 }
1603 }
1604
1605 private static void dumpSparseBooleanArray(PrintWriter fout, SparseBooleanArray value) {
1606 fout.print("[");
1607 final int size = value.size();
1608 for (int i = 0; i < size; i++) {
1609 fout.print(value.keyAt(i) + "=" + value.valueAt(i));
1610 if (i < size - 1) fout.print(",");
1611 }
1612 fout.print("]");
1613 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001614
Jeff Sharkey46645002011-07-27 21:11:21 -07001615 public static class XmlUtils {
1616 public static int readIntAttribute(XmlPullParser in, String name) throws IOException {
1617 final String value = in.getAttributeValue(null, name);
1618 try {
1619 return Integer.parseInt(value);
1620 } catch (NumberFormatException e) {
1621 throw new ProtocolException("problem parsing " + name + "=" + value + " as int");
1622 }
1623 }
1624
1625 public static void writeIntAttribute(XmlSerializer out, String name, int value)
1626 throws IOException {
1627 out.attribute(null, name, Integer.toString(value));
1628 }
1629
1630 public static long readLongAttribute(XmlPullParser in, String name) throws IOException {
1631 final String value = in.getAttributeValue(null, name);
1632 try {
1633 return Long.parseLong(value);
1634 } catch (NumberFormatException e) {
1635 throw new ProtocolException("problem parsing " + name + "=" + value + " as long");
1636 }
1637 }
1638
1639 public static void writeLongAttribute(XmlSerializer out, String name, long value)
1640 throws IOException {
1641 out.attribute(null, name, Long.toString(value));
1642 }
1643
1644 public static boolean readBooleanAttribute(XmlPullParser in, String name) {
1645 final String value = in.getAttributeValue(null, name);
1646 return Boolean.parseBoolean(value);
1647 }
1648
1649 public static void writeBooleanAttribute(XmlSerializer out, String name, boolean value)
1650 throws IOException {
1651 out.attribute(null, name, Boolean.toString(value));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001652 }
1653 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001654}