blob: 8c0f1e01f843bc827b780479a60cd60fab169830 [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 Sharkey7e25b0e2011-11-08 15:43:12 -0800193 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700194
Jeff Sharkey75279902011-05-24 18:39:45 -0700195 private final Context mContext;
196 private final IActivityManager mActivityManager;
197 private final IPowerManager mPowerManager;
198 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700199 private final INetworkManagementService mNetworkManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700200 private final TrustedTime mTime;
201
202 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700203 private INotificationManager mNotifManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700204
Jeff Sharkey75279902011-05-24 18:39:45 -0700205 private final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700206
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700207 private volatile boolean mScreenOn;
208 private volatile boolean mRestrictBackground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700209
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700210 private final boolean mSuppressDefaultPolicy;
211
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700212 /** Defined network policies. */
213 private HashMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = Maps.newHashMap();
214 /** Currently active network rules for ifaces. */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700215 private HashMap<NetworkPolicy, String[]> mNetworkRules = Maps.newHashMap();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700216
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700217 /** Defined UID policies. */
Jeff Sharkeya4620792011-05-20 15:29:23 -0700218 private SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700219 /** Currently derived rules for each UID. */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700220 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700221
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700222 /** Set of ifaces that are metered. */
223 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700224 /** Set of over-limit templates that have been notified. */
225 private HashSet<NetworkTemplate> mOverLimitNotified = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700226
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700227 /** Set of currently active {@link Notification} tags. */
228 private HashSet<String> mActiveNotifs = Sets.newHashSet();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700229
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700230 /** Foreground at both UID and PID granularity. */
Jeff Sharkeya4620792011-05-20 15:29:23 -0700231 private SparseBooleanArray mUidForeground = new SparseBooleanArray();
232 private SparseArray<SparseBooleanArray> mUidPidForeground = new SparseArray<
233 SparseBooleanArray>();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700234
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700235 private final RemoteCallbackList<INetworkPolicyListener> mListeners = new RemoteCallbackList<
236 INetworkPolicyListener>();
237
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700238 private final HandlerThread mHandlerThread;
239 private final Handler mHandler;
240
241 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700242
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700243 // TODO: keep whitelist of system-critical services that should never have
244 // rules enforced, such as system, phone, and radio UIDs.
245
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700246 // TODO: migrate notifications to SystemUI
247
Jeff Sharkey75279902011-05-24 18:39:45 -0700248 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700249 IPowerManager powerManager, INetworkStatsService networkStats,
250 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700251 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700252 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700253 }
254
255 private static File getSystemDir() {
256 return new File(Environment.getDataDirectory(), "system");
257 }
258
259 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700260 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700261 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
262 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700263 mContext = checkNotNull(context, "missing context");
264 mActivityManager = checkNotNull(activityManager, "missing activityManager");
265 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700266 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700267 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700268 mTime = checkNotNull(time, "missing TrustedTime");
269
270 mHandlerThread = new HandlerThread(TAG);
271 mHandlerThread.start();
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700272 mHandler = new Handler(mHandlerThread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700273
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700274 mSuppressDefaultPolicy = suppressDefaultPolicy;
275
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700276 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
277 }
278
279 public void bindConnectivityManager(IConnectivityManager connManager) {
280 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700281 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700282
Jeff Sharkey497e4432011-06-14 17:27:29 -0700283 public void bindNotificationManager(INotificationManager notifManager) {
284 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
285 }
286
Jeff Sharkeya4620792011-05-20 15:29:23 -0700287 public void systemReady() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700288 synchronized (mRulesLock) {
289 // read policy from disk
290 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700291
292 if (mRestrictBackground) {
293 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700294 updateNotificationsLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700295 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700296 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700297
Jeff Sharkeya4620792011-05-20 15:29:23 -0700298 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700299
Jeff Sharkeya4620792011-05-20 15:29:23 -0700300 try {
301 mActivityManager.registerProcessObserver(mProcessObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700302 mNetworkManager.registerObserver(mAlertObserver);
303 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700304 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700305 }
306
Jeff Sharkeya4620792011-05-20 15:29:23 -0700307 // TODO: traverse existing processes to know foreground state, or have
308 // activitymanager dispatch current state when new observer attached.
309
310 final IntentFilter screenFilter = new IntentFilter();
311 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
312 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700313 mContext.registerReceiver(mScreenReceiver, screenFilter, null, mHandler);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700314
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700315 // watch for network interfaces to be claimed
Jeff Sharkey961e3042011-08-29 16:02:57 -0700316 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION_IMMEDIATE);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700317 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
318
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700319 // listen for package/uid changes to update policy
320 final IntentFilter packageFilter = new IntentFilter();
321 packageFilter.addAction(ACTION_PACKAGE_ADDED);
322 packageFilter.addAction(ACTION_UID_REMOVED);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700323 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700324
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700325 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700326 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
327 mContext.registerReceiver(
328 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
329
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700330 // listen for restrict background changes from notifications
331 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
332 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
333
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700334 }
335
Jeff Sharkeya4620792011-05-20 15:29:23 -0700336 private IProcessObserver mProcessObserver = new IProcessObserver.Stub() {
337 @Override
338 public void onForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700339 mHandler.obtainMessage(MSG_FOREGROUND_ACTIVITIES_CHANGED,
340 pid, uid, foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700341 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700342
343 @Override
344 public void onProcessDied(int pid, int uid) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700345 mHandler.obtainMessage(MSG_PROCESS_DIED, pid, uid).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700346 }
347 };
348
349 private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
350 @Override
351 public void onReceive(Context context, Intent intent) {
352 synchronized (mRulesLock) {
353 // screen-related broadcasts are protected by system, no need
354 // for permissions check.
355 updateScreenOn();
356 }
357 }
358 };
359
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700360 private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700361 @Override
362 public void onReceive(Context context, Intent intent) {
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700363 // on background handler thread, and PACKAGE_ADDED and UID_REMOVED
364 // are protected broadcasts.
365
366 final String action = intent.getAction();
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700367 final int uid = intent.getIntExtra(EXTRA_UID, 0);
368 synchronized (mRulesLock) {
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700369 if (ACTION_PACKAGE_ADDED.equals(action)) {
370 // update rules for UID, since it might be subject to
371 // global background data policy.
372 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
373 updateRulesForUidLocked(uid);
374
375 } else if (ACTION_UID_REMOVED.equals(action)) {
376 // remove any policy and update rules to clean up.
377 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
378 mUidPolicy.delete(uid);
379 updateRulesForUidLocked(uid);
380 writePolicyLocked();
381 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700382 }
383 }
384 };
385
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700386 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700387 * Receiver that watches for {@link INetworkStatsService} updates, which we
388 * use to check against {@link NetworkPolicy#warningBytes}.
389 */
390 private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
391 @Override
392 public void onReceive(Context context, Intent intent) {
393 // on background handler thread, and verified
394 // READ_NETWORK_USAGE_HISTORY permission above.
395
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800396 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700397 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
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800427 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
428 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700429 }
430 }
431 };
432
433 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700434 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
435 * to show visible notifications as needed.
436 */
437 private void updateNotificationsLocked() {
438 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
439
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700440 // keep track of previously active notifications
441 final HashSet<String> beforeNotifs = Sets.newHashSet();
442 beforeNotifs.addAll(mActiveNotifs);
443 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700444
445 // TODO: when switching to kernel notifications, compute next future
446 // cycle boundary to recompute notifications.
447
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700448 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800449 final long currentTime = currentTimeMillis();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700450 for (NetworkPolicy policy : mNetworkPolicy.values()) {
451 // ignore policies that aren't relevant to user
452 if (!isTemplateRelevant(policy.template)) continue;
453
Jeff Sharkey497e4432011-06-14 17:27:29 -0700454 final long start = computeLastCycleBoundary(currentTime, policy);
455 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700456 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700457
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700458 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700459 if (policy.lastSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700460 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
461 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700462 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
463 notifyOverLimitLocked(policy.template);
464 }
465
Jeff Sharkey497e4432011-06-14 17:27:29 -0700466 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700467 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700468
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700469 if (policy.warningBytes != WARNING_DISABLED && totalBytes >= policy.warningBytes) {
470 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700471 }
472 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700473 }
474
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700475 // ongoing notification when restricting background data
476 if (mRestrictBackground) {
477 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700478 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700479
480 // cancel stale notifications that we didn't renew above
481 for (String tag : beforeNotifs) {
482 if (!mActiveNotifs.contains(tag)) {
483 cancelNotification(tag);
484 }
485 }
486 }
487
488 /**
489 * Test if given {@link NetworkTemplate} is relevant to user based on
490 * current device state, such as when {@link #getActiveSubscriberId()}
491 * matches. This is regardless of data connection status.
492 */
493 private boolean isTemplateRelevant(NetworkTemplate template) {
494 switch (template.getMatchRule()) {
495 case MATCH_MOBILE_3G_LOWER:
496 case MATCH_MOBILE_4G:
497 case MATCH_MOBILE_ALL:
498 // mobile templates are relevant when subscriberid is active
499 return Objects.equal(getActiveSubscriberId(), template.getSubscriberId());
500 }
501 return true;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700502 }
503
504 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700505 * Notify that given {@link NetworkTemplate} is over
506 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
507 */
508 private void notifyOverLimitLocked(NetworkTemplate template) {
509 if (!mOverLimitNotified.contains(template)) {
510 mContext.startActivity(buildNetworkOverLimitIntent(template));
511 mOverLimitNotified.add(template);
512 }
513 }
514
515 private void notifyUnderLimitLocked(NetworkTemplate template) {
516 mOverLimitNotified.remove(template);
517 }
518
519 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700520 * Build unique tag that identifies an active {@link NetworkPolicy}
521 * notification of a specific type, like {@link #TYPE_LIMIT}.
522 */
523 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700524 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700525 }
526
527 /**
528 * Show notification for combined {@link NetworkPolicy} and specific type,
529 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
530 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700531 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700532 final String tag = buildNotificationTag(policy, type);
533 final Notification.Builder builder = new Notification.Builder(mContext);
534 builder.setOnlyAlertOnce(true);
535 builder.setOngoing(true);
536
537 final Resources res = mContext.getResources();
538 switch (type) {
539 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700540 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700541 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700542
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700543 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700544 builder.setTicker(title);
545 builder.setContentTitle(title);
546 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700547
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700548 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700549 builder.setContentIntent(PendingIntent.getActivity(
550 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700551 break;
552 }
553 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700554 final CharSequence body = res.getText(R.string.data_usage_limit_body);
555
556 final CharSequence title;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700557 switch (policy.template.getMatchRule()) {
558 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700559 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700560 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700561 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700562 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700563 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700564 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700565 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700566 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700567 case MATCH_WIFI:
568 title = res.getText(R.string.data_usage_wifi_limit_title);
569 break;
570 default:
571 title = null;
572 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700573 }
574
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700575 builder.setSmallIcon(R.drawable.stat_notify_disabled);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700576 builder.setTicker(title);
577 builder.setContentTitle(title);
578 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700579
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700580 final Intent intent = buildNetworkOverLimitIntent(policy.template);
581 builder.setContentIntent(PendingIntent.getActivity(
582 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
583 break;
584 }
585 case TYPE_LIMIT_SNOOZED: {
586 final long overBytes = totalBytes - policy.limitBytes;
587 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
588 Formatter.formatFileSize(mContext, overBytes));
589
590 final CharSequence title;
591 switch (policy.template.getMatchRule()) {
592 case MATCH_MOBILE_3G_LOWER:
593 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
594 break;
595 case MATCH_MOBILE_4G:
596 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
597 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700598 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700599 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
600 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700601 case MATCH_WIFI:
602 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
603 break;
604 default:
605 title = null;
606 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700607 }
608
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700609 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700610 builder.setTicker(title);
611 builder.setContentTitle(title);
612 builder.setContentText(body);
613
614 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700615 builder.setContentIntent(PendingIntent.getActivity(
616 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700617 break;
618 }
619 }
620
621 // TODO: move to NotificationManager once we can mock it
622 try {
623 final String packageName = mContext.getPackageName();
624 final int[] idReceived = new int[1];
625 mNotifManager.enqueueNotificationWithTag(
626 packageName, tag, 0x0, builder.getNotification(), idReceived);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700627 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700628 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700629 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700630 }
631 }
632
633 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700634 * Show ongoing notification to reflect that {@link #mRestrictBackground}
635 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700636 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700637 private void enqueueRestrictedNotification(String tag) {
638 final Resources res = mContext.getResources();
639 final Notification.Builder builder = new Notification.Builder(mContext);
640
641 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
642 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
643
644 builder.setOnlyAlertOnce(true);
645 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700646 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700647 builder.setTicker(title);
648 builder.setContentTitle(title);
649 builder.setContentText(body);
650
651 final Intent intent = buildAllowBackgroundDataIntent();
652 builder.setContentIntent(
653 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700654
655 // TODO: move to NotificationManager once we can mock it
656 try {
657 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700658 final int[] idReceived = new int[1];
659 mNotifManager.enqueueNotificationWithTag(packageName, tag,
660 0x0, builder.getNotification(), idReceived);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700661 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700662 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700663 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700664 }
665 }
666
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700667 private void cancelNotification(String tag) {
668 // TODO: move to NotificationManager once we can mock it
669 try {
670 final String packageName = mContext.getPackageName();
671 mNotifManager.cancelNotificationWithTag(
672 packageName, tag, 0x0);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700673 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700674 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700675 }
676 }
677
678 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700679 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700680 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700681 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700682 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700683 @Override
684 public void onReceive(Context context, Intent intent) {
685 // on background handler thread, and verified CONNECTIVITY_INTERNAL
686 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800687
688 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700689 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700690 ensureActiveMobilePolicyLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700691 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700692 updateNetworkRulesLocked();
693 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700694 }
695 }
696 };
697
698 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700699 * Proactively control network data connections when they exceed
700 * {@link NetworkPolicy#limitBytes}.
701 */
702 private void updateNetworkEnabledLocked() {
703 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
704
705 // TODO: reset any policy-disabled networks when any policy is removed
706 // completely, which is currently rare case.
707
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800708 final long currentTime = currentTimeMillis();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700709 for (NetworkPolicy policy : mNetworkPolicy.values()) {
710 // shortcut when policy has no limit
711 if (policy.limitBytes == LIMIT_DISABLED) {
712 setNetworkTemplateEnabled(policy.template, true);
713 continue;
714 }
715
716 final long start = computeLastCycleBoundary(currentTime, policy);
717 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700718 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700719
720 // disable data connection when over limit and not snoozed
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700721 final boolean overLimit = policy.isOverLimit(totalBytes) && policy.lastSnooze < start;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700722 final boolean enabled = !overLimit;
723
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700724 setNetworkTemplateEnabled(policy.template, enabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700725 }
726 }
727
728 /**
729 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}
730 * for the given {@link NetworkTemplate}.
731 */
732 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700733 switch (template.getMatchRule()) {
734 case MATCH_MOBILE_3G_LOWER:
735 case MATCH_MOBILE_4G:
736 case MATCH_MOBILE_ALL:
737 // TODO: offer more granular control over radio states once
738 // 4965893 is available.
739 if (Objects.equal(getActiveSubscriberId(), template.getSubscriberId())) {
740 setPolicyDataEnable(TYPE_MOBILE, enabled);
741 setPolicyDataEnable(TYPE_WIMAX, enabled);
742 }
743 break;
744 case MATCH_WIFI:
745 setPolicyDataEnable(TYPE_WIFI, enabled);
746 break;
747 case MATCH_ETHERNET:
748 setPolicyDataEnable(TYPE_ETHERNET, enabled);
749 break;
750 default:
751 throw new IllegalArgumentException("unexpected template");
752 }
753 }
754
755 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700756 * Examine all connected {@link NetworkState}, looking for
757 * {@link NetworkPolicy} that need to be enforced. When matches found, set
758 * remaining quota based on usage cycle and historical stats.
759 */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700760 private void updateNetworkRulesLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700761 if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700762
763 final NetworkState[] states;
764 try {
765 states = mConnManager.getAllNetworkState();
766 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700767 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700768 return;
769 }
770
771 // first, derive identity for all connected networks, which can be used
772 // to match against templates.
773 final HashMap<NetworkIdentity, String> networks = Maps.newHashMap();
774 for (NetworkState state : states) {
775 // stash identity and iface away for later use
776 if (state.networkInfo.isConnected()) {
777 final String iface = state.linkProperties.getInterfaceName();
778 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
779 networks.put(ident, iface);
780 }
781 }
782
783 // build list of rules and ifaces to enforce them against
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700784 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700785 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700786 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700787
788 // collect all active ifaces that match this template
789 ifaceList.clear();
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700790 for (Map.Entry<NetworkIdentity, String> entry : networks.entrySet()) {
791 final NetworkIdentity ident = entry.getKey();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700792 if (policy.template.matches(ident)) {
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700793 final String iface = entry.getValue();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700794 ifaceList.add(iface);
795 }
796 }
797
798 if (ifaceList.size() > 0) {
799 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700800 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700801 }
802 }
803
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700804 final HashSet<String> newMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700805
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700806 // apply each policy that we found ifaces for; compute remaining data
807 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800808 final long currentTime = currentTimeMillis();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700809 for (NetworkPolicy policy : mNetworkRules.keySet()) {
810 final String[] ifaces = mNetworkRules.get(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700811
812 final long start = computeLastCycleBoundary(currentTime, policy);
813 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700814 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700815
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700816 if (LOGD) {
817 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700818 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700819 }
820
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700821 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700822 if (hasLimit) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700823 final long quotaBytes;
824 if (policy.lastSnooze >= start) {
825 // snoozing past quota, but we still need to restrict apps,
826 // so push really high quota.
827 quotaBytes = Long.MAX_VALUE;
828 } else {
829 // remaining "quota" bytes are based on total usage in
830 // current cycle. kernel doesn't like 0-byte rules, so we
831 // set 1-byte quota and disable the radio later.
832 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
833 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700834
835 if (ifaces.length > 1) {
836 // TODO: switch to shared quota once NMS supports
837 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700838 }
839
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700840 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700841 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700842 setInterfaceQuota(iface, quotaBytes);
843 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700844 }
845 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700846 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700847
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700848 // remove quota on any trailing interfaces
849 for (String iface : mMeteredIfaces) {
850 if (!newMeteredIfaces.contains(iface)) {
851 removeInterfaceQuota(iface);
852 }
853 }
854 mMeteredIfaces = newMeteredIfaces;
855
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700856 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700857 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700858 }
859
860 /**
861 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
862 * have at least a default mobile policy defined.
863 */
864 private void ensureActiveMobilePolicyLocked() {
865 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700866 if (mSuppressDefaultPolicy) return;
867
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700868 final String subscriberId = getActiveSubscriberId();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700869 final NetworkIdentity probeIdent = new NetworkIdentity(
Jeff Sharkey5dc0c262011-06-19 22:21:05 -0700870 TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, false);
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700871
872 // examine to see if any policy is defined for active mobile
873 boolean mobileDefined = false;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700874 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700875 if (policy.template.matches(probeIdent)) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700876 mobileDefined = true;
877 }
878 }
879
880 if (!mobileDefined) {
881 Slog.i(TAG, "no policy for active mobile network; generating default policy");
882
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700883 // build default mobile policy, and assume usage cycle starts today
884 final long warningBytes = mContext.getResources().getInteger(
885 com.android.internal.R.integer.config_networkPolicyDefaultWarning)
886 * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700887
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700888 final Time time = new Time(Time.TIMEZONE_UTC);
889 time.setToNow();
890 final int cycleDay = time.monthDay;
891
Jeff Sharkey4e814c32011-07-14 20:37:37 -0700892 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700893 mNetworkPolicy.put(template, new NetworkPolicy(
894 template, cycleDay, warningBytes, LIMIT_DISABLED, SNOOZE_NEVER));
Jeff Sharkeyfcc79772011-06-13 22:28:34 -0700895 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700896 }
897 }
898
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700899 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700900 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700901
902 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700903 mNetworkPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700904 mUidPolicy.clear();
905
906 FileInputStream fis = null;
907 try {
908 fis = mPolicyFile.openRead();
909 final XmlPullParser in = Xml.newPullParser();
910 in.setInput(fis, null);
911
912 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700913 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700914 while ((type = in.next()) != END_DOCUMENT) {
915 final String tag = in.getName();
916 if (type == START_TAG) {
917 if (TAG_POLICY_LIST.equals(tag)) {
918 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -0700919 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
920 mRestrictBackground = readBooleanAttribute(
921 in, ATTR_RESTRICT_BACKGROUND);
922 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700923 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -0700924 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700925
926 } else if (TAG_NETWORK_POLICY.equals(tag)) {
927 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
928 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700929 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
930 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
931 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700932 final long lastSnooze;
933 if (version >= VERSION_ADDED_SNOOZE) {
934 lastSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
935 } else {
936 lastSnooze = SNOOZE_NEVER;
937 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700938
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700939 final NetworkTemplate template = new NetworkTemplate(
940 networkTemplate, subscriberId);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700941 mNetworkPolicy.put(template, new NetworkPolicy(
942 template, cycleDay, warningBytes, limitBytes, lastSnooze));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700943
944 } else if (TAG_UID_POLICY.equals(tag)) {
945 final int uid = readIntAttribute(in, ATTR_UID);
946 final int policy = readIntAttribute(in, ATTR_POLICY);
947
Jeff Sharkey497e4432011-06-14 17:27:29 -0700948 if (isUidValidForPolicy(mContext, uid)) {
949 setUidPolicyUnchecked(uid, policy, false);
950 } else {
951 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
952 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700953 }
954 }
955 }
956
957 } catch (FileNotFoundException e) {
958 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700959 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700960 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700961 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700962 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700963 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700964 } finally {
965 IoUtils.closeQuietly(fis);
966 }
967 }
968
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700969 /**
970 * Upgrade legacy background data flags, notifying listeners of one last
971 * change to always-true.
972 */
973 private void upgradeLegacyBackgroundData() {
974 mRestrictBackground = Settings.Secure.getInt(
975 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
976
977 // kick off one last broadcast if restricted
978 if (mRestrictBackground) {
979 final Intent broadcast = new Intent(
980 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
981 mContext.sendBroadcast(broadcast);
982 }
983 }
984
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700985 private void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700986 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700987
988 FileOutputStream fos = null;
989 try {
990 fos = mPolicyFile.startWrite();
991
992 XmlSerializer out = new FastXmlSerializer();
993 out.setOutput(fos, "utf-8");
994 out.startDocument(null, true);
995
996 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey46645002011-07-27 21:11:21 -0700997 writeIntAttribute(out, ATTR_VERSION, VERSION_ADDED_RESTRICT_BACKGROUND);
998 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700999
1000 // write all known network policies
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001001 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001002 final NetworkTemplate template = policy.template;
1003
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001004 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001005 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1006 final String subscriberId = template.getSubscriberId();
1007 if (subscriberId != null) {
1008 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001009 }
1010 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
1011 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1012 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001013 writeLongAttribute(out, ATTR_LAST_SNOOZE, policy.lastSnooze);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001014 out.endTag(null, TAG_NETWORK_POLICY);
1015 }
1016
1017 // write all known uid policies
1018 for (int i = 0; i < mUidPolicy.size(); i++) {
1019 final int uid = mUidPolicy.keyAt(i);
1020 final int policy = mUidPolicy.valueAt(i);
1021
Jeff Sharkey497e4432011-06-14 17:27:29 -07001022 // skip writing empty policies
1023 if (policy == POLICY_NONE) continue;
1024
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001025 out.startTag(null, TAG_UID_POLICY);
1026 writeIntAttribute(out, ATTR_UID, uid);
1027 writeIntAttribute(out, ATTR_POLICY, policy);
1028 out.endTag(null, TAG_UID_POLICY);
1029 }
1030
1031 out.endTag(null, TAG_POLICY_LIST);
1032 out.endDocument();
1033
1034 mPolicyFile.finishWrite(fos);
1035 } catch (IOException e) {
1036 if (fos != null) {
1037 mPolicyFile.failWrite(fos);
1038 }
1039 }
1040 }
1041
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001042 @Override
1043 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001044 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001045
Jeff Sharkey497e4432011-06-14 17:27:29 -07001046 if (!isUidValidForPolicy(mContext, uid)) {
1047 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1048 }
1049
1050 setUidPolicyUnchecked(uid, policy, true);
1051 }
1052
1053 private void setUidPolicyUnchecked(int uid, int policy, boolean persist) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001054 final int oldPolicy;
Jeff Sharkeya4620792011-05-20 15:29:23 -07001055 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001056 oldPolicy = getUidPolicy(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001057 mUidPolicy.put(uid, policy);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001058
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001059 // uid policy changed, recompute rules and persist policy.
1060 updateRulesForUidLocked(uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001061 if (persist) {
1062 writePolicyLocked();
1063 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001064 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001065 }
1066
1067 @Override
1068 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001069 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1070
Jeff Sharkeya4620792011-05-20 15:29:23 -07001071 synchronized (mRulesLock) {
1072 return mUidPolicy.get(uid, POLICY_NONE);
1073 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001074 }
1075
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001076 @Override
1077 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001078 // TODO: create permission for observing network policy
1079 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1080
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001081 mListeners.register(listener);
1082
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001083 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001084 }
1085
1086 @Override
1087 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001088 // TODO: create permission for observing network policy
1089 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1090
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001091 mListeners.unregister(listener);
1092 }
1093
Jeff Sharkey1b861272011-05-22 00:34:52 -07001094 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001095 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001096 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1097
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001098 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001099 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001100 mNetworkPolicy.clear();
1101 for (NetworkPolicy policy : policies) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001102 mNetworkPolicy.put(policy.template, policy);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001103 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001104
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001105 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001106 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001107 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001108 writePolicyLocked();
1109 }
1110 }
1111
1112 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001113 public NetworkPolicy[] getNetworkPolicies() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001114 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001115 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001116
1117 synchronized (mRulesLock) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001118 return mNetworkPolicy.values().toArray(new NetworkPolicy[mNetworkPolicy.size()]);
1119 }
1120 }
1121
1122 @Override
1123 public void snoozePolicy(NetworkTemplate template) {
1124 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1125
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001126 maybeRefreshTrustedTime();
1127 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001128 synchronized (mRulesLock) {
1129 // find and snooze local policy that matches
1130 final NetworkPolicy policy = mNetworkPolicy.get(template);
1131 if (policy == null) {
1132 throw new IllegalArgumentException("unable to find policy for " + template);
1133 }
1134
1135 policy.lastSnooze = currentTime;
1136
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001137 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001138 updateNetworkRulesLocked();
1139 updateNotificationsLocked();
1140 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001141 }
1142 }
1143
1144 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001145 public void setRestrictBackground(boolean restrictBackground) {
1146 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1147
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001148 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001149 synchronized (mRulesLock) {
1150 mRestrictBackground = restrictBackground;
1151 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001152 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001153 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001154 }
1155 }
1156
1157 @Override
1158 public boolean getRestrictBackground() {
1159 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1160
1161 synchronized (mRulesLock) {
1162 return mRestrictBackground;
1163 }
1164 }
1165
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001166 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
1167 for (NetworkPolicy policy : mNetworkPolicy.values()) {
1168 if (policy.template.matches(ident)) {
1169 return policy;
1170 }
1171 }
1172 return null;
1173 }
1174
1175 @Override
1176 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1177 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1178
1179 // only returns usage summary, so we don't require caller to have
1180 // READ_NETWORK_USAGE_HISTORY.
1181 final long token = Binder.clearCallingIdentity();
1182 try {
1183 return getNetworkQuotaInfoUnchecked(state);
1184 } finally {
1185 Binder.restoreCallingIdentity(token);
1186 }
1187 }
1188
1189 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1190 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1191
1192 final NetworkPolicy policy;
1193 synchronized (mRulesLock) {
1194 policy = findPolicyForNetworkLocked(ident);
1195 }
1196
1197 if (policy == null) {
1198 // missing policy means we can't derive useful quota info
1199 return null;
1200 }
1201
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001202 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001203
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001204 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001205 final long start = computeLastCycleBoundary(currentTime, policy);
1206 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001207 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001208
1209 // report soft and hard limits under policy
1210 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1211 : NetworkQuotaInfo.NO_LIMIT;
1212 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1213 : NetworkQuotaInfo.NO_LIMIT;
1214
1215 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1216 }
1217
Jeff Sharkey46645002011-07-27 21:11:21 -07001218 @Override
Jeff Sharkey1b861272011-05-22 00:34:52 -07001219 protected void dump(FileDescriptor fd, PrintWriter fout, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001220 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001221
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001222 final HashSet<String> argSet = new HashSet<String>();
1223 for (String arg : args) {
1224 argSet.add(arg);
1225 }
1226
Jeff Sharkey1b861272011-05-22 00:34:52 -07001227 synchronized (mRulesLock) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001228 if (argSet.contains("unsnooze")) {
1229 for (NetworkPolicy policy : mNetworkPolicy.values()) {
1230 policy.lastSnooze = SNOOZE_NEVER;
1231 }
1232 writePolicyLocked();
1233 fout.println("Wiped snooze timestamps");
1234 return;
1235 }
1236
Jeff Sharkey46645002011-07-27 21:11:21 -07001237 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001238 fout.println("Network policies:");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001239 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001240 fout.print(" "); fout.println(policy.toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001241 }
1242
Jeff Sharkey1b861272011-05-22 00:34:52 -07001243 fout.println("Policy status for known UIDs:");
1244
1245 final SparseBooleanArray knownUids = new SparseBooleanArray();
1246 collectKeys(mUidPolicy, knownUids);
1247 collectKeys(mUidForeground, knownUids);
1248 collectKeys(mUidRules, knownUids);
1249
1250 final int size = knownUids.size();
1251 for (int i = 0; i < size; i++) {
1252 final int uid = knownUids.keyAt(i);
1253 fout.print(" UID=");
1254 fout.print(uid);
1255
1256 fout.print(" policy=");
1257 final int policyIndex = mUidPolicy.indexOfKey(uid);
1258 if (policyIndex < 0) {
1259 fout.print("UNKNOWN");
1260 } else {
1261 dumpPolicy(fout, mUidPolicy.valueAt(policyIndex));
1262 }
1263
1264 fout.print(" foreground=");
1265 final int foregroundIndex = mUidPidForeground.indexOfKey(uid);
1266 if (foregroundIndex < 0) {
1267 fout.print("UNKNOWN");
1268 } else {
1269 dumpSparseBooleanArray(fout, mUidPidForeground.valueAt(foregroundIndex));
1270 }
1271
1272 fout.print(" rules=");
1273 final int rulesIndex = mUidRules.indexOfKey(uid);
1274 if (rulesIndex < 0) {
1275 fout.print("UNKNOWN");
1276 } else {
1277 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1278 }
1279
1280 fout.println();
1281 }
1282 }
1283 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001284
1285 @Override
1286 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001287 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1288
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001289 synchronized (mRulesLock) {
1290 // only really in foreground when screen is also on
1291 return mUidForeground.get(uid, false) && mScreenOn;
1292 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001293 }
1294
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001295 /**
1296 * Foreground for PID changed; recompute foreground at UID level. If
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001297 * changed, will trigger {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001298 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001299 private void computeUidForegroundLocked(int uid) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001300 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1301
1302 // current pid is dropping foreground; examine other pids
1303 boolean uidForeground = false;
1304 final int size = pidForeground.size();
1305 for (int i = 0; i < size; i++) {
1306 if (pidForeground.valueAt(i)) {
1307 uidForeground = true;
1308 break;
1309 }
1310 }
1311
1312 final boolean oldUidForeground = mUidForeground.get(uid, false);
1313 if (oldUidForeground != uidForeground) {
1314 // foreground changed, push updated rules
1315 mUidForeground.put(uid, uidForeground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001316 updateRulesForUidLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001317 }
1318 }
1319
Jeff Sharkeya4620792011-05-20 15:29:23 -07001320 private void updateScreenOn() {
1321 synchronized (mRulesLock) {
1322 try {
1323 mScreenOn = mPowerManager.isScreenOn();
1324 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001325 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07001326 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001327 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001328 }
1329 }
1330
1331 /**
1332 * Update rules that might be changed by {@link #mScreenOn} value.
1333 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001334 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07001335 // only update rules for anyone with foreground activities
1336 final int size = mUidForeground.size();
1337 for (int i = 0; i < size; i++) {
1338 if (mUidForeground.valueAt(i)) {
1339 final int uid = mUidForeground.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001340 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001341 }
1342 }
1343 }
1344
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001345 /**
Jeff Sharkey46645002011-07-27 21:11:21 -07001346 * Update rules that might be changed by {@link #mRestrictBackground} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001347 */
Jeff Sharkey46645002011-07-27 21:11:21 -07001348 private void updateRulesForRestrictBackgroundLocked() {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001349 // update rules for all installed applications
1350 final PackageManager pm = mContext.getPackageManager();
1351 final List<ApplicationInfo> apps = pm.getInstalledApplications(0);
1352 for (ApplicationInfo app : apps) {
1353 updateRulesForUidLocked(app.uid);
1354 }
1355
1356 // and catch system UIDs
1357 // TODO: keep in sync with android_filesystem_config.h
1358 for (int uid = 1000; uid <= 1025; uid++) {
1359 updateRulesForUidLocked(uid);
1360 }
1361 for (int uid = 2000; uid <= 2002; uid++) {
1362 updateRulesForUidLocked(uid);
1363 }
1364 for (int uid = 3000; uid <= 3007; uid++) {
1365 updateRulesForUidLocked(uid);
1366 }
1367 for (int uid = 9998; uid <= 9999; uid++) {
1368 updateRulesForUidLocked(uid);
1369 }
1370 }
1371
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001372 private void updateRulesForUidLocked(int uid) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001373 final int uidPolicy = getUidPolicy(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001374 final boolean uidForeground = isUidForeground(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001375
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001376 // derive active rules based on policy and active state
1377 int uidRules = RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001378 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1379 // uid in background, and policy says to block metered data
1380 uidRules = RULE_REJECT_METERED;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001381 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001382 if (!uidForeground && mRestrictBackground) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001383 // uid in background, and global background disabled
1384 uidRules = RULE_REJECT_METERED;
1385 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001386
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001387 // TODO: only dispatch when rules actually change
1388
Jeff Sharkey350083e2011-06-29 10:45:16 -07001389 if (uidRules == RULE_ALLOW_ALL) {
1390 mUidRules.delete(uid);
1391 } else {
1392 mUidRules.put(uid, uidRules);
1393 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001394
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001395 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001396 setUidNetworkRules(uid, rejectMetered);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001397
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001398 // dispatch changed rule to existing listeners
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001399 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001400
1401 try {
1402 // adjust stats accounting based on foreground status
1403 mNetworkStats.setUidForeground(uid, uidForeground);
1404 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001405 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001406 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001407 }
1408
1409 private Handler.Callback mHandlerCallback = new Handler.Callback() {
1410 /** {@inheritDoc} */
1411 public boolean handleMessage(Message msg) {
1412 switch (msg.what) {
1413 case MSG_RULES_CHANGED: {
1414 final int uid = msg.arg1;
1415 final int uidRules = msg.arg2;
1416 final int length = mListeners.beginBroadcast();
1417 for (int i = 0; i < length; i++) {
1418 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1419 if (listener != null) {
1420 try {
1421 listener.onUidRulesChanged(uid, uidRules);
1422 } catch (RemoteException e) {
1423 }
1424 }
1425 }
1426 mListeners.finishBroadcast();
1427 return true;
1428 }
1429 case MSG_METERED_IFACES_CHANGED: {
1430 final String[] meteredIfaces = (String[]) msg.obj;
1431 final int length = mListeners.beginBroadcast();
1432 for (int i = 0; i < length; i++) {
1433 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1434 if (listener != null) {
1435 try {
1436 listener.onMeteredIfacesChanged(meteredIfaces);
1437 } catch (RemoteException e) {
1438 }
1439 }
1440 }
1441 mListeners.finishBroadcast();
1442 return true;
1443 }
Jeff Sharkey6f7af032011-11-01 18:25:15 -07001444 case MSG_FOREGROUND_ACTIVITIES_CHANGED: {
1445 final int pid = msg.arg1;
1446 final int uid = msg.arg2;
1447 final boolean foregroundActivities = (Boolean) msg.obj;
1448
1449 synchronized (mRulesLock) {
1450 // because a uid can have multiple pids running inside, we need to
1451 // remember all pid states and summarize foreground at uid level.
1452
1453 // record foreground for this specific pid
1454 SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1455 if (pidForeground == null) {
1456 pidForeground = new SparseBooleanArray(2);
1457 mUidPidForeground.put(uid, pidForeground);
1458 }
1459 pidForeground.put(pid, foregroundActivities);
1460 computeUidForegroundLocked(uid);
1461 }
1462 return true;
1463 }
1464 case MSG_PROCESS_DIED: {
1465 final int pid = msg.arg1;
1466 final int uid = msg.arg2;
1467
1468 synchronized (mRulesLock) {
1469 // clear records and recompute, when they exist
1470 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1471 if (pidForeground != null) {
1472 pidForeground.delete(pid);
1473 computeUidForegroundLocked(uid);
1474 }
1475 }
1476 return true;
1477 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001478 case MSG_LIMIT_REACHED: {
1479 final String iface = (String) msg.obj;
1480
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001481 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001482 synchronized (mRulesLock) {
1483 if (mMeteredIfaces.contains(iface)) {
1484 try {
1485 // force stats update to make sure we have
1486 // numbers that caused alert to trigger.
1487 mNetworkStats.forceUpdate();
1488 } catch (RemoteException e) {
1489 // ignored; service lives in system_server
1490 }
1491
1492 updateNetworkEnabledLocked();
1493 updateNotificationsLocked();
1494 }
1495 }
1496 return true;
1497 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001498 default: {
1499 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07001500 }
1501 }
1502 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001503 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001504
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001505 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001506 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001507 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001508 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001509 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001510 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001511 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001512 }
1513 }
1514
1515 private void removeInterfaceQuota(String iface) {
1516 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001517 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001518 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001519 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001520 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001521 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001522 }
1523 }
1524
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001525 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1526 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001527 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001528 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001529 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001530 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001531 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001532 }
1533 }
1534
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001535 /**
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001536 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001537 */
1538 private void setPolicyDataEnable(int networkType, boolean enabled) {
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001539 try {
1540 mConnManager.setPolicyDataEnable(networkType, enabled);
1541 } catch (RemoteException e) {
1542 // ignored; service lives in system_server
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001543 }
1544 }
1545
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001546 private String getActiveSubscriberId() {
1547 final TelephonyManager telephony = (TelephonyManager) mContext.getSystemService(
1548 Context.TELEPHONY_SERVICE);
1549 return telephony.getSubscriberId();
1550 }
1551
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001552 private long getTotalBytes(NetworkTemplate template, long start, long end) {
1553 try {
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001554 return mNetworkStats.getSummaryForNetwork(template, start, end).getTotalBytes();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001555 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001556 // ignored; service lives in system_server
1557 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001558 }
1559 }
1560
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001561 /**
1562 * Try refreshing {@link #mTime} when stale.
1563 */
1564 private void maybeRefreshTrustedTime() {
1565 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001566 mTime.forceRefresh();
1567 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001568 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001569
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001570 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001571 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
1572 }
1573
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001574 private static Intent buildAllowBackgroundDataIntent() {
1575 return new Intent(ACTION_ALLOW_BACKGROUND);
1576 }
1577
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001578 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
1579 final Intent intent = new Intent();
1580 intent.setComponent(new ComponentName(
1581 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
1582 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1583 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
1584 return intent;
1585 }
1586
1587 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
1588 final Intent intent = new Intent();
1589 intent.setComponent(new ComponentName(
1590 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
1591 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1592 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
1593 return intent;
1594 }
1595
Jeff Sharkey163e6442011-10-31 16:37:52 -07001596 // @VisibleForTesting
1597 public void addIdleHandler(IdleHandler handler) {
1598 mHandler.getLooper().getQueue().addIdleHandler(handler);
1599 }
1600
Jeff Sharkey1b861272011-05-22 00:34:52 -07001601 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
1602 final int size = source.size();
1603 for (int i = 0; i < size; i++) {
1604 target.put(source.keyAt(i), true);
1605 }
1606 }
1607
1608 private static void collectKeys(SparseBooleanArray source, SparseBooleanArray target) {
1609 final int size = source.size();
1610 for (int i = 0; i < size; i++) {
1611 target.put(source.keyAt(i), true);
1612 }
1613 }
1614
1615 private static void dumpSparseBooleanArray(PrintWriter fout, SparseBooleanArray value) {
1616 fout.print("[");
1617 final int size = value.size();
1618 for (int i = 0; i < size; i++) {
1619 fout.print(value.keyAt(i) + "=" + value.valueAt(i));
1620 if (i < size - 1) fout.print(",");
1621 }
1622 fout.print("]");
1623 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001624
Jeff Sharkey46645002011-07-27 21:11:21 -07001625 public static class XmlUtils {
1626 public static int readIntAttribute(XmlPullParser in, String name) throws IOException {
1627 final String value = in.getAttributeValue(null, name);
1628 try {
1629 return Integer.parseInt(value);
1630 } catch (NumberFormatException e) {
1631 throw new ProtocolException("problem parsing " + name + "=" + value + " as int");
1632 }
1633 }
1634
1635 public static void writeIntAttribute(XmlSerializer out, String name, int value)
1636 throws IOException {
1637 out.attribute(null, name, Integer.toString(value));
1638 }
1639
1640 public static long readLongAttribute(XmlPullParser in, String name) throws IOException {
1641 final String value = in.getAttributeValue(null, name);
1642 try {
1643 return Long.parseLong(value);
1644 } catch (NumberFormatException e) {
1645 throw new ProtocolException("problem parsing " + name + "=" + value + " as long");
1646 }
1647 }
1648
1649 public static void writeLongAttribute(XmlSerializer out, String name, long value)
1650 throws IOException {
1651 out.attribute(null, name, Long.toString(value));
1652 }
1653
1654 public static boolean readBooleanAttribute(XmlPullParser in, String name) {
1655 final String value = in.getAttributeValue(null, name);
1656 return Boolean.parseBoolean(value);
1657 }
1658
1659 public static void writeBooleanAttribute(XmlSerializer out, String name, boolean value)
1660 throws IOException {
1661 out.attribute(null, name, Boolean.toString(value));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001662 }
1663 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001664}