blob: 1b8c9cb24fd3973d8bca74fc65d205677b737def [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 Sharkey9f6e4ba2012-04-19 23:01:08 -070033import static android.net.ConnectivityManager.isNetworkTypeMobile;
34import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070035import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070036import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070037import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070038import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070039import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070040import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070041import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070042import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070043import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Jeff Sharkey1b861272011-05-22 00:34:52 -070044import static android.net.NetworkPolicyManager.dumpPolicy;
45import static android.net.NetworkPolicyManager.dumpRules;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070046import static android.net.NetworkTemplate.MATCH_ETHERNET;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070047import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
48import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070049import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
50import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070051import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080052import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070053import static android.net.wifi.WifiInfo.removeDoubleQuotes;
54import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
55import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
56import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
57import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
58import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
59import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
60import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070061import static android.telephony.TelephonyManager.SIM_STATE_READY;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070062import static android.text.format.DateUtils.DAY_IN_MILLIS;
Jeff Sharkey854b2b12012-04-13 16:03:40 -070063import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070064import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey961e3042011-08-29 16:02:57 -070065import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey46645002011-07-27 21:11:21 -070066import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.readBooleanAttribute;
67import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.readIntAttribute;
68import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.readLongAttribute;
69import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.writeBooleanAttribute;
70import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.writeIntAttribute;
71import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.writeLongAttribute;
Jeff Sharkey497e4432011-06-14 17:27:29 -070072import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070073import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
74import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070075
Jeff Sharkeya4620792011-05-20 15:29:23 -070076import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070077import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070078import android.app.IProcessObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070079import android.app.Notification;
80import android.app.PendingIntent;
Jeff Sharkeya4620792011-05-20 15:29:23 -070081import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070082import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070083import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070084import android.content.Intent;
85import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070086import android.content.pm.ApplicationInfo;
87import android.content.pm.PackageManager;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -070088import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -070089import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070090import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070091import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070092import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070093import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070094import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -070095import android.net.INetworkStatsService;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070096import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070097import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070098import android.net.NetworkPolicy;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070099import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700100import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700101import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700102import android.net.wifi.WifiConfiguration;
103import android.net.wifi.WifiInfo;
104import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700105import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700106import android.os.Environment;
107import android.os.Handler;
108import android.os.HandlerThread;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700109import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700110import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700111import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700112import android.os.MessageQueue.IdleHandler;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700113import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700114import android.os.RemoteException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700115import android.os.UserId;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700116import android.provider.Settings;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700117import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700118import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700119import android.text.format.Time;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700120import android.util.Log;
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700121import android.util.MathUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700122import android.util.NtpTrustedTime;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700123import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700124import android.util.SparseArray;
125import android.util.SparseBooleanArray;
126import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700127import android.util.TrustedTime;
128import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700129
Jeff Sharkey497e4432011-06-14 17:27:29 -0700130import com.android.internal.R;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700131import com.android.internal.os.AtomicFile;
132import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700133import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700134import com.android.internal.util.Objects;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700135import com.google.android.collect.Lists;
136import com.google.android.collect.Maps;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700137import com.google.android.collect.Sets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700138
139import org.xmlpull.v1.XmlPullParser;
140import org.xmlpull.v1.XmlPullParserException;
141import org.xmlpull.v1.XmlSerializer;
142
143import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700144import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700145import java.io.FileInputStream;
146import java.io.FileNotFoundException;
147import java.io.FileOutputStream;
148import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700149import java.io.PrintWriter;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700150import java.net.ProtocolException;
151import java.util.ArrayList;
152import java.util.Arrays;
153import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700154import java.util.HashSet;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700155import java.util.List;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700156import java.util.Map;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700157
158import libcore.io.IoUtils;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700159
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700160/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700161 * Service that maintains low-level network policy rules, using
162 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700163 * <p>
164 * Derives active rules by combining a given policy with other system status,
165 * and delivers to listeners, such as {@link ConnectivityManager}, for
166 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700167 */
168public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
169 private static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700170 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700171 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700172
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700173 private static final int VERSION_INIT = 1;
174 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700175 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800176 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800177 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800178 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700179 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700180 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700181 private static final int VERSION_ADDED_NETWORK_ID = 9;
182 private static final int VERSION_LATEST = VERSION_ADDED_NETWORK_ID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700183
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700184 // @VisibleForTesting
185 public static final int TYPE_WARNING = 0x1;
186 public static final int TYPE_LIMIT = 0x2;
187 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700188
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700189 private static final String TAG_POLICY_LIST = "policy-list";
190 private static final String TAG_NETWORK_POLICY = "network-policy";
191 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700192 private static final String TAG_APP_POLICY = "app-policy";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700193
194 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700195 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700196 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
197 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700198 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700199 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800200 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700201 private static final String ATTR_WARNING_BYTES = "warningBytes";
202 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700203 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800204 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
205 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800206 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700207 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700208 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700209 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700210 private static final String ATTR_POLICY = "policy";
211
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700212 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
213
214 // @VisibleForTesting
215 public static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800216 "com.android.server.net.action.ALLOW_BACKGROUND";
217 public static final String ACTION_SNOOZE_WARNING =
218 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700219
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700220 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
221
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700222 private static final int MSG_RULES_CHANGED = 1;
223 private static final int MSG_METERED_IFACES_CHANGED = 2;
224 private static final int MSG_FOREGROUND_ACTIVITIES_CHANGED = 3;
225 private static final int MSG_PROCESS_DIED = 4;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800226 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800227 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700228
Jeff Sharkey75279902011-05-24 18:39:45 -0700229 private final Context mContext;
230 private final IActivityManager mActivityManager;
231 private final IPowerManager mPowerManager;
232 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700233 private final INetworkManagementService mNetworkManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700234 private final TrustedTime mTime;
235
236 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700237 private INotificationManager mNotifManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700238
Jeff Sharkey75279902011-05-24 18:39:45 -0700239 private final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700240
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700241 private volatile boolean mScreenOn;
242 private volatile boolean mRestrictBackground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700243
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700244 private final boolean mSuppressDefaultPolicy;
245
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700246 /** Defined network policies. */
247 private HashMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = Maps.newHashMap();
248 /** Currently active network rules for ifaces. */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700249 private HashMap<NetworkPolicy, String[]> mNetworkRules = Maps.newHashMap();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700250
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700251 /** Defined app policies. */
252 private SparseIntArray mAppPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700253 /** Currently derived rules for each UID. */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700254 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700255
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700256 /** Set of ifaces that are metered. */
257 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700258 /** Set of over-limit templates that have been notified. */
259 private HashSet<NetworkTemplate> mOverLimitNotified = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700260
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700261 /** Set of currently active {@link Notification} tags. */
262 private HashSet<String> mActiveNotifs = Sets.newHashSet();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700263
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700264 /** Foreground at both UID and PID granularity. */
Jeff Sharkeya4620792011-05-20 15:29:23 -0700265 private SparseBooleanArray mUidForeground = new SparseBooleanArray();
266 private SparseArray<SparseBooleanArray> mUidPidForeground = new SparseArray<
267 SparseBooleanArray>();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700268
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700269 private final RemoteCallbackList<INetworkPolicyListener> mListeners = new RemoteCallbackList<
270 INetworkPolicyListener>();
271
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700272 private final HandlerThread mHandlerThread;
273 private final Handler mHandler;
274
275 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700276
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700277 // TODO: keep whitelist of system-critical services that should never have
278 // rules enforced, such as system, phone, and radio UIDs.
279
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700280 // TODO: migrate notifications to SystemUI
281
Jeff Sharkey75279902011-05-24 18:39:45 -0700282 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700283 IPowerManager powerManager, INetworkStatsService networkStats,
284 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700285 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700286 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700287 }
288
289 private static File getSystemDir() {
290 return new File(Environment.getDataDirectory(), "system");
291 }
292
293 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700294 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700295 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
296 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700297 mContext = checkNotNull(context, "missing context");
298 mActivityManager = checkNotNull(activityManager, "missing activityManager");
299 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700300 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700301 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700302 mTime = checkNotNull(time, "missing TrustedTime");
303
304 mHandlerThread = new HandlerThread(TAG);
305 mHandlerThread.start();
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700306 mHandler = new Handler(mHandlerThread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700307
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700308 mSuppressDefaultPolicy = suppressDefaultPolicy;
309
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700310 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
311 }
312
313 public void bindConnectivityManager(IConnectivityManager connManager) {
314 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700315 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700316
Jeff Sharkey497e4432011-06-14 17:27:29 -0700317 public void bindNotificationManager(INotificationManager notifManager) {
318 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
319 }
320
Jeff Sharkeya4620792011-05-20 15:29:23 -0700321 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700322 if (!isBandwidthControlEnabled()) {
323 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
324 return;
325 }
326
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700327 synchronized (mRulesLock) {
328 // read policy from disk
329 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700330
331 if (mRestrictBackground) {
332 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700333 updateNotificationsLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700334 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700335 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700336
Jeff Sharkeya4620792011-05-20 15:29:23 -0700337 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700338
Jeff Sharkeya4620792011-05-20 15:29:23 -0700339 try {
340 mActivityManager.registerProcessObserver(mProcessObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700341 mNetworkManager.registerObserver(mAlertObserver);
342 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700343 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700344 }
345
Jeff Sharkeya4620792011-05-20 15:29:23 -0700346 // TODO: traverse existing processes to know foreground state, or have
347 // activitymanager dispatch current state when new observer attached.
348
349 final IntentFilter screenFilter = new IntentFilter();
350 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
351 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700352 mContext.registerReceiver(mScreenReceiver, screenFilter, null, mHandler);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700353
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700354 // watch for network interfaces to be claimed
Jeff Sharkey961e3042011-08-29 16:02:57 -0700355 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION_IMMEDIATE);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700356 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
357
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700358 // listen for package/uid changes to update policy
359 final IntentFilter packageFilter = new IntentFilter();
360 packageFilter.addAction(ACTION_PACKAGE_ADDED);
361 packageFilter.addAction(ACTION_UID_REMOVED);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700362 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700363
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700364 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700365 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
366 mContext.registerReceiver(
367 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
368
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700369 // listen for restrict background changes from notifications
370 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
371 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
372
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800373 // listen for snooze warning from notifications
374 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
375 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
376 MANAGE_NETWORK_POLICY, mHandler);
377
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700378 // listen for configured wifi networks to be removed
379 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
380 mContext.registerReceiver(
381 mWifiConfigReceiver, wifiConfigFilter, CONNECTIVITY_INTERNAL, mHandler);
382
383 // listen for wifi state changes to catch metered hint
384 final IntentFilter wifiStateFilter = new IntentFilter(
385 WifiManager.NETWORK_STATE_CHANGED_ACTION);
386 mContext.registerReceiver(
387 mWifiStateReceiver, wifiStateFilter, CONNECTIVITY_INTERNAL, mHandler);
388
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700389 }
390
Jeff Sharkeya4620792011-05-20 15:29:23 -0700391 private IProcessObserver mProcessObserver = new IProcessObserver.Stub() {
392 @Override
393 public void onForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700394 mHandler.obtainMessage(MSG_FOREGROUND_ACTIVITIES_CHANGED,
395 pid, uid, foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700396 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700397
398 @Override
399 public void onProcessDied(int pid, int uid) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700400 mHandler.obtainMessage(MSG_PROCESS_DIED, pid, uid).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700401 }
402 };
403
404 private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
405 @Override
406 public void onReceive(Context context, Intent intent) {
407 synchronized (mRulesLock) {
408 // screen-related broadcasts are protected by system, no need
409 // for permissions check.
410 updateScreenOn();
411 }
412 }
413 };
414
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700415 private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700416 @Override
417 public void onReceive(Context context, Intent intent) {
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700418 // on background handler thread, and PACKAGE_ADDED and UID_REMOVED
419 // are protected broadcasts.
420
421 final String action = intent.getAction();
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700422 final int uid = intent.getIntExtra(EXTRA_UID, 0);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700423 final int appId = UserId.getAppId(uid);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700424 synchronized (mRulesLock) {
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700425 if (ACTION_PACKAGE_ADDED.equals(action)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700426 // NOTE: PACKAGE_ADDED is currently only sent once, and is
427 // not broadcast when users are added.
428
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700429 // update rules for UID, since it might be subject to
430 // global background data policy.
431 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700432 updateRulesForAppLocked(appId);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700433
434 } else if (ACTION_UID_REMOVED.equals(action)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700435 // NOTE: UID_REMOVED is currently only sent once, and is not
436 // broadcast when users are removed.
437
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700438 // remove any policy and update rules to clean up.
439 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700440
441 mAppPolicy.delete(appId);
442 updateRulesForAppLocked(appId);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700443 writePolicyLocked();
444 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700445 }
446 }
447 };
448
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700449 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700450 * Receiver that watches for {@link INetworkStatsService} updates, which we
451 * use to check against {@link NetworkPolicy#warningBytes}.
452 */
453 private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
454 @Override
455 public void onReceive(Context context, Intent intent) {
456 // on background handler thread, and verified
457 // READ_NETWORK_USAGE_HISTORY permission above.
458
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800459 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700460 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700461 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700462 updateNotificationsLocked();
463 }
464 }
465 };
466
467 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700468 * Receiver that watches for {@link Notification} control of
469 * {@link #mRestrictBackground}.
470 */
471 private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
472 @Override
473 public void onReceive(Context context, Intent intent) {
474 // on background handler thread, and verified MANAGE_NETWORK_POLICY
475 // permission above.
476
477 setRestrictBackground(false);
478 }
479 };
480
481 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800482 * Receiver that watches for {@link Notification} control of
483 * {@link NetworkPolicy#lastWarningSnooze}.
484 */
485 private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
486 @Override
487 public void onReceive(Context context, Intent intent) {
488 // on background handler thread, and verified MANAGE_NETWORK_POLICY
489 // permission above.
490
491 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
492 performSnooze(template, TYPE_WARNING);
493 }
494 };
495
496 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700497 * Receiver that watches for {@link WifiConfiguration} to be changed.
498 */
499 private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
500 @Override
501 public void onReceive(Context context, Intent intent) {
502 // on background handler thread, and verified CONNECTIVITY_INTERNAL
503 // permission above.
504
505 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
506 if (reason == CHANGE_REASON_REMOVED) {
507 final WifiConfiguration config = intent.getParcelableExtra(
508 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700509 if (config.SSID != null) {
510 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(
511 removeDoubleQuotes(config.SSID));
512 synchronized (mRulesLock) {
513 if (mNetworkPolicy.containsKey(template)) {
514 mNetworkPolicy.remove(template);
515 writePolicyLocked();
516 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700517 }
518 }
519 }
520 }
521 };
522
523 /**
524 * Receiver that watches {@link WifiInfo} state changes to infer metered
525 * state. Ignores hints when policy is user-defined.
526 */
527 private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
528 @Override
529 public void onReceive(Context context, Intent intent) {
530 // on background handler thread, and verified CONNECTIVITY_INTERNAL
531 // permission above.
532
533 // ignore when not connected
534 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
535 if (!netInfo.isConnected()) return;
536
537 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
538 final boolean meteredHint = info.getMeteredHint();
539
540 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(
541 removeDoubleQuotes(info.getSSID()));
542 synchronized (mRulesLock) {
543 NetworkPolicy policy = mNetworkPolicy.get(template);
544 if (policy == null && meteredHint) {
545 // policy doesn't exist, and AP is hinting that it's
546 // metered: create an inferred policy.
547 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
548 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
549 meteredHint, true);
550 addNetworkPolicyLocked(policy);
551
552 } else if (policy != null && policy.inferred) {
553 // policy exists, and was inferred: update its current
554 // metered state.
555 policy.metered = meteredHint;
556
557 // since this is inferred for each wifi session, just update
558 // rules without persisting.
559 updateNetworkRulesLocked();
560 }
561 }
562 }
563 };
564
565 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700566 * Observer that watches for {@link INetworkManagementService} alerts.
567 */
568 private INetworkManagementEventObserver mAlertObserver = new NetworkAlertObserver() {
569 @Override
570 public void limitReached(String limitName, String iface) {
571 // only someone like NMS should be calling us
572 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
573
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800574 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
575 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700576 }
577 }
578 };
579
580 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700581 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
582 * to show visible notifications as needed.
583 */
584 private void updateNotificationsLocked() {
585 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
586
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700587 // keep track of previously active notifications
588 final HashSet<String> beforeNotifs = Sets.newHashSet();
589 beforeNotifs.addAll(mActiveNotifs);
590 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700591
592 // TODO: when switching to kernel notifications, compute next future
593 // cycle boundary to recompute notifications.
594
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700595 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800596 final long currentTime = currentTimeMillis();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700597 for (NetworkPolicy policy : mNetworkPolicy.values()) {
598 // ignore policies that aren't relevant to user
599 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700600 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700601
Jeff Sharkey497e4432011-06-14 17:27:29 -0700602 final long start = computeLastCycleBoundary(currentTime, policy);
603 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700604 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700605
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700606 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800607 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700608 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
609 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700610 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
611 notifyOverLimitLocked(policy.template);
612 }
613
Jeff Sharkey497e4432011-06-14 17:27:29 -0700614 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700615 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700616
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800617 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700618 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700619 }
620 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700621 }
622
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700623 // ongoing notification when restricting background data
624 if (mRestrictBackground) {
625 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700626 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700627
628 // cancel stale notifications that we didn't renew above
629 for (String tag : beforeNotifs) {
630 if (!mActiveNotifs.contains(tag)) {
631 cancelNotification(tag);
632 }
633 }
634 }
635
636 /**
637 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700638 * current device state, such as when
639 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
640 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700641 */
642 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700643 final TelephonyManager tele = TelephonyManager.from(mContext);
644
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700645 switch (template.getMatchRule()) {
646 case MATCH_MOBILE_3G_LOWER:
647 case MATCH_MOBILE_4G:
648 case MATCH_MOBILE_ALL:
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700649 // mobile templates are relevant when SIM is ready and
650 // subscriberId matches.
651 if (tele.getSimState() == SIM_STATE_READY) {
652 return Objects.equal(tele.getSubscriberId(), template.getSubscriberId());
653 } else {
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700654 return false;
655 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700656 }
657 return true;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700658 }
659
660 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700661 * Notify that given {@link NetworkTemplate} is over
662 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
663 */
664 private void notifyOverLimitLocked(NetworkTemplate template) {
665 if (!mOverLimitNotified.contains(template)) {
666 mContext.startActivity(buildNetworkOverLimitIntent(template));
667 mOverLimitNotified.add(template);
668 }
669 }
670
671 private void notifyUnderLimitLocked(NetworkTemplate template) {
672 mOverLimitNotified.remove(template);
673 }
674
675 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700676 * Build unique tag that identifies an active {@link NetworkPolicy}
677 * notification of a specific type, like {@link #TYPE_LIMIT}.
678 */
679 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700680 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700681 }
682
683 /**
684 * Show notification for combined {@link NetworkPolicy} and specific type,
685 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
686 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700687 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700688 final String tag = buildNotificationTag(policy, type);
689 final Notification.Builder builder = new Notification.Builder(mContext);
690 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800691 builder.setWhen(0L);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700692
693 final Resources res = mContext.getResources();
694 switch (type) {
695 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700696 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700697 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700698
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700699 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700700 builder.setTicker(title);
701 builder.setContentTitle(title);
702 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700703
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800704 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
705 builder.setDeleteIntent(PendingIntent.getBroadcast(
706 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
707
708 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700709 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800710 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
711
Jeff Sharkey497e4432011-06-14 17:27:29 -0700712 break;
713 }
714 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700715 final CharSequence body = res.getText(R.string.data_usage_limit_body);
716
717 final CharSequence title;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700718 switch (policy.template.getMatchRule()) {
719 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700720 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700721 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700722 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700723 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700724 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700725 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700726 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700727 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700728 case MATCH_WIFI:
729 title = res.getText(R.string.data_usage_wifi_limit_title);
730 break;
731 default:
732 title = null;
733 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700734 }
735
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800736 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700737 builder.setSmallIcon(R.drawable.stat_notify_disabled);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700738 builder.setTicker(title);
739 builder.setContentTitle(title);
740 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700741
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700742 final Intent intent = buildNetworkOverLimitIntent(policy.template);
743 builder.setContentIntent(PendingIntent.getActivity(
744 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
745 break;
746 }
747 case TYPE_LIMIT_SNOOZED: {
748 final long overBytes = totalBytes - policy.limitBytes;
749 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
750 Formatter.formatFileSize(mContext, overBytes));
751
752 final CharSequence title;
753 switch (policy.template.getMatchRule()) {
754 case MATCH_MOBILE_3G_LOWER:
755 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
756 break;
757 case MATCH_MOBILE_4G:
758 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
759 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700760 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700761 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
762 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700763 case MATCH_WIFI:
764 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
765 break;
766 default:
767 title = null;
768 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700769 }
770
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800771 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700772 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700773 builder.setTicker(title);
774 builder.setContentTitle(title);
775 builder.setContentText(body);
776
777 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700778 builder.setContentIntent(PendingIntent.getActivity(
779 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700780 break;
781 }
782 }
783
784 // TODO: move to NotificationManager once we can mock it
785 try {
786 final String packageName = mContext.getPackageName();
787 final int[] idReceived = new int[1];
788 mNotifManager.enqueueNotificationWithTag(
789 packageName, tag, 0x0, builder.getNotification(), idReceived);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700790 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700791 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700792 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700793 }
794 }
795
796 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700797 * Show ongoing notification to reflect that {@link #mRestrictBackground}
798 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700799 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700800 private void enqueueRestrictedNotification(String tag) {
801 final Resources res = mContext.getResources();
802 final Notification.Builder builder = new Notification.Builder(mContext);
803
804 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
805 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
806
807 builder.setOnlyAlertOnce(true);
808 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700809 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700810 builder.setTicker(title);
811 builder.setContentTitle(title);
812 builder.setContentText(body);
813
814 final Intent intent = buildAllowBackgroundDataIntent();
815 builder.setContentIntent(
816 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700817
818 // TODO: move to NotificationManager once we can mock it
819 try {
820 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700821 final int[] idReceived = new int[1];
822 mNotifManager.enqueueNotificationWithTag(packageName, tag,
823 0x0, builder.getNotification(), idReceived);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700824 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700825 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700826 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700827 }
828 }
829
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700830 private void cancelNotification(String tag) {
831 // TODO: move to NotificationManager once we can mock it
832 try {
833 final String packageName = mContext.getPackageName();
834 mNotifManager.cancelNotificationWithTag(
835 packageName, tag, 0x0);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700836 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700837 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700838 }
839 }
840
841 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700842 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700843 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700844 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700845 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700846 @Override
847 public void onReceive(Context context, Intent intent) {
848 // on background handler thread, and verified CONNECTIVITY_INTERNAL
849 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800850
851 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700852 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700853 ensureActiveMobilePolicyLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700854 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700855 updateNetworkRulesLocked();
856 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700857 }
858 }
859 };
860
861 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700862 * Proactively control network data connections when they exceed
863 * {@link NetworkPolicy#limitBytes}.
864 */
865 private void updateNetworkEnabledLocked() {
866 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
867
868 // TODO: reset any policy-disabled networks when any policy is removed
869 // completely, which is currently rare case.
870
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800871 final long currentTime = currentTimeMillis();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700872 for (NetworkPolicy policy : mNetworkPolicy.values()) {
873 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700874 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700875 setNetworkTemplateEnabled(policy.template, true);
876 continue;
877 }
878
879 final long start = computeLastCycleBoundary(currentTime, policy);
880 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700881 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700882
883 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800884 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
885 && policy.lastLimitSnooze < start;
886 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700887
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800888 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700889 }
890 }
891
892 /**
893 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}
894 * for the given {@link NetworkTemplate}.
895 */
896 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700897 final TelephonyManager tele = TelephonyManager.from(mContext);
898
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700899 switch (template.getMatchRule()) {
900 case MATCH_MOBILE_3G_LOWER:
901 case MATCH_MOBILE_4G:
902 case MATCH_MOBILE_ALL:
903 // TODO: offer more granular control over radio states once
904 // 4965893 is available.
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700905 if (tele.getSimState() == SIM_STATE_READY
906 && Objects.equal(tele.getSubscriberId(), template.getSubscriberId())) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700907 setPolicyDataEnable(TYPE_MOBILE, enabled);
908 setPolicyDataEnable(TYPE_WIMAX, enabled);
909 }
910 break;
911 case MATCH_WIFI:
912 setPolicyDataEnable(TYPE_WIFI, enabled);
913 break;
914 case MATCH_ETHERNET:
915 setPolicyDataEnable(TYPE_ETHERNET, enabled);
916 break;
917 default:
918 throw new IllegalArgumentException("unexpected template");
919 }
920 }
921
922 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700923 * Examine all connected {@link NetworkState}, looking for
924 * {@link NetworkPolicy} that need to be enforced. When matches found, set
925 * remaining quota based on usage cycle and historical stats.
926 */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700927 private void updateNetworkRulesLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700928 if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700929
930 final NetworkState[] states;
931 try {
932 states = mConnManager.getAllNetworkState();
933 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700934 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700935 return;
936 }
937
938 // first, derive identity for all connected networks, which can be used
939 // to match against templates.
940 final HashMap<NetworkIdentity, String> networks = Maps.newHashMap();
941 for (NetworkState state : states) {
942 // stash identity and iface away for later use
943 if (state.networkInfo.isConnected()) {
944 final String iface = state.linkProperties.getInterfaceName();
945 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
946 networks.put(ident, iface);
947 }
948 }
949
950 // build list of rules and ifaces to enforce them against
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700951 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700952 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700953 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700954
955 // collect all active ifaces that match this template
956 ifaceList.clear();
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700957 for (Map.Entry<NetworkIdentity, String> entry : networks.entrySet()) {
958 final NetworkIdentity ident = entry.getKey();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700959 if (policy.template.matches(ident)) {
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700960 final String iface = entry.getValue();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700961 ifaceList.add(iface);
962 }
963 }
964
965 if (ifaceList.size() > 0) {
966 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700967 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700968 }
969 }
970
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700971 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700972 final HashSet<String> newMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700973
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700974 // apply each policy that we found ifaces for; compute remaining data
975 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800976 final long currentTime = currentTimeMillis();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700977 for (NetworkPolicy policy : mNetworkRules.keySet()) {
978 final String[] ifaces = mNetworkRules.get(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700979
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700980 final long start;
981 final long totalBytes;
982 if (policy.hasCycle()) {
983 start = computeLastCycleBoundary(currentTime, policy);
984 totalBytes = getTotalBytes(policy.template, start, currentTime);
985 } else {
986 start = Long.MAX_VALUE;
987 totalBytes = 0;
988 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700989
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700990 if (LOGD) {
991 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700992 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700993 }
994
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700995 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700996 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800997 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700998 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800999 if (!hasLimit) {
1000 // metered network, but no policy limit; we still need to
1001 // restrict apps, so push really high quota.
1002 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001003 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001004 // snoozing past quota, but we still need to restrict apps,
1005 // so push really high quota.
1006 quotaBytes = Long.MAX_VALUE;
1007 } else {
1008 // remaining "quota" bytes are based on total usage in
1009 // current cycle. kernel doesn't like 0-byte rules, so we
1010 // set 1-byte quota and disable the radio later.
1011 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1012 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001013
1014 if (ifaces.length > 1) {
1015 // TODO: switch to shared quota once NMS supports
1016 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001017 }
1018
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001019 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001020 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001021 setInterfaceQuota(iface, quotaBytes);
1022 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001023 }
1024 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001025
1026 // keep track of lowest warning or limit of active policies
1027 if (hasWarning && policy.warningBytes < lowestRule) {
1028 lowestRule = policy.warningBytes;
1029 }
1030 if (hasLimit && policy.limitBytes < lowestRule) {
1031 lowestRule = policy.limitBytes;
1032 }
1033 }
1034
1035 try {
1036 // make sure stats are recorded frequently enough; we aim for 2MB
1037 // threshold for 2GB/month rules.
1038 final long persistThreshold = lowestRule / 1000;
1039 mNetworkStats.advisePersistThreshold(persistThreshold);
1040 } catch (RemoteException e) {
1041 // ignored; service lives in system_server
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001042 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001043
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001044 // remove quota on any trailing interfaces
1045 for (String iface : mMeteredIfaces) {
1046 if (!newMeteredIfaces.contains(iface)) {
1047 removeInterfaceQuota(iface);
1048 }
1049 }
1050 mMeteredIfaces = newMeteredIfaces;
1051
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001052 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001053 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001054 }
1055
1056 /**
1057 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1058 * have at least a default mobile policy defined.
1059 */
1060 private void ensureActiveMobilePolicyLocked() {
1061 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001062 if (mSuppressDefaultPolicy) return;
1063
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001064 final TelephonyManager tele = TelephonyManager.from(mContext);
1065
1066 // avoid creating policy when SIM isn't ready
1067 if (tele.getSimState() != SIM_STATE_READY) return;
1068
1069 final String subscriberId = tele.getSubscriberId();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001070 final NetworkIdentity probeIdent = new NetworkIdentity(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001071 TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001072
1073 // examine to see if any policy is defined for active mobile
1074 boolean mobileDefined = false;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001075 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001076 if (policy.template.matches(probeIdent)) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001077 mobileDefined = true;
1078 }
1079 }
1080
1081 if (!mobileDefined) {
1082 Slog.i(TAG, "no policy for active mobile network; generating default policy");
1083
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001084 // build default mobile policy, and assume usage cycle starts today
1085 final long warningBytes = mContext.getResources().getInteger(
1086 com.android.internal.R.integer.config_networkPolicyDefaultWarning)
1087 * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001088
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001089 final Time time = new Time();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001090 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001091
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001092 final int cycleDay = time.monthDay;
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001093 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001094
Jeff Sharkey4e814c32011-07-14 20:37:37 -07001095 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001096 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1097 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1098 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001099 }
1100 }
1101
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001102 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001103 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001104
1105 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001106 mNetworkPolicy.clear();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001107 mAppPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001108
1109 FileInputStream fis = null;
1110 try {
1111 fis = mPolicyFile.openRead();
1112 final XmlPullParser in = Xml.newPullParser();
1113 in.setInput(fis, null);
1114
1115 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001116 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001117 while ((type = in.next()) != END_DOCUMENT) {
1118 final String tag = in.getName();
1119 if (type == START_TAG) {
1120 if (TAG_POLICY_LIST.equals(tag)) {
1121 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001122 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1123 mRestrictBackground = readBooleanAttribute(
1124 in, ATTR_RESTRICT_BACKGROUND);
1125 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001126 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001127 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001128
1129 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1130 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1131 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001132 final String networkId;
1133 if (version >= VERSION_ADDED_NETWORK_ID) {
1134 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1135 } else {
1136 networkId = null;
1137 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001138 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001139 final String cycleTimezone;
1140 if (version >= VERSION_ADDED_TIMEZONE) {
1141 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1142 } else {
1143 cycleTimezone = Time.TIMEZONE_UTC;
1144 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001145 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1146 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001147 final long lastLimitSnooze;
1148 if (version >= VERSION_SPLIT_SNOOZE) {
1149 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1150 } else if (version >= VERSION_ADDED_SNOOZE) {
1151 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001152 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001153 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001154 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001155 final boolean metered;
1156 if (version >= VERSION_ADDED_METERED) {
1157 metered = readBooleanAttribute(in, ATTR_METERED);
1158 } else {
1159 switch (networkTemplate) {
1160 case MATCH_MOBILE_3G_LOWER:
1161 case MATCH_MOBILE_4G:
1162 case MATCH_MOBILE_ALL:
1163 metered = true;
1164 break;
1165 default:
1166 metered = false;
1167 }
1168 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001169 final long lastWarningSnooze;
1170 if (version >= VERSION_SPLIT_SNOOZE) {
1171 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1172 } else {
1173 lastWarningSnooze = SNOOZE_NEVER;
1174 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001175 final boolean inferred;
1176 if (version >= VERSION_ADDED_INFERRED) {
1177 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1178 } else {
1179 inferred = false;
1180 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001181
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001182 final NetworkTemplate template = new NetworkTemplate(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001183 networkTemplate, subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001184 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001185 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001186 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001187
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001188 } else if (TAG_UID_POLICY.equals(tag) && version < VERSION_SWITCH_APP_ID) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001189 final int uid = readIntAttribute(in, ATTR_UID);
1190 final int policy = readIntAttribute(in, ATTR_POLICY);
1191
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001192 final int appId = UserId.getAppId(uid);
1193 if (UserId.isApp(appId)) {
1194 setAppPolicyUnchecked(appId, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001195 } else {
1196 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1197 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001198 } else if (TAG_APP_POLICY.equals(tag) && version >= VERSION_SWITCH_APP_ID) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001199 final int appId = readIntAttribute(in, ATTR_APP_ID);
1200 final int policy = readIntAttribute(in, ATTR_POLICY);
1201
1202 if (UserId.isApp(appId)) {
1203 setAppPolicyUnchecked(appId, policy, false);
1204 } else {
1205 Slog.w(TAG, "unable to apply policy to appId " + appId + "; ignoring");
1206 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001207 }
1208 }
1209 }
1210
1211 } catch (FileNotFoundException e) {
1212 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001213 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001214 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001215 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001216 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001217 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001218 } finally {
1219 IoUtils.closeQuietly(fis);
1220 }
1221 }
1222
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001223 /**
1224 * Upgrade legacy background data flags, notifying listeners of one last
1225 * change to always-true.
1226 */
1227 private void upgradeLegacyBackgroundData() {
1228 mRestrictBackground = Settings.Secure.getInt(
1229 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1230
1231 // kick off one last broadcast if restricted
1232 if (mRestrictBackground) {
1233 final Intent broadcast = new Intent(
1234 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1235 mContext.sendBroadcast(broadcast);
1236 }
1237 }
1238
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001239 private void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001240 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001241
1242 FileOutputStream fos = null;
1243 try {
1244 fos = mPolicyFile.startWrite();
1245
1246 XmlSerializer out = new FastXmlSerializer();
1247 out.setOutput(fos, "utf-8");
1248 out.startDocument(null, true);
1249
1250 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001251 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001252 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001253
1254 // write all known network policies
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001255 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001256 final NetworkTemplate template = policy.template;
1257
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001258 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001259 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1260 final String subscriberId = template.getSubscriberId();
1261 if (subscriberId != null) {
1262 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001263 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001264 final String networkId = template.getNetworkId();
1265 if (networkId != null) {
1266 out.attribute(null, ATTR_NETWORK_ID, networkId);
1267 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001268 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001269 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001270 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1271 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001272 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1273 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001274 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001275 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001276 out.endTag(null, TAG_NETWORK_POLICY);
1277 }
1278
1279 // write all known uid policies
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001280 for (int i = 0; i < mAppPolicy.size(); i++) {
1281 final int appId = mAppPolicy.keyAt(i);
1282 final int policy = mAppPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001283
Jeff Sharkey497e4432011-06-14 17:27:29 -07001284 // skip writing empty policies
1285 if (policy == POLICY_NONE) continue;
1286
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001287 out.startTag(null, TAG_APP_POLICY);
1288 writeIntAttribute(out, ATTR_APP_ID, appId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001289 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001290 out.endTag(null, TAG_APP_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001291 }
1292
1293 out.endTag(null, TAG_POLICY_LIST);
1294 out.endDocument();
1295
1296 mPolicyFile.finishWrite(fos);
1297 } catch (IOException e) {
1298 if (fos != null) {
1299 mPolicyFile.failWrite(fos);
1300 }
1301 }
1302 }
1303
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001304 @Override
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001305 public void setAppPolicy(int appId, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001306 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001307
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001308 if (!UserId.isApp(appId)) {
1309 throw new IllegalArgumentException("cannot apply policy to appId " + appId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001310 }
1311
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001312 setAppPolicyUnchecked(appId, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001313 }
1314
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001315 private void setAppPolicyUnchecked(int appId, int policy, boolean persist) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001316 final int oldPolicy;
Jeff Sharkeya4620792011-05-20 15:29:23 -07001317 synchronized (mRulesLock) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001318 oldPolicy = getAppPolicy(appId);
1319 mAppPolicy.put(appId, policy);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001320
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001321 // uid policy changed, recompute rules and persist policy.
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001322 updateRulesForAppLocked(appId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001323 if (persist) {
1324 writePolicyLocked();
1325 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001326 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001327 }
1328
1329 @Override
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001330 public int getAppPolicy(int appId) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001331 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1332
Jeff Sharkeya4620792011-05-20 15:29:23 -07001333 synchronized (mRulesLock) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001334 return mAppPolicy.get(appId, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001335 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001336 }
1337
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001338 @Override
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001339 public int[] getAppsWithPolicy(int policy) {
1340 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1341
1342 int[] appIds = new int[0];
1343 synchronized (mRulesLock) {
1344 for (int i = 0; i < mAppPolicy.size(); i++) {
1345 final int appId = mAppPolicy.keyAt(i);
1346 final int appPolicy = mAppPolicy.valueAt(i);
1347 if (appPolicy == policy) {
1348 appIds = appendInt(appIds, appId);
1349 }
1350 }
1351 }
1352 return appIds;
1353 }
1354
1355 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001356 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001357 // TODO: create permission for observing network policy
1358 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1359
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001360 mListeners.register(listener);
1361
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001362 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001363 }
1364
1365 @Override
1366 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001367 // TODO: create permission for observing network policy
1368 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1369
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001370 mListeners.unregister(listener);
1371 }
1372
Jeff Sharkey1b861272011-05-22 00:34:52 -07001373 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001374 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001375 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1376
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001377 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001378 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001379 mNetworkPolicy.clear();
1380 for (NetworkPolicy policy : policies) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001381 mNetworkPolicy.put(policy.template, policy);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001382 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001383
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001384 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001385 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001386 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001387 writePolicyLocked();
1388 }
1389 }
1390
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001391 private void addNetworkPolicyLocked(NetworkPolicy policy) {
1392 mNetworkPolicy.put(policy.template, policy);
1393
1394 updateNetworkEnabledLocked();
1395 updateNetworkRulesLocked();
1396 updateNotificationsLocked();
1397 writePolicyLocked();
1398 }
1399
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001400 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001401 public NetworkPolicy[] getNetworkPolicies() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001402 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001403 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001404
1405 synchronized (mRulesLock) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001406 return mNetworkPolicy.values().toArray(new NetworkPolicy[mNetworkPolicy.size()]);
1407 }
1408 }
1409
1410 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001411 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001412 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001413 performSnooze(template, TYPE_LIMIT);
1414 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001415
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001416 private void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001417 maybeRefreshTrustedTime();
1418 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001419 synchronized (mRulesLock) {
1420 // find and snooze local policy that matches
1421 final NetworkPolicy policy = mNetworkPolicy.get(template);
1422 if (policy == null) {
1423 throw new IllegalArgumentException("unable to find policy for " + template);
1424 }
1425
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001426 switch (type) {
1427 case TYPE_WARNING:
1428 policy.lastWarningSnooze = currentTime;
1429 break;
1430 case TYPE_LIMIT:
1431 policy.lastLimitSnooze = currentTime;
1432 break;
1433 default:
1434 throw new IllegalArgumentException("unexpected type");
1435 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001436
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001437 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001438 updateNetworkRulesLocked();
1439 updateNotificationsLocked();
1440 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001441 }
1442 }
1443
1444 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001445 public void setRestrictBackground(boolean restrictBackground) {
1446 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1447
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001448 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001449 synchronized (mRulesLock) {
1450 mRestrictBackground = restrictBackground;
1451 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001452 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001453 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001454 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001455
1456 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1457 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001458 }
1459
1460 @Override
1461 public boolean getRestrictBackground() {
1462 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1463
1464 synchronized (mRulesLock) {
1465 return mRestrictBackground;
1466 }
1467 }
1468
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001469 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
1470 for (NetworkPolicy policy : mNetworkPolicy.values()) {
1471 if (policy.template.matches(ident)) {
1472 return policy;
1473 }
1474 }
1475 return null;
1476 }
1477
1478 @Override
1479 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1480 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1481
1482 // only returns usage summary, so we don't require caller to have
1483 // READ_NETWORK_USAGE_HISTORY.
1484 final long token = Binder.clearCallingIdentity();
1485 try {
1486 return getNetworkQuotaInfoUnchecked(state);
1487 } finally {
1488 Binder.restoreCallingIdentity(token);
1489 }
1490 }
1491
1492 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1493 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1494
1495 final NetworkPolicy policy;
1496 synchronized (mRulesLock) {
1497 policy = findPolicyForNetworkLocked(ident);
1498 }
1499
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001500 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001501 // missing policy means we can't derive useful quota info
1502 return null;
1503 }
1504
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001505 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001506
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001507 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001508 final long start = computeLastCycleBoundary(currentTime, policy);
1509 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001510 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001511
1512 // report soft and hard limits under policy
1513 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1514 : NetworkQuotaInfo.NO_LIMIT;
1515 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1516 : NetworkQuotaInfo.NO_LIMIT;
1517
1518 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1519 }
1520
Jeff Sharkey46645002011-07-27 21:11:21 -07001521 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001522 public boolean isNetworkMetered(NetworkState state) {
1523 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1524
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001525 // roaming networks are always considered metered
1526 if (ident.getRoaming()) {
1527 return true;
1528 }
1529
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001530 final NetworkPolicy policy;
1531 synchronized (mRulesLock) {
1532 policy = findPolicyForNetworkLocked(ident);
1533 }
1534
1535 if (policy != null) {
1536 return policy.metered;
1537 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001538 final int type = state.networkInfo.getType();
1539 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1540 return true;
1541 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001542 return false;
1543 }
1544 }
1545
1546 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001547 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001548 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001549
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001550 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1551
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001552 final HashSet<String> argSet = new HashSet<String>();
1553 for (String arg : args) {
1554 argSet.add(arg);
1555 }
1556
Jeff Sharkey1b861272011-05-22 00:34:52 -07001557 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001558 if (argSet.contains("--unsnooze")) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001559 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001560 policy.clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001561 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001562
1563 updateNetworkEnabledLocked();
1564 updateNetworkRulesLocked();
1565 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001566 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001567
1568 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001569 return;
1570 }
1571
Jeff Sharkey46645002011-07-27 21:11:21 -07001572 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001573 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001574 fout.increaseIndent();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001575 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001576 fout.println(policy.toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001577 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001578 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001579
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001580 fout.println("Policy for apps:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001581 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001582 int size = mAppPolicy.size();
1583 for (int i = 0; i < size; i++) {
1584 final int appId = mAppPolicy.keyAt(i);
1585 final int policy = mAppPolicy.valueAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001586 fout.print("appId=");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001587 fout.print(appId);
1588 fout.print(" policy=");
1589 dumpPolicy(fout, policy);
1590 fout.println();
1591 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001592 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001593
1594 final SparseBooleanArray knownUids = new SparseBooleanArray();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001595 collectKeys(mUidForeground, knownUids);
1596 collectKeys(mUidRules, knownUids);
1597
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001598 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001599 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001600 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001601 for (int i = 0; i < size; i++) {
1602 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001603 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001604 fout.print(uid);
1605
Jeff Sharkey1b861272011-05-22 00:34:52 -07001606 fout.print(" foreground=");
1607 final int foregroundIndex = mUidPidForeground.indexOfKey(uid);
1608 if (foregroundIndex < 0) {
1609 fout.print("UNKNOWN");
1610 } else {
1611 dumpSparseBooleanArray(fout, mUidPidForeground.valueAt(foregroundIndex));
1612 }
1613
1614 fout.print(" rules=");
1615 final int rulesIndex = mUidRules.indexOfKey(uid);
1616 if (rulesIndex < 0) {
1617 fout.print("UNKNOWN");
1618 } else {
1619 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1620 }
1621
1622 fout.println();
1623 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001624 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001625 }
1626 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001627
1628 @Override
1629 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001630 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1631
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001632 synchronized (mRulesLock) {
1633 // only really in foreground when screen is also on
1634 return mUidForeground.get(uid, false) && mScreenOn;
1635 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001636 }
1637
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001638 /**
1639 * Foreground for PID changed; recompute foreground at UID level. If
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001640 * changed, will trigger {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001641 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001642 private void computeUidForegroundLocked(int uid) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001643 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1644
1645 // current pid is dropping foreground; examine other pids
1646 boolean uidForeground = false;
1647 final int size = pidForeground.size();
1648 for (int i = 0; i < size; i++) {
1649 if (pidForeground.valueAt(i)) {
1650 uidForeground = true;
1651 break;
1652 }
1653 }
1654
1655 final boolean oldUidForeground = mUidForeground.get(uid, false);
1656 if (oldUidForeground != uidForeground) {
1657 // foreground changed, push updated rules
1658 mUidForeground.put(uid, uidForeground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001659 updateRulesForUidLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001660 }
1661 }
1662
Jeff Sharkeya4620792011-05-20 15:29:23 -07001663 private void updateScreenOn() {
1664 synchronized (mRulesLock) {
1665 try {
1666 mScreenOn = mPowerManager.isScreenOn();
1667 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001668 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07001669 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001670 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001671 }
1672 }
1673
1674 /**
1675 * Update rules that might be changed by {@link #mScreenOn} value.
1676 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001677 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07001678 // only update rules for anyone with foreground activities
1679 final int size = mUidForeground.size();
1680 for (int i = 0; i < size; i++) {
1681 if (mUidForeground.valueAt(i)) {
1682 final int uid = mUidForeground.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001683 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001684 }
1685 }
1686 }
1687
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001688 /**
Jeff Sharkey46645002011-07-27 21:11:21 -07001689 * Update rules that might be changed by {@link #mRestrictBackground} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001690 */
Jeff Sharkey46645002011-07-27 21:11:21 -07001691 private void updateRulesForRestrictBackgroundLocked() {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001692 // update rules for all installed applications
1693 final PackageManager pm = mContext.getPackageManager();
1694 final List<ApplicationInfo> apps = pm.getInstalledApplications(0);
1695 for (ApplicationInfo app : apps) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001696 final int appId = UserId.getAppId(app.uid);
1697 updateRulesForAppLocked(appId);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001698 }
1699
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001700 // limit data usage for some internal system services
1701 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
1702 updateRulesForUidLocked(android.os.Process.DRM_UID);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001703 }
1704
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001705 private void updateRulesForAppLocked(int appId) {
1706 for (UserInfo user : mContext.getPackageManager().getUsers()) {
1707 final int uid = UserId.getUid(user.id, appId);
1708 updateRulesForUidLocked(uid);
1709 }
1710 }
1711
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001712 private static boolean isUidValidForRules(int uid) {
1713 // allow rules on specific system services, and any apps
1714 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
1715 || UserId.isApp(uid)) {
1716 return true;
1717 }
1718
1719 return false;
1720 }
1721
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001722 private void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001723 if (!isUidValidForRules(uid)) return;
1724
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001725 final int appId = UserId.getAppId(uid);
1726 final int appPolicy = getAppPolicy(appId);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001727 final boolean uidForeground = isUidForeground(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001728
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001729 // derive active rules based on policy and active state
1730 int uidRules = RULE_ALLOW_ALL;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001731 if (!uidForeground && (appPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001732 // uid in background, and policy says to block metered data
1733 uidRules = RULE_REJECT_METERED;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001734 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001735 if (!uidForeground && mRestrictBackground) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001736 // uid in background, and global background disabled
1737 uidRules = RULE_REJECT_METERED;
1738 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001739
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001740 // TODO: only dispatch when rules actually change
1741
Jeff Sharkey350083e2011-06-29 10:45:16 -07001742 if (uidRules == RULE_ALLOW_ALL) {
1743 mUidRules.delete(uid);
1744 } else {
1745 mUidRules.put(uid, uidRules);
1746 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001747
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001748 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001749 setUidNetworkRules(uid, rejectMetered);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001750
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001751 // dispatch changed rule to existing listeners
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001752 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001753
1754 try {
1755 // adjust stats accounting based on foreground status
1756 mNetworkStats.setUidForeground(uid, uidForeground);
1757 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001758 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001759 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001760 }
1761
1762 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001763 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001764 public boolean handleMessage(Message msg) {
1765 switch (msg.what) {
1766 case MSG_RULES_CHANGED: {
1767 final int uid = msg.arg1;
1768 final int uidRules = msg.arg2;
1769 final int length = mListeners.beginBroadcast();
1770 for (int i = 0; i < length; i++) {
1771 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1772 if (listener != null) {
1773 try {
1774 listener.onUidRulesChanged(uid, uidRules);
1775 } catch (RemoteException e) {
1776 }
1777 }
1778 }
1779 mListeners.finishBroadcast();
1780 return true;
1781 }
1782 case MSG_METERED_IFACES_CHANGED: {
1783 final String[] meteredIfaces = (String[]) msg.obj;
1784 final int length = mListeners.beginBroadcast();
1785 for (int i = 0; i < length; i++) {
1786 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1787 if (listener != null) {
1788 try {
1789 listener.onMeteredIfacesChanged(meteredIfaces);
1790 } catch (RemoteException e) {
1791 }
1792 }
1793 }
1794 mListeners.finishBroadcast();
1795 return true;
1796 }
Jeff Sharkey6f7af032011-11-01 18:25:15 -07001797 case MSG_FOREGROUND_ACTIVITIES_CHANGED: {
1798 final int pid = msg.arg1;
1799 final int uid = msg.arg2;
1800 final boolean foregroundActivities = (Boolean) msg.obj;
1801
1802 synchronized (mRulesLock) {
1803 // because a uid can have multiple pids running inside, we need to
1804 // remember all pid states and summarize foreground at uid level.
1805
1806 // record foreground for this specific pid
1807 SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1808 if (pidForeground == null) {
1809 pidForeground = new SparseBooleanArray(2);
1810 mUidPidForeground.put(uid, pidForeground);
1811 }
1812 pidForeground.put(pid, foregroundActivities);
1813 computeUidForegroundLocked(uid);
1814 }
1815 return true;
1816 }
1817 case MSG_PROCESS_DIED: {
1818 final int pid = msg.arg1;
1819 final int uid = msg.arg2;
1820
1821 synchronized (mRulesLock) {
1822 // clear records and recompute, when they exist
1823 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1824 if (pidForeground != null) {
1825 pidForeground.delete(pid);
1826 computeUidForegroundLocked(uid);
1827 }
1828 }
1829 return true;
1830 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001831 case MSG_LIMIT_REACHED: {
1832 final String iface = (String) msg.obj;
1833
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001834 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001835 synchronized (mRulesLock) {
1836 if (mMeteredIfaces.contains(iface)) {
1837 try {
1838 // force stats update to make sure we have
1839 // numbers that caused alert to trigger.
1840 mNetworkStats.forceUpdate();
1841 } catch (RemoteException e) {
1842 // ignored; service lives in system_server
1843 }
1844
1845 updateNetworkEnabledLocked();
1846 updateNotificationsLocked();
1847 }
1848 }
1849 return true;
1850 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001851 case MSG_RESTRICT_BACKGROUND_CHANGED: {
1852 final boolean restrictBackground = msg.arg1 != 0;
1853 final int length = mListeners.beginBroadcast();
1854 for (int i = 0; i < length; i++) {
1855 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1856 if (listener != null) {
1857 try {
1858 listener.onRestrictBackgroundChanged(restrictBackground);
1859 } catch (RemoteException e) {
1860 }
1861 }
1862 }
1863 mListeners.finishBroadcast();
1864 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001865 default: {
1866 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07001867 }
1868 }
1869 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001870 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001871
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001872 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001873 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001874 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001875 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001876 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001877 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001878 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001879 }
1880 }
1881
1882 private void removeInterfaceQuota(String iface) {
1883 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001884 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001885 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001886 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001887 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001888 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001889 }
1890 }
1891
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001892 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1893 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001894 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001895 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001896 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001897 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001898 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001899 }
1900 }
1901
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001902 /**
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001903 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001904 */
1905 private void setPolicyDataEnable(int networkType, boolean enabled) {
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001906 try {
1907 mConnManager.setPolicyDataEnable(networkType, enabled);
1908 } catch (RemoteException e) {
1909 // ignored; service lives in system_server
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001910 }
1911 }
1912
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001913 private long getTotalBytes(NetworkTemplate template, long start, long end) {
1914 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07001915 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001916 } catch (RuntimeException e) {
1917 Slog.w(TAG, "problem reading network stats: " + e);
1918 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001919 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001920 // ignored; service lives in system_server
1921 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001922 }
1923 }
1924
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07001925 private boolean isBandwidthControlEnabled() {
1926 final long token = Binder.clearCallingIdentity();
1927 try {
1928 return mNetworkManager.isBandwidthControlEnabled();
1929 } catch (RemoteException e) {
1930 // ignored; service lives in system_server
1931 return false;
1932 } finally {
1933 Binder.restoreCallingIdentity(token);
1934 }
1935 }
1936
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001937 /**
1938 * Try refreshing {@link #mTime} when stale.
1939 */
1940 private void maybeRefreshTrustedTime() {
1941 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001942 mTime.forceRefresh();
1943 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001944 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001945
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001946 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001947 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
1948 }
1949
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001950 private static Intent buildAllowBackgroundDataIntent() {
1951 return new Intent(ACTION_ALLOW_BACKGROUND);
1952 }
1953
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001954 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
1955 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
1956 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
1957 return intent;
1958 }
1959
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001960 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
1961 final Intent intent = new Intent();
1962 intent.setComponent(new ComponentName(
1963 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
1964 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1965 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
1966 return intent;
1967 }
1968
1969 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
1970 final Intent intent = new Intent();
1971 intent.setComponent(new ComponentName(
1972 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
1973 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1974 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
1975 return intent;
1976 }
1977
Jeff Sharkey163e6442011-10-31 16:37:52 -07001978 // @VisibleForTesting
1979 public void addIdleHandler(IdleHandler handler) {
1980 mHandler.getLooper().getQueue().addIdleHandler(handler);
1981 }
1982
Jeff Sharkey1b861272011-05-22 00:34:52 -07001983 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
1984 final int size = source.size();
1985 for (int i = 0; i < size; i++) {
1986 target.put(source.keyAt(i), true);
1987 }
1988 }
1989
1990 private static void collectKeys(SparseBooleanArray source, SparseBooleanArray target) {
1991 final int size = source.size();
1992 for (int i = 0; i < size; i++) {
1993 target.put(source.keyAt(i), true);
1994 }
1995 }
1996
1997 private static void dumpSparseBooleanArray(PrintWriter fout, SparseBooleanArray value) {
1998 fout.print("[");
1999 final int size = value.size();
2000 for (int i = 0; i < size; i++) {
2001 fout.print(value.keyAt(i) + "=" + value.valueAt(i));
2002 if (i < size - 1) fout.print(",");
2003 }
2004 fout.print("]");
2005 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002006
Jeff Sharkey46645002011-07-27 21:11:21 -07002007 public static class XmlUtils {
2008 public static int readIntAttribute(XmlPullParser in, String name) throws IOException {
2009 final String value = in.getAttributeValue(null, name);
2010 try {
2011 return Integer.parseInt(value);
2012 } catch (NumberFormatException e) {
2013 throw new ProtocolException("problem parsing " + name + "=" + value + " as int");
2014 }
2015 }
2016
2017 public static void writeIntAttribute(XmlSerializer out, String name, int value)
2018 throws IOException {
2019 out.attribute(null, name, Integer.toString(value));
2020 }
2021
2022 public static long readLongAttribute(XmlPullParser in, String name) throws IOException {
2023 final String value = in.getAttributeValue(null, name);
2024 try {
2025 return Long.parseLong(value);
2026 } catch (NumberFormatException e) {
2027 throw new ProtocolException("problem parsing " + name + "=" + value + " as long");
2028 }
2029 }
2030
2031 public static void writeLongAttribute(XmlSerializer out, String name, long value)
2032 throws IOException {
2033 out.attribute(null, name, Long.toString(value));
2034 }
2035
2036 public static boolean readBooleanAttribute(XmlPullParser in, String name) {
2037 final String value = in.getAttributeValue(null, name);
2038 return Boolean.parseBoolean(value);
2039 }
2040
2041 public static void writeBooleanAttribute(XmlSerializer out, String name, boolean value)
2042 throws IOException {
2043 out.attribute(null, name, Boolean.toString(value));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002044 }
2045 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002046}