blob: c82f37cbe3ef775a5887c6cc6414173b935525cc [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 Sharkey21c9c452011-06-07 12:26:43 -0700121import android.util.NtpTrustedTime;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700122import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700123import android.util.SparseArray;
124import android.util.SparseBooleanArray;
125import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700126import android.util.TrustedTime;
127import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700128
Jeff Sharkey497e4432011-06-14 17:27:29 -0700129import com.android.internal.R;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700130import com.android.internal.os.AtomicFile;
131import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700132import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700133import com.android.internal.util.Objects;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700134import com.google.android.collect.Lists;
135import com.google.android.collect.Maps;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700136import com.google.android.collect.Sets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700137
138import org.xmlpull.v1.XmlPullParser;
139import org.xmlpull.v1.XmlPullParserException;
140import org.xmlpull.v1.XmlSerializer;
141
142import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700143import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700144import java.io.FileInputStream;
145import java.io.FileNotFoundException;
146import java.io.FileOutputStream;
147import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700148import java.io.PrintWriter;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700149import java.net.ProtocolException;
150import java.util.ArrayList;
151import java.util.Arrays;
152import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700153import java.util.HashSet;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700154import java.util.List;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700155import java.util.Map;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700156
157import libcore.io.IoUtils;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700158
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700159/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700160 * Service that maintains low-level network policy rules, using
161 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700162 * <p>
163 * Derives active rules by combining a given policy with other system status,
164 * and delivers to listeners, such as {@link ConnectivityManager}, for
165 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700166 */
167public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
168 private static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700169 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700170 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700171
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700172 private static final int VERSION_INIT = 1;
173 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700174 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800175 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800176 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800177 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700178 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700179 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700180 private static final int VERSION_ADDED_NETWORK_ID = 9;
181 private static final int VERSION_LATEST = VERSION_ADDED_NETWORK_ID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700182
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700183 // @VisibleForTesting
184 public static final int TYPE_WARNING = 0x1;
185 public static final int TYPE_LIMIT = 0x2;
186 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700187
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700188 private static final String TAG_POLICY_LIST = "policy-list";
189 private static final String TAG_NETWORK_POLICY = "network-policy";
190 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700191 private static final String TAG_APP_POLICY = "app-policy";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700192
193 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700194 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700195 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
196 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700197 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700198 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800199 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700200 private static final String ATTR_WARNING_BYTES = "warningBytes";
201 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700202 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800203 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
204 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800205 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700206 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700207 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700208 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700209 private static final String ATTR_POLICY = "policy";
210
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700211 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
212
213 // @VisibleForTesting
214 public static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800215 "com.android.server.net.action.ALLOW_BACKGROUND";
216 public static final String ACTION_SNOOZE_WARNING =
217 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700218
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700219 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
220
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700221 private static final int MSG_RULES_CHANGED = 1;
222 private static final int MSG_METERED_IFACES_CHANGED = 2;
223 private static final int MSG_FOREGROUND_ACTIVITIES_CHANGED = 3;
224 private static final int MSG_PROCESS_DIED = 4;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800225 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800226 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700227 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
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
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001035 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001036
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001037 // remove quota on any trailing interfaces
1038 for (String iface : mMeteredIfaces) {
1039 if (!newMeteredIfaces.contains(iface)) {
1040 removeInterfaceQuota(iface);
1041 }
1042 }
1043 mMeteredIfaces = newMeteredIfaces;
1044
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001045 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001046 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001047 }
1048
1049 /**
1050 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1051 * have at least a default mobile policy defined.
1052 */
1053 private void ensureActiveMobilePolicyLocked() {
1054 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001055 if (mSuppressDefaultPolicy) return;
1056
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001057 final TelephonyManager tele = TelephonyManager.from(mContext);
1058
1059 // avoid creating policy when SIM isn't ready
1060 if (tele.getSimState() != SIM_STATE_READY) return;
1061
1062 final String subscriberId = tele.getSubscriberId();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001063 final NetworkIdentity probeIdent = new NetworkIdentity(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001064 TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001065
1066 // examine to see if any policy is defined for active mobile
1067 boolean mobileDefined = false;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001068 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001069 if (policy.template.matches(probeIdent)) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001070 mobileDefined = true;
1071 }
1072 }
1073
1074 if (!mobileDefined) {
1075 Slog.i(TAG, "no policy for active mobile network; generating default policy");
1076
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001077 // build default mobile policy, and assume usage cycle starts today
1078 final long warningBytes = mContext.getResources().getInteger(
1079 com.android.internal.R.integer.config_networkPolicyDefaultWarning)
1080 * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001081
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001082 final Time time = new Time();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001083 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001084
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001085 final int cycleDay = time.monthDay;
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001086 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001087
Jeff Sharkey4e814c32011-07-14 20:37:37 -07001088 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001089 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1090 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1091 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001092 }
1093 }
1094
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001095 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001096 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001097
1098 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001099 mNetworkPolicy.clear();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001100 mAppPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001101
1102 FileInputStream fis = null;
1103 try {
1104 fis = mPolicyFile.openRead();
1105 final XmlPullParser in = Xml.newPullParser();
1106 in.setInput(fis, null);
1107
1108 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001109 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001110 while ((type = in.next()) != END_DOCUMENT) {
1111 final String tag = in.getName();
1112 if (type == START_TAG) {
1113 if (TAG_POLICY_LIST.equals(tag)) {
1114 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001115 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1116 mRestrictBackground = readBooleanAttribute(
1117 in, ATTR_RESTRICT_BACKGROUND);
1118 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001119 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001120 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001121
1122 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1123 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1124 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001125 final String networkId;
1126 if (version >= VERSION_ADDED_NETWORK_ID) {
1127 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1128 } else {
1129 networkId = null;
1130 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001131 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001132 final String cycleTimezone;
1133 if (version >= VERSION_ADDED_TIMEZONE) {
1134 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1135 } else {
1136 cycleTimezone = Time.TIMEZONE_UTC;
1137 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001138 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1139 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001140 final long lastLimitSnooze;
1141 if (version >= VERSION_SPLIT_SNOOZE) {
1142 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1143 } else if (version >= VERSION_ADDED_SNOOZE) {
1144 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001145 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001146 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001147 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001148 final boolean metered;
1149 if (version >= VERSION_ADDED_METERED) {
1150 metered = readBooleanAttribute(in, ATTR_METERED);
1151 } else {
1152 switch (networkTemplate) {
1153 case MATCH_MOBILE_3G_LOWER:
1154 case MATCH_MOBILE_4G:
1155 case MATCH_MOBILE_ALL:
1156 metered = true;
1157 break;
1158 default:
1159 metered = false;
1160 }
1161 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001162 final long lastWarningSnooze;
1163 if (version >= VERSION_SPLIT_SNOOZE) {
1164 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1165 } else {
1166 lastWarningSnooze = SNOOZE_NEVER;
1167 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001168 final boolean inferred;
1169 if (version >= VERSION_ADDED_INFERRED) {
1170 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1171 } else {
1172 inferred = false;
1173 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001174
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001175 final NetworkTemplate template = new NetworkTemplate(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001176 networkTemplate, subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001177 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001178 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001179 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001180
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001181 } else if (TAG_UID_POLICY.equals(tag) && version < VERSION_SWITCH_APP_ID) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001182 final int uid = readIntAttribute(in, ATTR_UID);
1183 final int policy = readIntAttribute(in, ATTR_POLICY);
1184
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001185 final int appId = UserId.getAppId(uid);
1186 if (UserId.isApp(appId)) {
1187 setAppPolicyUnchecked(appId, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001188 } else {
1189 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1190 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001191 } else if (TAG_APP_POLICY.equals(tag) && version >= VERSION_SWITCH_APP_ID) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001192 final int appId = readIntAttribute(in, ATTR_APP_ID);
1193 final int policy = readIntAttribute(in, ATTR_POLICY);
1194
1195 if (UserId.isApp(appId)) {
1196 setAppPolicyUnchecked(appId, policy, false);
1197 } else {
1198 Slog.w(TAG, "unable to apply policy to appId " + appId + "; ignoring");
1199 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001200 }
1201 }
1202 }
1203
1204 } catch (FileNotFoundException e) {
1205 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001206 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001207 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001208 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001209 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001210 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001211 } finally {
1212 IoUtils.closeQuietly(fis);
1213 }
1214 }
1215
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001216 /**
1217 * Upgrade legacy background data flags, notifying listeners of one last
1218 * change to always-true.
1219 */
1220 private void upgradeLegacyBackgroundData() {
1221 mRestrictBackground = Settings.Secure.getInt(
1222 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1223
1224 // kick off one last broadcast if restricted
1225 if (mRestrictBackground) {
1226 final Intent broadcast = new Intent(
1227 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1228 mContext.sendBroadcast(broadcast);
1229 }
1230 }
1231
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001232 private void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001233 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001234
1235 FileOutputStream fos = null;
1236 try {
1237 fos = mPolicyFile.startWrite();
1238
1239 XmlSerializer out = new FastXmlSerializer();
1240 out.setOutput(fos, "utf-8");
1241 out.startDocument(null, true);
1242
1243 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001244 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001245 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001246
1247 // write all known network policies
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001248 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001249 final NetworkTemplate template = policy.template;
1250
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001251 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001252 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1253 final String subscriberId = template.getSubscriberId();
1254 if (subscriberId != null) {
1255 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001256 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001257 final String networkId = template.getNetworkId();
1258 if (networkId != null) {
1259 out.attribute(null, ATTR_NETWORK_ID, networkId);
1260 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001261 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001262 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001263 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1264 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001265 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1266 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001267 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001268 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001269 out.endTag(null, TAG_NETWORK_POLICY);
1270 }
1271
1272 // write all known uid policies
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001273 for (int i = 0; i < mAppPolicy.size(); i++) {
1274 final int appId = mAppPolicy.keyAt(i);
1275 final int policy = mAppPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001276
Jeff Sharkey497e4432011-06-14 17:27:29 -07001277 // skip writing empty policies
1278 if (policy == POLICY_NONE) continue;
1279
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001280 out.startTag(null, TAG_APP_POLICY);
1281 writeIntAttribute(out, ATTR_APP_ID, appId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001282 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001283 out.endTag(null, TAG_APP_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001284 }
1285
1286 out.endTag(null, TAG_POLICY_LIST);
1287 out.endDocument();
1288
1289 mPolicyFile.finishWrite(fos);
1290 } catch (IOException e) {
1291 if (fos != null) {
1292 mPolicyFile.failWrite(fos);
1293 }
1294 }
1295 }
1296
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001297 @Override
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001298 public void setAppPolicy(int appId, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001299 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001300
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001301 if (!UserId.isApp(appId)) {
1302 throw new IllegalArgumentException("cannot apply policy to appId " + appId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001303 }
1304
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001305 setAppPolicyUnchecked(appId, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001306 }
1307
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001308 private void setAppPolicyUnchecked(int appId, int policy, boolean persist) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001309 final int oldPolicy;
Jeff Sharkeya4620792011-05-20 15:29:23 -07001310 synchronized (mRulesLock) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001311 oldPolicy = getAppPolicy(appId);
1312 mAppPolicy.put(appId, policy);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001313
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001314 // uid policy changed, recompute rules and persist policy.
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001315 updateRulesForAppLocked(appId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001316 if (persist) {
1317 writePolicyLocked();
1318 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001319 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001320 }
1321
1322 @Override
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001323 public int getAppPolicy(int appId) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001324 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1325
Jeff Sharkeya4620792011-05-20 15:29:23 -07001326 synchronized (mRulesLock) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001327 return mAppPolicy.get(appId, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001328 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001329 }
1330
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001331 @Override
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001332 public int[] getAppsWithPolicy(int policy) {
1333 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1334
1335 int[] appIds = new int[0];
1336 synchronized (mRulesLock) {
1337 for (int i = 0; i < mAppPolicy.size(); i++) {
1338 final int appId = mAppPolicy.keyAt(i);
1339 final int appPolicy = mAppPolicy.valueAt(i);
1340 if (appPolicy == policy) {
1341 appIds = appendInt(appIds, appId);
1342 }
1343 }
1344 }
1345 return appIds;
1346 }
1347
1348 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001349 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001350 // TODO: create permission for observing network policy
1351 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1352
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001353 mListeners.register(listener);
1354
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001355 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001356 }
1357
1358 @Override
1359 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001360 // TODO: create permission for observing network policy
1361 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1362
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001363 mListeners.unregister(listener);
1364 }
1365
Jeff Sharkey1b861272011-05-22 00:34:52 -07001366 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001367 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001368 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1369
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001370 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001371 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001372 mNetworkPolicy.clear();
1373 for (NetworkPolicy policy : policies) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001374 mNetworkPolicy.put(policy.template, policy);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001375 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001376
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001377 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001378 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001379 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001380 writePolicyLocked();
1381 }
1382 }
1383
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001384 private void addNetworkPolicyLocked(NetworkPolicy policy) {
1385 mNetworkPolicy.put(policy.template, policy);
1386
1387 updateNetworkEnabledLocked();
1388 updateNetworkRulesLocked();
1389 updateNotificationsLocked();
1390 writePolicyLocked();
1391 }
1392
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001393 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001394 public NetworkPolicy[] getNetworkPolicies() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001395 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001396 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001397
1398 synchronized (mRulesLock) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001399 return mNetworkPolicy.values().toArray(new NetworkPolicy[mNetworkPolicy.size()]);
1400 }
1401 }
1402
1403 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001404 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001405 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001406 performSnooze(template, TYPE_LIMIT);
1407 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001408
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001409 private void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001410 maybeRefreshTrustedTime();
1411 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001412 synchronized (mRulesLock) {
1413 // find and snooze local policy that matches
1414 final NetworkPolicy policy = mNetworkPolicy.get(template);
1415 if (policy == null) {
1416 throw new IllegalArgumentException("unable to find policy for " + template);
1417 }
1418
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001419 switch (type) {
1420 case TYPE_WARNING:
1421 policy.lastWarningSnooze = currentTime;
1422 break;
1423 case TYPE_LIMIT:
1424 policy.lastLimitSnooze = currentTime;
1425 break;
1426 default:
1427 throw new IllegalArgumentException("unexpected type");
1428 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001429
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001430 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001431 updateNetworkRulesLocked();
1432 updateNotificationsLocked();
1433 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001434 }
1435 }
1436
1437 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001438 public void setRestrictBackground(boolean restrictBackground) {
1439 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1440
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001441 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001442 synchronized (mRulesLock) {
1443 mRestrictBackground = restrictBackground;
1444 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001445 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001446 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001447 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001448
1449 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1450 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001451 }
1452
1453 @Override
1454 public boolean getRestrictBackground() {
1455 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1456
1457 synchronized (mRulesLock) {
1458 return mRestrictBackground;
1459 }
1460 }
1461
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001462 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
1463 for (NetworkPolicy policy : mNetworkPolicy.values()) {
1464 if (policy.template.matches(ident)) {
1465 return policy;
1466 }
1467 }
1468 return null;
1469 }
1470
1471 @Override
1472 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1473 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1474
1475 // only returns usage summary, so we don't require caller to have
1476 // READ_NETWORK_USAGE_HISTORY.
1477 final long token = Binder.clearCallingIdentity();
1478 try {
1479 return getNetworkQuotaInfoUnchecked(state);
1480 } finally {
1481 Binder.restoreCallingIdentity(token);
1482 }
1483 }
1484
1485 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1486 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1487
1488 final NetworkPolicy policy;
1489 synchronized (mRulesLock) {
1490 policy = findPolicyForNetworkLocked(ident);
1491 }
1492
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001493 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001494 // missing policy means we can't derive useful quota info
1495 return null;
1496 }
1497
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001498 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001499
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001500 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001501 final long start = computeLastCycleBoundary(currentTime, policy);
1502 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001503 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001504
1505 // report soft and hard limits under policy
1506 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1507 : NetworkQuotaInfo.NO_LIMIT;
1508 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1509 : NetworkQuotaInfo.NO_LIMIT;
1510
1511 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1512 }
1513
Jeff Sharkey46645002011-07-27 21:11:21 -07001514 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001515 public boolean isNetworkMetered(NetworkState state) {
1516 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1517
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001518 // roaming networks are always considered metered
1519 if (ident.getRoaming()) {
1520 return true;
1521 }
1522
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001523 final NetworkPolicy policy;
1524 synchronized (mRulesLock) {
1525 policy = findPolicyForNetworkLocked(ident);
1526 }
1527
1528 if (policy != null) {
1529 return policy.metered;
1530 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001531 final int type = state.networkInfo.getType();
1532 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1533 return true;
1534 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001535 return false;
1536 }
1537 }
1538
1539 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001540 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001541 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001542
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001543 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1544
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001545 final HashSet<String> argSet = new HashSet<String>();
1546 for (String arg : args) {
1547 argSet.add(arg);
1548 }
1549
Jeff Sharkey1b861272011-05-22 00:34:52 -07001550 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001551 if (argSet.contains("--unsnooze")) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001552 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001553 policy.clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001554 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001555
1556 updateNetworkEnabledLocked();
1557 updateNetworkRulesLocked();
1558 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001559 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001560
1561 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001562 return;
1563 }
1564
Jeff Sharkey46645002011-07-27 21:11:21 -07001565 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001566 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001567 fout.increaseIndent();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001568 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001569 fout.println(policy.toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001570 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001571 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001572
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001573 fout.println("Policy for apps:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001574 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001575 int size = mAppPolicy.size();
1576 for (int i = 0; i < size; i++) {
1577 final int appId = mAppPolicy.keyAt(i);
1578 final int policy = mAppPolicy.valueAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001579 fout.print("appId=");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001580 fout.print(appId);
1581 fout.print(" policy=");
1582 dumpPolicy(fout, policy);
1583 fout.println();
1584 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001585 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001586
1587 final SparseBooleanArray knownUids = new SparseBooleanArray();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001588 collectKeys(mUidForeground, knownUids);
1589 collectKeys(mUidRules, knownUids);
1590
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001591 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001592 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001593 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001594 for (int i = 0; i < size; i++) {
1595 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001596 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001597 fout.print(uid);
1598
Jeff Sharkey1b861272011-05-22 00:34:52 -07001599 fout.print(" foreground=");
1600 final int foregroundIndex = mUidPidForeground.indexOfKey(uid);
1601 if (foregroundIndex < 0) {
1602 fout.print("UNKNOWN");
1603 } else {
1604 dumpSparseBooleanArray(fout, mUidPidForeground.valueAt(foregroundIndex));
1605 }
1606
1607 fout.print(" rules=");
1608 final int rulesIndex = mUidRules.indexOfKey(uid);
1609 if (rulesIndex < 0) {
1610 fout.print("UNKNOWN");
1611 } else {
1612 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1613 }
1614
1615 fout.println();
1616 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001617 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001618 }
1619 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001620
1621 @Override
1622 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001623 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1624
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001625 synchronized (mRulesLock) {
1626 // only really in foreground when screen is also on
1627 return mUidForeground.get(uid, false) && mScreenOn;
1628 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001629 }
1630
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001631 /**
1632 * Foreground for PID changed; recompute foreground at UID level. If
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001633 * changed, will trigger {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001634 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001635 private void computeUidForegroundLocked(int uid) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001636 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1637
1638 // current pid is dropping foreground; examine other pids
1639 boolean uidForeground = false;
1640 final int size = pidForeground.size();
1641 for (int i = 0; i < size; i++) {
1642 if (pidForeground.valueAt(i)) {
1643 uidForeground = true;
1644 break;
1645 }
1646 }
1647
1648 final boolean oldUidForeground = mUidForeground.get(uid, false);
1649 if (oldUidForeground != uidForeground) {
1650 // foreground changed, push updated rules
1651 mUidForeground.put(uid, uidForeground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001652 updateRulesForUidLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001653 }
1654 }
1655
Jeff Sharkeya4620792011-05-20 15:29:23 -07001656 private void updateScreenOn() {
1657 synchronized (mRulesLock) {
1658 try {
1659 mScreenOn = mPowerManager.isScreenOn();
1660 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001661 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07001662 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001663 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001664 }
1665 }
1666
1667 /**
1668 * Update rules that might be changed by {@link #mScreenOn} value.
1669 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001670 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07001671 // only update rules for anyone with foreground activities
1672 final int size = mUidForeground.size();
1673 for (int i = 0; i < size; i++) {
1674 if (mUidForeground.valueAt(i)) {
1675 final int uid = mUidForeground.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001676 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001677 }
1678 }
1679 }
1680
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001681 /**
Jeff Sharkey46645002011-07-27 21:11:21 -07001682 * Update rules that might be changed by {@link #mRestrictBackground} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001683 */
Jeff Sharkey46645002011-07-27 21:11:21 -07001684 private void updateRulesForRestrictBackgroundLocked() {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001685 // update rules for all installed applications
1686 final PackageManager pm = mContext.getPackageManager();
1687 final List<ApplicationInfo> apps = pm.getInstalledApplications(0);
1688 for (ApplicationInfo app : apps) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001689 final int appId = UserId.getAppId(app.uid);
1690 updateRulesForAppLocked(appId);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001691 }
1692
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001693 // limit data usage for some internal system services
1694 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
1695 updateRulesForUidLocked(android.os.Process.DRM_UID);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001696 }
1697
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001698 private void updateRulesForAppLocked(int appId) {
1699 for (UserInfo user : mContext.getPackageManager().getUsers()) {
1700 final int uid = UserId.getUid(user.id, appId);
1701 updateRulesForUidLocked(uid);
1702 }
1703 }
1704
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001705 private static boolean isUidValidForRules(int uid) {
1706 // allow rules on specific system services, and any apps
1707 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
1708 || UserId.isApp(uid)) {
1709 return true;
1710 }
1711
1712 return false;
1713 }
1714
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001715 private void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001716 if (!isUidValidForRules(uid)) return;
1717
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001718 final int appId = UserId.getAppId(uid);
1719 final int appPolicy = getAppPolicy(appId);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001720 final boolean uidForeground = isUidForeground(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001721
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001722 // derive active rules based on policy and active state
1723 int uidRules = RULE_ALLOW_ALL;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001724 if (!uidForeground && (appPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001725 // uid in background, and policy says to block metered data
1726 uidRules = RULE_REJECT_METERED;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001727 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001728 if (!uidForeground && mRestrictBackground) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001729 // uid in background, and global background disabled
1730 uidRules = RULE_REJECT_METERED;
1731 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001732
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001733 // TODO: only dispatch when rules actually change
1734
Jeff Sharkey350083e2011-06-29 10:45:16 -07001735 if (uidRules == RULE_ALLOW_ALL) {
1736 mUidRules.delete(uid);
1737 } else {
1738 mUidRules.put(uid, uidRules);
1739 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001740
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001741 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001742 setUidNetworkRules(uid, rejectMetered);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001743
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001744 // dispatch changed rule to existing listeners
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001745 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001746
1747 try {
1748 // adjust stats accounting based on foreground status
1749 mNetworkStats.setUidForeground(uid, uidForeground);
1750 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001751 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001752 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001753 }
1754
1755 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001756 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001757 public boolean handleMessage(Message msg) {
1758 switch (msg.what) {
1759 case MSG_RULES_CHANGED: {
1760 final int uid = msg.arg1;
1761 final int uidRules = msg.arg2;
1762 final int length = mListeners.beginBroadcast();
1763 for (int i = 0; i < length; i++) {
1764 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1765 if (listener != null) {
1766 try {
1767 listener.onUidRulesChanged(uid, uidRules);
1768 } catch (RemoteException e) {
1769 }
1770 }
1771 }
1772 mListeners.finishBroadcast();
1773 return true;
1774 }
1775 case MSG_METERED_IFACES_CHANGED: {
1776 final String[] meteredIfaces = (String[]) msg.obj;
1777 final int length = mListeners.beginBroadcast();
1778 for (int i = 0; i < length; i++) {
1779 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1780 if (listener != null) {
1781 try {
1782 listener.onMeteredIfacesChanged(meteredIfaces);
1783 } catch (RemoteException e) {
1784 }
1785 }
1786 }
1787 mListeners.finishBroadcast();
1788 return true;
1789 }
Jeff Sharkey6f7af032011-11-01 18:25:15 -07001790 case MSG_FOREGROUND_ACTIVITIES_CHANGED: {
1791 final int pid = msg.arg1;
1792 final int uid = msg.arg2;
1793 final boolean foregroundActivities = (Boolean) msg.obj;
1794
1795 synchronized (mRulesLock) {
1796 // because a uid can have multiple pids running inside, we need to
1797 // remember all pid states and summarize foreground at uid level.
1798
1799 // record foreground for this specific pid
1800 SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1801 if (pidForeground == null) {
1802 pidForeground = new SparseBooleanArray(2);
1803 mUidPidForeground.put(uid, pidForeground);
1804 }
1805 pidForeground.put(pid, foregroundActivities);
1806 computeUidForegroundLocked(uid);
1807 }
1808 return true;
1809 }
1810 case MSG_PROCESS_DIED: {
1811 final int pid = msg.arg1;
1812 final int uid = msg.arg2;
1813
1814 synchronized (mRulesLock) {
1815 // clear records and recompute, when they exist
1816 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1817 if (pidForeground != null) {
1818 pidForeground.delete(pid);
1819 computeUidForegroundLocked(uid);
1820 }
1821 }
1822 return true;
1823 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001824 case MSG_LIMIT_REACHED: {
1825 final String iface = (String) msg.obj;
1826
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001827 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001828 synchronized (mRulesLock) {
1829 if (mMeteredIfaces.contains(iface)) {
1830 try {
1831 // force stats update to make sure we have
1832 // numbers that caused alert to trigger.
1833 mNetworkStats.forceUpdate();
1834 } catch (RemoteException e) {
1835 // ignored; service lives in system_server
1836 }
1837
1838 updateNetworkEnabledLocked();
1839 updateNotificationsLocked();
1840 }
1841 }
1842 return true;
1843 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001844 case MSG_RESTRICT_BACKGROUND_CHANGED: {
1845 final boolean restrictBackground = msg.arg1 != 0;
1846 final int length = mListeners.beginBroadcast();
1847 for (int i = 0; i < length; i++) {
1848 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1849 if (listener != null) {
1850 try {
1851 listener.onRestrictBackgroundChanged(restrictBackground);
1852 } catch (RemoteException e) {
1853 }
1854 }
1855 }
1856 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001857 return true;
1858 }
1859 case MSG_ADVISE_PERSIST_THRESHOLD: {
1860 final long lowestRule = (Long) msg.obj;
1861 try {
1862 // make sure stats are recorded frequently enough; we aim
1863 // for 2MB threshold for 2GB/month rules.
1864 final long persistThreshold = lowestRule / 1000;
1865 mNetworkStats.advisePersistThreshold(persistThreshold);
1866 } catch (RemoteException e) {
1867 // ignored; service lives in system_server
1868 }
1869 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001870 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001871 default: {
1872 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07001873 }
1874 }
1875 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001876 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001877
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001878 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001879 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001880 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001881 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001882 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001883 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001884 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001885 }
1886 }
1887
1888 private void removeInterfaceQuota(String iface) {
1889 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001890 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001891 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001892 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001893 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001894 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001895 }
1896 }
1897
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001898 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1899 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001900 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001901 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001902 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001903 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001904 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001905 }
1906 }
1907
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001908 /**
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001909 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001910 */
1911 private void setPolicyDataEnable(int networkType, boolean enabled) {
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001912 try {
1913 mConnManager.setPolicyDataEnable(networkType, enabled);
1914 } catch (RemoteException e) {
1915 // ignored; service lives in system_server
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001916 }
1917 }
1918
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001919 private long getTotalBytes(NetworkTemplate template, long start, long end) {
1920 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07001921 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001922 } catch (RuntimeException e) {
1923 Slog.w(TAG, "problem reading network stats: " + e);
1924 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001925 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001926 // ignored; service lives in system_server
1927 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001928 }
1929 }
1930
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07001931 private boolean isBandwidthControlEnabled() {
1932 final long token = Binder.clearCallingIdentity();
1933 try {
1934 return mNetworkManager.isBandwidthControlEnabled();
1935 } catch (RemoteException e) {
1936 // ignored; service lives in system_server
1937 return false;
1938 } finally {
1939 Binder.restoreCallingIdentity(token);
1940 }
1941 }
1942
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001943 /**
1944 * Try refreshing {@link #mTime} when stale.
1945 */
1946 private void maybeRefreshTrustedTime() {
1947 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001948 mTime.forceRefresh();
1949 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001950 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001951
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001952 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001953 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
1954 }
1955
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001956 private static Intent buildAllowBackgroundDataIntent() {
1957 return new Intent(ACTION_ALLOW_BACKGROUND);
1958 }
1959
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001960 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
1961 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
1962 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
1963 return intent;
1964 }
1965
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001966 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
1967 final Intent intent = new Intent();
1968 intent.setComponent(new ComponentName(
1969 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
1970 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1971 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
1972 return intent;
1973 }
1974
1975 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
1976 final Intent intent = new Intent();
1977 intent.setComponent(new ComponentName(
1978 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
1979 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1980 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
1981 return intent;
1982 }
1983
Jeff Sharkey163e6442011-10-31 16:37:52 -07001984 // @VisibleForTesting
1985 public void addIdleHandler(IdleHandler handler) {
1986 mHandler.getLooper().getQueue().addIdleHandler(handler);
1987 }
1988
Jeff Sharkey1b861272011-05-22 00:34:52 -07001989 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
1990 final int size = source.size();
1991 for (int i = 0; i < size; i++) {
1992 target.put(source.keyAt(i), true);
1993 }
1994 }
1995
1996 private static void collectKeys(SparseBooleanArray source, SparseBooleanArray target) {
1997 final int size = source.size();
1998 for (int i = 0; i < size; i++) {
1999 target.put(source.keyAt(i), true);
2000 }
2001 }
2002
2003 private static void dumpSparseBooleanArray(PrintWriter fout, SparseBooleanArray value) {
2004 fout.print("[");
2005 final int size = value.size();
2006 for (int i = 0; i < size; i++) {
2007 fout.print(value.keyAt(i) + "=" + value.valueAt(i));
2008 if (i < size - 1) fout.print(",");
2009 }
2010 fout.print("]");
2011 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002012
Jeff Sharkey46645002011-07-27 21:11:21 -07002013 public static class XmlUtils {
2014 public static int readIntAttribute(XmlPullParser in, String name) throws IOException {
2015 final String value = in.getAttributeValue(null, name);
2016 try {
2017 return Integer.parseInt(value);
2018 } catch (NumberFormatException e) {
2019 throw new ProtocolException("problem parsing " + name + "=" + value + " as int");
2020 }
2021 }
2022
2023 public static void writeIntAttribute(XmlSerializer out, String name, int value)
2024 throws IOException {
2025 out.attribute(null, name, Integer.toString(value));
2026 }
2027
2028 public static long readLongAttribute(XmlPullParser in, String name) throws IOException {
2029 final String value = in.getAttributeValue(null, name);
2030 try {
2031 return Long.parseLong(value);
2032 } catch (NumberFormatException e) {
2033 throw new ProtocolException("problem parsing " + name + "=" + value + " as long");
2034 }
2035 }
2036
2037 public static void writeLongAttribute(XmlSerializer out, String name, long value)
2038 throws IOException {
2039 out.attribute(null, name, Long.toString(value));
2040 }
2041
2042 public static boolean readBooleanAttribute(XmlPullParser in, String name) {
2043 final String value = in.getAttributeValue(null, name);
2044 return Boolean.parseBoolean(value);
2045 }
2046
2047 public static void writeBooleanAttribute(XmlSerializer out, String name, boolean value)
2048 throws IOException {
2049 out.attribute(null, name, Boolean.toString(value));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002050 }
2051 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002052}