blob: f873b6ccce7a4d46f37794f20a16bfa583b81da1 [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";
169 private static final boolean LOGD = true;
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 Sharkey4414cea2011-06-24 17:05:24 -0700227
Jeff Sharkey75279902011-05-24 18:39:45 -0700228 private final Context mContext;
229 private final IActivityManager mActivityManager;
230 private final IPowerManager mPowerManager;
231 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700232 private final INetworkManagementService mNetworkManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700233 private final TrustedTime mTime;
234
235 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700236 private INotificationManager mNotifManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700237
Jeff Sharkey75279902011-05-24 18:39:45 -0700238 private final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700239
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700240 private volatile boolean mScreenOn;
241 private volatile boolean mRestrictBackground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700242
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700243 private final boolean mSuppressDefaultPolicy;
244
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700245 /** Defined network policies. */
246 private HashMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = Maps.newHashMap();
247 /** Currently active network rules for ifaces. */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700248 private HashMap<NetworkPolicy, String[]> mNetworkRules = Maps.newHashMap();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700249
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700250 /** Defined app policies. */
251 private SparseIntArray mAppPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700252 /** Currently derived rules for each UID. */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700253 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700254
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700255 /** Set of ifaces that are metered. */
256 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700257 /** Set of over-limit templates that have been notified. */
258 private HashSet<NetworkTemplate> mOverLimitNotified = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700259
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700260 /** Set of currently active {@link Notification} tags. */
261 private HashSet<String> mActiveNotifs = Sets.newHashSet();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700262
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700263 /** Foreground at both UID and PID granularity. */
Jeff Sharkeya4620792011-05-20 15:29:23 -0700264 private SparseBooleanArray mUidForeground = new SparseBooleanArray();
265 private SparseArray<SparseBooleanArray> mUidPidForeground = new SparseArray<
266 SparseBooleanArray>();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700267
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700268 private final RemoteCallbackList<INetworkPolicyListener> mListeners = new RemoteCallbackList<
269 INetworkPolicyListener>();
270
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700271 private final HandlerThread mHandlerThread;
272 private final Handler mHandler;
273
274 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700275
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700276 // TODO: keep whitelist of system-critical services that should never have
277 // rules enforced, such as system, phone, and radio UIDs.
278
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700279 // TODO: migrate notifications to SystemUI
280
Jeff Sharkey75279902011-05-24 18:39:45 -0700281 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700282 IPowerManager powerManager, INetworkStatsService networkStats,
283 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700284 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700285 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700286 }
287
288 private static File getSystemDir() {
289 return new File(Environment.getDataDirectory(), "system");
290 }
291
292 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700293 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700294 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
295 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700296 mContext = checkNotNull(context, "missing context");
297 mActivityManager = checkNotNull(activityManager, "missing activityManager");
298 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700299 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700300 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700301 mTime = checkNotNull(time, "missing TrustedTime");
302
303 mHandlerThread = new HandlerThread(TAG);
304 mHandlerThread.start();
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700305 mHandler = new Handler(mHandlerThread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700306
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700307 mSuppressDefaultPolicy = suppressDefaultPolicy;
308
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700309 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
310 }
311
312 public void bindConnectivityManager(IConnectivityManager connManager) {
313 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700314 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700315
Jeff Sharkey497e4432011-06-14 17:27:29 -0700316 public void bindNotificationManager(INotificationManager notifManager) {
317 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
318 }
319
Jeff Sharkeya4620792011-05-20 15:29:23 -0700320 public void systemReady() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700321 synchronized (mRulesLock) {
322 // read policy from disk
323 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700324
325 if (mRestrictBackground) {
326 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700327 updateNotificationsLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700328 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700329 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700330
Jeff Sharkeya4620792011-05-20 15:29:23 -0700331 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700332
Jeff Sharkeya4620792011-05-20 15:29:23 -0700333 try {
334 mActivityManager.registerProcessObserver(mProcessObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700335 mNetworkManager.registerObserver(mAlertObserver);
336 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700337 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700338 }
339
Jeff Sharkeya4620792011-05-20 15:29:23 -0700340 // TODO: traverse existing processes to know foreground state, or have
341 // activitymanager dispatch current state when new observer attached.
342
343 final IntentFilter screenFilter = new IntentFilter();
344 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
345 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700346 mContext.registerReceiver(mScreenReceiver, screenFilter, null, mHandler);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700347
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700348 // watch for network interfaces to be claimed
Jeff Sharkey961e3042011-08-29 16:02:57 -0700349 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION_IMMEDIATE);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700350 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
351
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700352 // listen for package/uid changes to update policy
353 final IntentFilter packageFilter = new IntentFilter();
354 packageFilter.addAction(ACTION_PACKAGE_ADDED);
355 packageFilter.addAction(ACTION_UID_REMOVED);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700356 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700357
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700358 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700359 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
360 mContext.registerReceiver(
361 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
362
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700363 // listen for restrict background changes from notifications
364 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
365 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
366
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800367 // listen for snooze warning from notifications
368 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
369 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
370 MANAGE_NETWORK_POLICY, mHandler);
371
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700372 // listen for configured wifi networks to be removed
373 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
374 mContext.registerReceiver(
375 mWifiConfigReceiver, wifiConfigFilter, CONNECTIVITY_INTERNAL, mHandler);
376
377 // listen for wifi state changes to catch metered hint
378 final IntentFilter wifiStateFilter = new IntentFilter(
379 WifiManager.NETWORK_STATE_CHANGED_ACTION);
380 mContext.registerReceiver(
381 mWifiStateReceiver, wifiStateFilter, CONNECTIVITY_INTERNAL, mHandler);
382
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700383 }
384
Jeff Sharkeya4620792011-05-20 15:29:23 -0700385 private IProcessObserver mProcessObserver = new IProcessObserver.Stub() {
386 @Override
387 public void onForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700388 mHandler.obtainMessage(MSG_FOREGROUND_ACTIVITIES_CHANGED,
389 pid, uid, foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700390 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700391
392 @Override
393 public void onProcessDied(int pid, int uid) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700394 mHandler.obtainMessage(MSG_PROCESS_DIED, pid, uid).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700395 }
396 };
397
398 private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
399 @Override
400 public void onReceive(Context context, Intent intent) {
401 synchronized (mRulesLock) {
402 // screen-related broadcasts are protected by system, no need
403 // for permissions check.
404 updateScreenOn();
405 }
406 }
407 };
408
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700409 private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700410 @Override
411 public void onReceive(Context context, Intent intent) {
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700412 // on background handler thread, and PACKAGE_ADDED and UID_REMOVED
413 // are protected broadcasts.
414
415 final String action = intent.getAction();
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700416 final int uid = intent.getIntExtra(EXTRA_UID, 0);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700417 final int appId = UserId.getAppId(uid);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700418 synchronized (mRulesLock) {
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700419 if (ACTION_PACKAGE_ADDED.equals(action)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700420 // NOTE: PACKAGE_ADDED is currently only sent once, and is
421 // not broadcast when users are added.
422
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700423 // update rules for UID, since it might be subject to
424 // global background data policy.
425 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700426 updateRulesForAppLocked(appId);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700427
428 } else if (ACTION_UID_REMOVED.equals(action)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700429 // NOTE: UID_REMOVED is currently only sent once, and is not
430 // broadcast when users are removed.
431
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700432 // remove any policy and update rules to clean up.
433 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700434
435 mAppPolicy.delete(appId);
436 updateRulesForAppLocked(appId);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700437 writePolicyLocked();
438 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700439 }
440 }
441 };
442
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700443 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700444 * Receiver that watches for {@link INetworkStatsService} updates, which we
445 * use to check against {@link NetworkPolicy#warningBytes}.
446 */
447 private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
448 @Override
449 public void onReceive(Context context, Intent intent) {
450 // on background handler thread, and verified
451 // READ_NETWORK_USAGE_HISTORY permission above.
452
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800453 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700454 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700455 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700456 updateNotificationsLocked();
457 }
458 }
459 };
460
461 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700462 * Receiver that watches for {@link Notification} control of
463 * {@link #mRestrictBackground}.
464 */
465 private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
466 @Override
467 public void onReceive(Context context, Intent intent) {
468 // on background handler thread, and verified MANAGE_NETWORK_POLICY
469 // permission above.
470
471 setRestrictBackground(false);
472 }
473 };
474
475 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800476 * Receiver that watches for {@link Notification} control of
477 * {@link NetworkPolicy#lastWarningSnooze}.
478 */
479 private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
480 @Override
481 public void onReceive(Context context, Intent intent) {
482 // on background handler thread, and verified MANAGE_NETWORK_POLICY
483 // permission above.
484
485 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
486 performSnooze(template, TYPE_WARNING);
487 }
488 };
489
490 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700491 * Receiver that watches for {@link WifiConfiguration} to be changed.
492 */
493 private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
494 @Override
495 public void onReceive(Context context, Intent intent) {
496 // on background handler thread, and verified CONNECTIVITY_INTERNAL
497 // permission above.
498
499 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
500 if (reason == CHANGE_REASON_REMOVED) {
501 final WifiConfiguration config = intent.getParcelableExtra(
502 EXTRA_WIFI_CONFIGURATION);
503 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(
504 removeDoubleQuotes(config.SSID));
505 synchronized (mRulesLock) {
506 if (mNetworkPolicy.containsKey(template)) {
507 mNetworkPolicy.remove(template);
508 writePolicyLocked();
509 }
510 }
511 }
512 }
513 };
514
515 /**
516 * Receiver that watches {@link WifiInfo} state changes to infer metered
517 * state. Ignores hints when policy is user-defined.
518 */
519 private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
520 @Override
521 public void onReceive(Context context, Intent intent) {
522 // on background handler thread, and verified CONNECTIVITY_INTERNAL
523 // permission above.
524
525 // ignore when not connected
526 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
527 if (!netInfo.isConnected()) return;
528
529 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
530 final boolean meteredHint = info.getMeteredHint();
531
532 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(
533 removeDoubleQuotes(info.getSSID()));
534 synchronized (mRulesLock) {
535 NetworkPolicy policy = mNetworkPolicy.get(template);
536 if (policy == null && meteredHint) {
537 // policy doesn't exist, and AP is hinting that it's
538 // metered: create an inferred policy.
539 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
540 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
541 meteredHint, true);
542 addNetworkPolicyLocked(policy);
543
544 } else if (policy != null && policy.inferred) {
545 // policy exists, and was inferred: update its current
546 // metered state.
547 policy.metered = meteredHint;
548
549 // since this is inferred for each wifi session, just update
550 // rules without persisting.
551 updateNetworkRulesLocked();
552 }
553 }
554 }
555 };
556
557 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700558 * Observer that watches for {@link INetworkManagementService} alerts.
559 */
560 private INetworkManagementEventObserver mAlertObserver = new NetworkAlertObserver() {
561 @Override
562 public void limitReached(String limitName, String iface) {
563 // only someone like NMS should be calling us
564 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
565
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800566 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
567 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700568 }
569 }
570 };
571
572 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700573 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
574 * to show visible notifications as needed.
575 */
576 private void updateNotificationsLocked() {
577 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
578
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700579 // keep track of previously active notifications
580 final HashSet<String> beforeNotifs = Sets.newHashSet();
581 beforeNotifs.addAll(mActiveNotifs);
582 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700583
584 // TODO: when switching to kernel notifications, compute next future
585 // cycle boundary to recompute notifications.
586
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700587 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800588 final long currentTime = currentTimeMillis();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700589 for (NetworkPolicy policy : mNetworkPolicy.values()) {
590 // ignore policies that aren't relevant to user
591 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700592 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700593
Jeff Sharkey497e4432011-06-14 17:27:29 -0700594 final long start = computeLastCycleBoundary(currentTime, policy);
595 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700596 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700597
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700598 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800599 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700600 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
601 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700602 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
603 notifyOverLimitLocked(policy.template);
604 }
605
Jeff Sharkey497e4432011-06-14 17:27:29 -0700606 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700607 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700608
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800609 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700610 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700611 }
612 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700613 }
614
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700615 // ongoing notification when restricting background data
616 if (mRestrictBackground) {
617 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700618 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700619
620 // cancel stale notifications that we didn't renew above
621 for (String tag : beforeNotifs) {
622 if (!mActiveNotifs.contains(tag)) {
623 cancelNotification(tag);
624 }
625 }
626 }
627
628 /**
629 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700630 * current device state, such as when
631 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
632 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700633 */
634 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700635 final TelephonyManager tele = TelephonyManager.from(mContext);
636
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700637 switch (template.getMatchRule()) {
638 case MATCH_MOBILE_3G_LOWER:
639 case MATCH_MOBILE_4G:
640 case MATCH_MOBILE_ALL:
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700641 // mobile templates are relevant when SIM is ready and
642 // subscriberId matches.
643 if (tele.getSimState() == SIM_STATE_READY) {
644 return Objects.equal(tele.getSubscriberId(), template.getSubscriberId());
645 } else {
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700646 return false;
647 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700648 }
649 return true;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700650 }
651
652 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700653 * Notify that given {@link NetworkTemplate} is over
654 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
655 */
656 private void notifyOverLimitLocked(NetworkTemplate template) {
657 if (!mOverLimitNotified.contains(template)) {
658 mContext.startActivity(buildNetworkOverLimitIntent(template));
659 mOverLimitNotified.add(template);
660 }
661 }
662
663 private void notifyUnderLimitLocked(NetworkTemplate template) {
664 mOverLimitNotified.remove(template);
665 }
666
667 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700668 * Build unique tag that identifies an active {@link NetworkPolicy}
669 * notification of a specific type, like {@link #TYPE_LIMIT}.
670 */
671 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700672 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700673 }
674
675 /**
676 * Show notification for combined {@link NetworkPolicy} and specific type,
677 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
678 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700679 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700680 final String tag = buildNotificationTag(policy, type);
681 final Notification.Builder builder = new Notification.Builder(mContext);
682 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800683 builder.setWhen(0L);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700684
685 final Resources res = mContext.getResources();
686 switch (type) {
687 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700688 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700689 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700690
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700691 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700692 builder.setTicker(title);
693 builder.setContentTitle(title);
694 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700695
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800696 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
697 builder.setDeleteIntent(PendingIntent.getBroadcast(
698 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
699
700 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700701 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800702 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
703
Jeff Sharkey497e4432011-06-14 17:27:29 -0700704 break;
705 }
706 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700707 final CharSequence body = res.getText(R.string.data_usage_limit_body);
708
709 final CharSequence title;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700710 switch (policy.template.getMatchRule()) {
711 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700712 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700713 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700714 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700715 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700716 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700717 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700718 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700719 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700720 case MATCH_WIFI:
721 title = res.getText(R.string.data_usage_wifi_limit_title);
722 break;
723 default:
724 title = null;
725 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700726 }
727
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800728 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700729 builder.setSmallIcon(R.drawable.stat_notify_disabled);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700730 builder.setTicker(title);
731 builder.setContentTitle(title);
732 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700733
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700734 final Intent intent = buildNetworkOverLimitIntent(policy.template);
735 builder.setContentIntent(PendingIntent.getActivity(
736 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
737 break;
738 }
739 case TYPE_LIMIT_SNOOZED: {
740 final long overBytes = totalBytes - policy.limitBytes;
741 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
742 Formatter.formatFileSize(mContext, overBytes));
743
744 final CharSequence title;
745 switch (policy.template.getMatchRule()) {
746 case MATCH_MOBILE_3G_LOWER:
747 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
748 break;
749 case MATCH_MOBILE_4G:
750 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
751 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700752 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700753 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
754 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700755 case MATCH_WIFI:
756 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
757 break;
758 default:
759 title = null;
760 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700761 }
762
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800763 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700764 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700765 builder.setTicker(title);
766 builder.setContentTitle(title);
767 builder.setContentText(body);
768
769 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700770 builder.setContentIntent(PendingIntent.getActivity(
771 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700772 break;
773 }
774 }
775
776 // TODO: move to NotificationManager once we can mock it
777 try {
778 final String packageName = mContext.getPackageName();
779 final int[] idReceived = new int[1];
780 mNotifManager.enqueueNotificationWithTag(
781 packageName, tag, 0x0, builder.getNotification(), idReceived);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700782 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700783 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700784 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700785 }
786 }
787
788 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700789 * Show ongoing notification to reflect that {@link #mRestrictBackground}
790 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700791 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700792 private void enqueueRestrictedNotification(String tag) {
793 final Resources res = mContext.getResources();
794 final Notification.Builder builder = new Notification.Builder(mContext);
795
796 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
797 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
798
799 builder.setOnlyAlertOnce(true);
800 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700801 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700802 builder.setTicker(title);
803 builder.setContentTitle(title);
804 builder.setContentText(body);
805
806 final Intent intent = buildAllowBackgroundDataIntent();
807 builder.setContentIntent(
808 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700809
810 // TODO: move to NotificationManager once we can mock it
811 try {
812 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700813 final int[] idReceived = new int[1];
814 mNotifManager.enqueueNotificationWithTag(packageName, tag,
815 0x0, builder.getNotification(), idReceived);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700816 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700817 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700818 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700819 }
820 }
821
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700822 private void cancelNotification(String tag) {
823 // TODO: move to NotificationManager once we can mock it
824 try {
825 final String packageName = mContext.getPackageName();
826 mNotifManager.cancelNotificationWithTag(
827 packageName, tag, 0x0);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700828 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700829 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700830 }
831 }
832
833 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700834 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700835 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700836 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700837 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700838 @Override
839 public void onReceive(Context context, Intent intent) {
840 // on background handler thread, and verified CONNECTIVITY_INTERNAL
841 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800842
843 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700844 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700845 ensureActiveMobilePolicyLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700846 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700847 updateNetworkRulesLocked();
848 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700849 }
850 }
851 };
852
853 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700854 * Proactively control network data connections when they exceed
855 * {@link NetworkPolicy#limitBytes}.
856 */
857 private void updateNetworkEnabledLocked() {
858 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
859
860 // TODO: reset any policy-disabled networks when any policy is removed
861 // completely, which is currently rare case.
862
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800863 final long currentTime = currentTimeMillis();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700864 for (NetworkPolicy policy : mNetworkPolicy.values()) {
865 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700866 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700867 setNetworkTemplateEnabled(policy.template, true);
868 continue;
869 }
870
871 final long start = computeLastCycleBoundary(currentTime, policy);
872 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700873 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700874
875 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800876 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
877 && policy.lastLimitSnooze < start;
878 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700879
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800880 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700881 }
882 }
883
884 /**
885 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}
886 * for the given {@link NetworkTemplate}.
887 */
888 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700889 final TelephonyManager tele = TelephonyManager.from(mContext);
890
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700891 switch (template.getMatchRule()) {
892 case MATCH_MOBILE_3G_LOWER:
893 case MATCH_MOBILE_4G:
894 case MATCH_MOBILE_ALL:
895 // TODO: offer more granular control over radio states once
896 // 4965893 is available.
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700897 if (tele.getSimState() == SIM_STATE_READY
898 && Objects.equal(tele.getSubscriberId(), template.getSubscriberId())) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700899 setPolicyDataEnable(TYPE_MOBILE, enabled);
900 setPolicyDataEnable(TYPE_WIMAX, enabled);
901 }
902 break;
903 case MATCH_WIFI:
904 setPolicyDataEnable(TYPE_WIFI, enabled);
905 break;
906 case MATCH_ETHERNET:
907 setPolicyDataEnable(TYPE_ETHERNET, enabled);
908 break;
909 default:
910 throw new IllegalArgumentException("unexpected template");
911 }
912 }
913
914 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700915 * Examine all connected {@link NetworkState}, looking for
916 * {@link NetworkPolicy} that need to be enforced. When matches found, set
917 * remaining quota based on usage cycle and historical stats.
918 */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700919 private void updateNetworkRulesLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700920 if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700921
922 final NetworkState[] states;
923 try {
924 states = mConnManager.getAllNetworkState();
925 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700926 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700927 return;
928 }
929
930 // first, derive identity for all connected networks, which can be used
931 // to match against templates.
932 final HashMap<NetworkIdentity, String> networks = Maps.newHashMap();
933 for (NetworkState state : states) {
934 // stash identity and iface away for later use
935 if (state.networkInfo.isConnected()) {
936 final String iface = state.linkProperties.getInterfaceName();
937 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
938 networks.put(ident, iface);
939 }
940 }
941
942 // build list of rules and ifaces to enforce them against
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700943 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700944 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700945 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700946
947 // collect all active ifaces that match this template
948 ifaceList.clear();
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700949 for (Map.Entry<NetworkIdentity, String> entry : networks.entrySet()) {
950 final NetworkIdentity ident = entry.getKey();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700951 if (policy.template.matches(ident)) {
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700952 final String iface = entry.getValue();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700953 ifaceList.add(iface);
954 }
955 }
956
957 if (ifaceList.size() > 0) {
958 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700959 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700960 }
961 }
962
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700963 final HashSet<String> newMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700964
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700965 // apply each policy that we found ifaces for; compute remaining data
966 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800967 final long currentTime = currentTimeMillis();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700968 for (NetworkPolicy policy : mNetworkRules.keySet()) {
969 final String[] ifaces = mNetworkRules.get(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700970
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700971 final long start;
972 final long totalBytes;
973 if (policy.hasCycle()) {
974 start = computeLastCycleBoundary(currentTime, policy);
975 totalBytes = getTotalBytes(policy.template, start, currentTime);
976 } else {
977 start = Long.MAX_VALUE;
978 totalBytes = 0;
979 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700980
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700981 if (LOGD) {
982 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700983 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700984 }
985
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700986 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800987 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700988 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800989 if (!hasLimit) {
990 // metered network, but no policy limit; we still need to
991 // restrict apps, so push really high quota.
992 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800993 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700994 // snoozing past quota, but we still need to restrict apps,
995 // so push really high quota.
996 quotaBytes = Long.MAX_VALUE;
997 } else {
998 // remaining "quota" bytes are based on total usage in
999 // current cycle. kernel doesn't like 0-byte rules, so we
1000 // set 1-byte quota and disable the radio later.
1001 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1002 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001003
1004 if (ifaces.length > 1) {
1005 // TODO: switch to shared quota once NMS supports
1006 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001007 }
1008
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001009 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001010 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001011 setInterfaceQuota(iface, quotaBytes);
1012 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001013 }
1014 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001015 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001016
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001017 // remove quota on any trailing interfaces
1018 for (String iface : mMeteredIfaces) {
1019 if (!newMeteredIfaces.contains(iface)) {
1020 removeInterfaceQuota(iface);
1021 }
1022 }
1023 mMeteredIfaces = newMeteredIfaces;
1024
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001025 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001026 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001027 }
1028
1029 /**
1030 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1031 * have at least a default mobile policy defined.
1032 */
1033 private void ensureActiveMobilePolicyLocked() {
1034 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001035 if (mSuppressDefaultPolicy) return;
1036
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001037 final TelephonyManager tele = TelephonyManager.from(mContext);
1038
1039 // avoid creating policy when SIM isn't ready
1040 if (tele.getSimState() != SIM_STATE_READY) return;
1041
1042 final String subscriberId = tele.getSubscriberId();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001043 final NetworkIdentity probeIdent = new NetworkIdentity(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001044 TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001045
1046 // examine to see if any policy is defined for active mobile
1047 boolean mobileDefined = false;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001048 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001049 if (policy.template.matches(probeIdent)) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001050 mobileDefined = true;
1051 }
1052 }
1053
1054 if (!mobileDefined) {
1055 Slog.i(TAG, "no policy for active mobile network; generating default policy");
1056
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001057 // build default mobile policy, and assume usage cycle starts today
1058 final long warningBytes = mContext.getResources().getInteger(
1059 com.android.internal.R.integer.config_networkPolicyDefaultWarning)
1060 * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001061
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001062 final Time time = new Time();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001063 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001064
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001065 final int cycleDay = time.monthDay;
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001066 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001067
Jeff Sharkey4e814c32011-07-14 20:37:37 -07001068 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001069 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1070 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1071 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001072 }
1073 }
1074
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001075 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001076 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001077
1078 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001079 mNetworkPolicy.clear();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001080 mAppPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001081
1082 FileInputStream fis = null;
1083 try {
1084 fis = mPolicyFile.openRead();
1085 final XmlPullParser in = Xml.newPullParser();
1086 in.setInput(fis, null);
1087
1088 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001089 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001090 while ((type = in.next()) != END_DOCUMENT) {
1091 final String tag = in.getName();
1092 if (type == START_TAG) {
1093 if (TAG_POLICY_LIST.equals(tag)) {
1094 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001095 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1096 mRestrictBackground = readBooleanAttribute(
1097 in, ATTR_RESTRICT_BACKGROUND);
1098 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001099 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001100 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001101
1102 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1103 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1104 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001105 final String networkId;
1106 if (version >= VERSION_ADDED_NETWORK_ID) {
1107 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1108 } else {
1109 networkId = null;
1110 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001111 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001112 final String cycleTimezone;
1113 if (version >= VERSION_ADDED_TIMEZONE) {
1114 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1115 } else {
1116 cycleTimezone = Time.TIMEZONE_UTC;
1117 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001118 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1119 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001120 final long lastLimitSnooze;
1121 if (version >= VERSION_SPLIT_SNOOZE) {
1122 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1123 } else if (version >= VERSION_ADDED_SNOOZE) {
1124 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001125 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001126 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001127 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001128 final boolean metered;
1129 if (version >= VERSION_ADDED_METERED) {
1130 metered = readBooleanAttribute(in, ATTR_METERED);
1131 } else {
1132 switch (networkTemplate) {
1133 case MATCH_MOBILE_3G_LOWER:
1134 case MATCH_MOBILE_4G:
1135 case MATCH_MOBILE_ALL:
1136 metered = true;
1137 break;
1138 default:
1139 metered = false;
1140 }
1141 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001142 final long lastWarningSnooze;
1143 if (version >= VERSION_SPLIT_SNOOZE) {
1144 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1145 } else {
1146 lastWarningSnooze = SNOOZE_NEVER;
1147 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001148 final boolean inferred;
1149 if (version >= VERSION_ADDED_INFERRED) {
1150 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1151 } else {
1152 inferred = false;
1153 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001154
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001155 final NetworkTemplate template = new NetworkTemplate(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001156 networkTemplate, subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001157 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001158 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001159 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001160
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001161 } else if (TAG_UID_POLICY.equals(tag) && version < VERSION_SWITCH_APP_ID) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001162 final int uid = readIntAttribute(in, ATTR_UID);
1163 final int policy = readIntAttribute(in, ATTR_POLICY);
1164
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001165 final int appId = UserId.getAppId(uid);
1166 if (UserId.isApp(appId)) {
1167 setAppPolicyUnchecked(appId, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001168 } else {
1169 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1170 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001171 } else if (TAG_APP_POLICY.equals(tag) && version >= VERSION_SWITCH_APP_ID) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001172 final int appId = readIntAttribute(in, ATTR_APP_ID);
1173 final int policy = readIntAttribute(in, ATTR_POLICY);
1174
1175 if (UserId.isApp(appId)) {
1176 setAppPolicyUnchecked(appId, policy, false);
1177 } else {
1178 Slog.w(TAG, "unable to apply policy to appId " + appId + "; ignoring");
1179 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001180 }
1181 }
1182 }
1183
1184 } catch (FileNotFoundException e) {
1185 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001186 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001187 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001188 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001189 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001190 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001191 } finally {
1192 IoUtils.closeQuietly(fis);
1193 }
1194 }
1195
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001196 /**
1197 * Upgrade legacy background data flags, notifying listeners of one last
1198 * change to always-true.
1199 */
1200 private void upgradeLegacyBackgroundData() {
1201 mRestrictBackground = Settings.Secure.getInt(
1202 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1203
1204 // kick off one last broadcast if restricted
1205 if (mRestrictBackground) {
1206 final Intent broadcast = new Intent(
1207 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
1208 mContext.sendBroadcast(broadcast);
1209 }
1210 }
1211
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001212 private void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001213 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001214
1215 FileOutputStream fos = null;
1216 try {
1217 fos = mPolicyFile.startWrite();
1218
1219 XmlSerializer out = new FastXmlSerializer();
1220 out.setOutput(fos, "utf-8");
1221 out.startDocument(null, true);
1222
1223 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001224 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001225 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001226
1227 // write all known network policies
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001228 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001229 final NetworkTemplate template = policy.template;
1230
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001231 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001232 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1233 final String subscriberId = template.getSubscriberId();
1234 if (subscriberId != null) {
1235 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001236 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001237 final String networkId = template.getNetworkId();
1238 if (networkId != null) {
1239 out.attribute(null, ATTR_NETWORK_ID, networkId);
1240 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001241 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001242 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001243 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1244 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001245 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1246 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001247 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001248 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001249 out.endTag(null, TAG_NETWORK_POLICY);
1250 }
1251
1252 // write all known uid policies
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001253 for (int i = 0; i < mAppPolicy.size(); i++) {
1254 final int appId = mAppPolicy.keyAt(i);
1255 final int policy = mAppPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001256
Jeff Sharkey497e4432011-06-14 17:27:29 -07001257 // skip writing empty policies
1258 if (policy == POLICY_NONE) continue;
1259
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001260 out.startTag(null, TAG_APP_POLICY);
1261 writeIntAttribute(out, ATTR_APP_ID, appId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001262 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001263 out.endTag(null, TAG_APP_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001264 }
1265
1266 out.endTag(null, TAG_POLICY_LIST);
1267 out.endDocument();
1268
1269 mPolicyFile.finishWrite(fos);
1270 } catch (IOException e) {
1271 if (fos != null) {
1272 mPolicyFile.failWrite(fos);
1273 }
1274 }
1275 }
1276
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001277 @Override
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001278 public void setAppPolicy(int appId, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001279 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001280
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001281 if (!UserId.isApp(appId)) {
1282 throw new IllegalArgumentException("cannot apply policy to appId " + appId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001283 }
1284
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001285 setAppPolicyUnchecked(appId, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001286 }
1287
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001288 private void setAppPolicyUnchecked(int appId, int policy, boolean persist) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001289 final int oldPolicy;
Jeff Sharkeya4620792011-05-20 15:29:23 -07001290 synchronized (mRulesLock) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001291 oldPolicy = getAppPolicy(appId);
1292 mAppPolicy.put(appId, policy);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001293
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001294 // uid policy changed, recompute rules and persist policy.
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001295 updateRulesForAppLocked(appId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001296 if (persist) {
1297 writePolicyLocked();
1298 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001299 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001300 }
1301
1302 @Override
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001303 public int getAppPolicy(int appId) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001304 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1305
Jeff Sharkeya4620792011-05-20 15:29:23 -07001306 synchronized (mRulesLock) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001307 return mAppPolicy.get(appId, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001308 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001309 }
1310
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001311 @Override
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001312 public int[] getAppsWithPolicy(int policy) {
1313 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1314
1315 int[] appIds = new int[0];
1316 synchronized (mRulesLock) {
1317 for (int i = 0; i < mAppPolicy.size(); i++) {
1318 final int appId = mAppPolicy.keyAt(i);
1319 final int appPolicy = mAppPolicy.valueAt(i);
1320 if (appPolicy == policy) {
1321 appIds = appendInt(appIds, appId);
1322 }
1323 }
1324 }
1325 return appIds;
1326 }
1327
1328 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001329 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001330 // TODO: create permission for observing network policy
1331 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1332
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001333 mListeners.register(listener);
1334
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001335 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001336 }
1337
1338 @Override
1339 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001340 // TODO: create permission for observing network policy
1341 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1342
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001343 mListeners.unregister(listener);
1344 }
1345
Jeff Sharkey1b861272011-05-22 00:34:52 -07001346 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001347 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001348 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1349
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001350 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001351 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001352 mNetworkPolicy.clear();
1353 for (NetworkPolicy policy : policies) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001354 mNetworkPolicy.put(policy.template, policy);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001355 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001356
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001357 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001358 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001359 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001360 writePolicyLocked();
1361 }
1362 }
1363
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001364 private void addNetworkPolicyLocked(NetworkPolicy policy) {
1365 mNetworkPolicy.put(policy.template, policy);
1366
1367 updateNetworkEnabledLocked();
1368 updateNetworkRulesLocked();
1369 updateNotificationsLocked();
1370 writePolicyLocked();
1371 }
1372
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001373 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001374 public NetworkPolicy[] getNetworkPolicies() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001375 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001376 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001377
1378 synchronized (mRulesLock) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001379 return mNetworkPolicy.values().toArray(new NetworkPolicy[mNetworkPolicy.size()]);
1380 }
1381 }
1382
1383 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001384 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001385 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001386 performSnooze(template, TYPE_LIMIT);
1387 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001388
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001389 private void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001390 maybeRefreshTrustedTime();
1391 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001392 synchronized (mRulesLock) {
1393 // find and snooze local policy that matches
1394 final NetworkPolicy policy = mNetworkPolicy.get(template);
1395 if (policy == null) {
1396 throw new IllegalArgumentException("unable to find policy for " + template);
1397 }
1398
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001399 switch (type) {
1400 case TYPE_WARNING:
1401 policy.lastWarningSnooze = currentTime;
1402 break;
1403 case TYPE_LIMIT:
1404 policy.lastLimitSnooze = currentTime;
1405 break;
1406 default:
1407 throw new IllegalArgumentException("unexpected type");
1408 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001409
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001410 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001411 updateNetworkRulesLocked();
1412 updateNotificationsLocked();
1413 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001414 }
1415 }
1416
1417 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001418 public void setRestrictBackground(boolean restrictBackground) {
1419 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1420
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001421 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001422 synchronized (mRulesLock) {
1423 mRestrictBackground = restrictBackground;
1424 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001425 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001426 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001427 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001428
1429 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1430 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001431 }
1432
1433 @Override
1434 public boolean getRestrictBackground() {
1435 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1436
1437 synchronized (mRulesLock) {
1438 return mRestrictBackground;
1439 }
1440 }
1441
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001442 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
1443 for (NetworkPolicy policy : mNetworkPolicy.values()) {
1444 if (policy.template.matches(ident)) {
1445 return policy;
1446 }
1447 }
1448 return null;
1449 }
1450
1451 @Override
1452 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1453 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1454
1455 // only returns usage summary, so we don't require caller to have
1456 // READ_NETWORK_USAGE_HISTORY.
1457 final long token = Binder.clearCallingIdentity();
1458 try {
1459 return getNetworkQuotaInfoUnchecked(state);
1460 } finally {
1461 Binder.restoreCallingIdentity(token);
1462 }
1463 }
1464
1465 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1466 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1467
1468 final NetworkPolicy policy;
1469 synchronized (mRulesLock) {
1470 policy = findPolicyForNetworkLocked(ident);
1471 }
1472
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001473 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001474 // missing policy means we can't derive useful quota info
1475 return null;
1476 }
1477
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001478 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001479
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001480 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001481 final long start = computeLastCycleBoundary(currentTime, policy);
1482 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001483 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001484
1485 // report soft and hard limits under policy
1486 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1487 : NetworkQuotaInfo.NO_LIMIT;
1488 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1489 : NetworkQuotaInfo.NO_LIMIT;
1490
1491 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1492 }
1493
Jeff Sharkey46645002011-07-27 21:11:21 -07001494 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001495 public boolean isNetworkMetered(NetworkState state) {
1496 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1497
1498 final NetworkPolicy policy;
1499 synchronized (mRulesLock) {
1500 policy = findPolicyForNetworkLocked(ident);
1501 }
1502
1503 if (policy != null) {
1504 return policy.metered;
1505 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001506 final int type = state.networkInfo.getType();
1507 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1508 return true;
1509 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001510 return false;
1511 }
1512 }
1513
1514 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001515 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001516 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001517
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001518 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1519
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001520 final HashSet<String> argSet = new HashSet<String>();
1521 for (String arg : args) {
1522 argSet.add(arg);
1523 }
1524
Jeff Sharkey1b861272011-05-22 00:34:52 -07001525 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001526 if (argSet.contains("--unsnooze")) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001527 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001528 policy.clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001529 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001530
1531 updateNetworkEnabledLocked();
1532 updateNetworkRulesLocked();
1533 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001534 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001535
1536 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001537 return;
1538 }
1539
Jeff Sharkey46645002011-07-27 21:11:21 -07001540 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001541 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001542 fout.increaseIndent();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001543 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001544 fout.println(policy.toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001545 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001546 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001547
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001548 fout.println("Policy for apps:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001549 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001550 int size = mAppPolicy.size();
1551 for (int i = 0; i < size; i++) {
1552 final int appId = mAppPolicy.keyAt(i);
1553 final int policy = mAppPolicy.valueAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001554 fout.print("appId=");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001555 fout.print(appId);
1556 fout.print(" policy=");
1557 dumpPolicy(fout, policy);
1558 fout.println();
1559 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001560 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001561
1562 final SparseBooleanArray knownUids = new SparseBooleanArray();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001563 collectKeys(mUidForeground, knownUids);
1564 collectKeys(mUidRules, knownUids);
1565
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001566 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001567 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001568 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001569 for (int i = 0; i < size; i++) {
1570 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001571 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001572 fout.print(uid);
1573
Jeff Sharkey1b861272011-05-22 00:34:52 -07001574 fout.print(" foreground=");
1575 final int foregroundIndex = mUidPidForeground.indexOfKey(uid);
1576 if (foregroundIndex < 0) {
1577 fout.print("UNKNOWN");
1578 } else {
1579 dumpSparseBooleanArray(fout, mUidPidForeground.valueAt(foregroundIndex));
1580 }
1581
1582 fout.print(" rules=");
1583 final int rulesIndex = mUidRules.indexOfKey(uid);
1584 if (rulesIndex < 0) {
1585 fout.print("UNKNOWN");
1586 } else {
1587 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1588 }
1589
1590 fout.println();
1591 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001592 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001593 }
1594 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001595
1596 @Override
1597 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001598 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1599
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001600 synchronized (mRulesLock) {
1601 // only really in foreground when screen is also on
1602 return mUidForeground.get(uid, false) && mScreenOn;
1603 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001604 }
1605
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001606 /**
1607 * Foreground for PID changed; recompute foreground at UID level. If
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001608 * changed, will trigger {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001609 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001610 private void computeUidForegroundLocked(int uid) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001611 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1612
1613 // current pid is dropping foreground; examine other pids
1614 boolean uidForeground = false;
1615 final int size = pidForeground.size();
1616 for (int i = 0; i < size; i++) {
1617 if (pidForeground.valueAt(i)) {
1618 uidForeground = true;
1619 break;
1620 }
1621 }
1622
1623 final boolean oldUidForeground = mUidForeground.get(uid, false);
1624 if (oldUidForeground != uidForeground) {
1625 // foreground changed, push updated rules
1626 mUidForeground.put(uid, uidForeground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001627 updateRulesForUidLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001628 }
1629 }
1630
Jeff Sharkeya4620792011-05-20 15:29:23 -07001631 private void updateScreenOn() {
1632 synchronized (mRulesLock) {
1633 try {
1634 mScreenOn = mPowerManager.isScreenOn();
1635 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001636 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07001637 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001638 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001639 }
1640 }
1641
1642 /**
1643 * Update rules that might be changed by {@link #mScreenOn} value.
1644 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001645 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07001646 // only update rules for anyone with foreground activities
1647 final int size = mUidForeground.size();
1648 for (int i = 0; i < size; i++) {
1649 if (mUidForeground.valueAt(i)) {
1650 final int uid = mUidForeground.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001651 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001652 }
1653 }
1654 }
1655
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001656 /**
Jeff Sharkey46645002011-07-27 21:11:21 -07001657 * Update rules that might be changed by {@link #mRestrictBackground} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001658 */
Jeff Sharkey46645002011-07-27 21:11:21 -07001659 private void updateRulesForRestrictBackgroundLocked() {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001660 // update rules for all installed applications
1661 final PackageManager pm = mContext.getPackageManager();
1662 final List<ApplicationInfo> apps = pm.getInstalledApplications(0);
1663 for (ApplicationInfo app : apps) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001664 final int appId = UserId.getAppId(app.uid);
1665 updateRulesForAppLocked(appId);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001666 }
1667
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001668 // limit data usage for some internal system services
1669 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
1670 updateRulesForUidLocked(android.os.Process.DRM_UID);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001671 }
1672
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001673 private void updateRulesForAppLocked(int appId) {
1674 for (UserInfo user : mContext.getPackageManager().getUsers()) {
1675 final int uid = UserId.getUid(user.id, appId);
1676 updateRulesForUidLocked(uid);
1677 }
1678 }
1679
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001680 private static boolean isUidValidForRules(int uid) {
1681 // allow rules on specific system services, and any apps
1682 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
1683 || UserId.isApp(uid)) {
1684 return true;
1685 }
1686
1687 return false;
1688 }
1689
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001690 private void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001691 if (!isUidValidForRules(uid)) return;
1692
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001693 final int appId = UserId.getAppId(uid);
1694 final int appPolicy = getAppPolicy(appId);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001695 final boolean uidForeground = isUidForeground(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001696
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001697 // derive active rules based on policy and active state
1698 int uidRules = RULE_ALLOW_ALL;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001699 if (!uidForeground && (appPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001700 // uid in background, and policy says to block metered data
1701 uidRules = RULE_REJECT_METERED;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001702 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001703 if (!uidForeground && mRestrictBackground) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001704 // uid in background, and global background disabled
1705 uidRules = RULE_REJECT_METERED;
1706 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001707
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001708 // TODO: only dispatch when rules actually change
1709
Jeff Sharkey350083e2011-06-29 10:45:16 -07001710 if (uidRules == RULE_ALLOW_ALL) {
1711 mUidRules.delete(uid);
1712 } else {
1713 mUidRules.put(uid, uidRules);
1714 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001715
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001716 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001717 setUidNetworkRules(uid, rejectMetered);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001718
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001719 // dispatch changed rule to existing listeners
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001720 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001721
1722 try {
1723 // adjust stats accounting based on foreground status
1724 mNetworkStats.setUidForeground(uid, uidForeground);
1725 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001726 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001727 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001728 }
1729
1730 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001731 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001732 public boolean handleMessage(Message msg) {
1733 switch (msg.what) {
1734 case MSG_RULES_CHANGED: {
1735 final int uid = msg.arg1;
1736 final int uidRules = msg.arg2;
1737 final int length = mListeners.beginBroadcast();
1738 for (int i = 0; i < length; i++) {
1739 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1740 if (listener != null) {
1741 try {
1742 listener.onUidRulesChanged(uid, uidRules);
1743 } catch (RemoteException e) {
1744 }
1745 }
1746 }
1747 mListeners.finishBroadcast();
1748 return true;
1749 }
1750 case MSG_METERED_IFACES_CHANGED: {
1751 final String[] meteredIfaces = (String[]) msg.obj;
1752 final int length = mListeners.beginBroadcast();
1753 for (int i = 0; i < length; i++) {
1754 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1755 if (listener != null) {
1756 try {
1757 listener.onMeteredIfacesChanged(meteredIfaces);
1758 } catch (RemoteException e) {
1759 }
1760 }
1761 }
1762 mListeners.finishBroadcast();
1763 return true;
1764 }
Jeff Sharkey6f7af032011-11-01 18:25:15 -07001765 case MSG_FOREGROUND_ACTIVITIES_CHANGED: {
1766 final int pid = msg.arg1;
1767 final int uid = msg.arg2;
1768 final boolean foregroundActivities = (Boolean) msg.obj;
1769
1770 synchronized (mRulesLock) {
1771 // because a uid can have multiple pids running inside, we need to
1772 // remember all pid states and summarize foreground at uid level.
1773
1774 // record foreground for this specific pid
1775 SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1776 if (pidForeground == null) {
1777 pidForeground = new SparseBooleanArray(2);
1778 mUidPidForeground.put(uid, pidForeground);
1779 }
1780 pidForeground.put(pid, foregroundActivities);
1781 computeUidForegroundLocked(uid);
1782 }
1783 return true;
1784 }
1785 case MSG_PROCESS_DIED: {
1786 final int pid = msg.arg1;
1787 final int uid = msg.arg2;
1788
1789 synchronized (mRulesLock) {
1790 // clear records and recompute, when they exist
1791 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1792 if (pidForeground != null) {
1793 pidForeground.delete(pid);
1794 computeUidForegroundLocked(uid);
1795 }
1796 }
1797 return true;
1798 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001799 case MSG_LIMIT_REACHED: {
1800 final String iface = (String) msg.obj;
1801
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001802 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001803 synchronized (mRulesLock) {
1804 if (mMeteredIfaces.contains(iface)) {
1805 try {
1806 // force stats update to make sure we have
1807 // numbers that caused alert to trigger.
1808 mNetworkStats.forceUpdate();
1809 } catch (RemoteException e) {
1810 // ignored; service lives in system_server
1811 }
1812
1813 updateNetworkEnabledLocked();
1814 updateNotificationsLocked();
1815 }
1816 }
1817 return true;
1818 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001819 case MSG_RESTRICT_BACKGROUND_CHANGED: {
1820 final boolean restrictBackground = msg.arg1 != 0;
1821 final int length = mListeners.beginBroadcast();
1822 for (int i = 0; i < length; i++) {
1823 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1824 if (listener != null) {
1825 try {
1826 listener.onRestrictBackgroundChanged(restrictBackground);
1827 } catch (RemoteException e) {
1828 }
1829 }
1830 }
1831 mListeners.finishBroadcast();
1832 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001833 default: {
1834 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07001835 }
1836 }
1837 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001838 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001839
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001840 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001841 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001842 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001843 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001844 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001845 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001846 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001847 }
1848 }
1849
1850 private void removeInterfaceQuota(String iface) {
1851 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001852 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001853 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001854 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001855 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001856 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001857 }
1858 }
1859
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001860 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1861 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001862 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001863 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001864 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001865 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001866 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001867 }
1868 }
1869
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001870 /**
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001871 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001872 */
1873 private void setPolicyDataEnable(int networkType, boolean enabled) {
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001874 try {
1875 mConnManager.setPolicyDataEnable(networkType, enabled);
1876 } catch (RemoteException e) {
1877 // ignored; service lives in system_server
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001878 }
1879 }
1880
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001881 private long getTotalBytes(NetworkTemplate template, long start, long end) {
1882 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07001883 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001884 } catch (RuntimeException e) {
1885 Slog.w(TAG, "problem reading network stats: " + e);
1886 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001887 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001888 // ignored; service lives in system_server
1889 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001890 }
1891 }
1892
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001893 /**
1894 * Try refreshing {@link #mTime} when stale.
1895 */
1896 private void maybeRefreshTrustedTime() {
1897 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001898 mTime.forceRefresh();
1899 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001900 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001901
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001902 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001903 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
1904 }
1905
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001906 private static Intent buildAllowBackgroundDataIntent() {
1907 return new Intent(ACTION_ALLOW_BACKGROUND);
1908 }
1909
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001910 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
1911 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
1912 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
1913 return intent;
1914 }
1915
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001916 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
1917 final Intent intent = new Intent();
1918 intent.setComponent(new ComponentName(
1919 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
1920 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1921 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
1922 return intent;
1923 }
1924
1925 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
1926 final Intent intent = new Intent();
1927 intent.setComponent(new ComponentName(
1928 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
1929 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
1930 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
1931 return intent;
1932 }
1933
Jeff Sharkey163e6442011-10-31 16:37:52 -07001934 // @VisibleForTesting
1935 public void addIdleHandler(IdleHandler handler) {
1936 mHandler.getLooper().getQueue().addIdleHandler(handler);
1937 }
1938
Jeff Sharkey1b861272011-05-22 00:34:52 -07001939 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
1940 final int size = source.size();
1941 for (int i = 0; i < size; i++) {
1942 target.put(source.keyAt(i), true);
1943 }
1944 }
1945
1946 private static void collectKeys(SparseBooleanArray source, SparseBooleanArray target) {
1947 final int size = source.size();
1948 for (int i = 0; i < size; i++) {
1949 target.put(source.keyAt(i), true);
1950 }
1951 }
1952
1953 private static void dumpSparseBooleanArray(PrintWriter fout, SparseBooleanArray value) {
1954 fout.print("[");
1955 final int size = value.size();
1956 for (int i = 0; i < size; i++) {
1957 fout.print(value.keyAt(i) + "=" + value.valueAt(i));
1958 if (i < size - 1) fout.print(",");
1959 }
1960 fout.print("]");
1961 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001962
Jeff Sharkey46645002011-07-27 21:11:21 -07001963 public static class XmlUtils {
1964 public static int readIntAttribute(XmlPullParser in, String name) throws IOException {
1965 final String value = in.getAttributeValue(null, name);
1966 try {
1967 return Integer.parseInt(value);
1968 } catch (NumberFormatException e) {
1969 throw new ProtocolException("problem parsing " + name + "=" + value + " as int");
1970 }
1971 }
1972
1973 public static void writeIntAttribute(XmlSerializer out, String name, int value)
1974 throws IOException {
1975 out.attribute(null, name, Integer.toString(value));
1976 }
1977
1978 public static long readLongAttribute(XmlPullParser in, String name) throws IOException {
1979 final String value = in.getAttributeValue(null, name);
1980 try {
1981 return Long.parseLong(value);
1982 } catch (NumberFormatException e) {
1983 throw new ProtocolException("problem parsing " + name + "=" + value + " as long");
1984 }
1985 }
1986
1987 public static void writeLongAttribute(XmlSerializer out, String name, long value)
1988 throws IOException {
1989 out.attribute(null, name, Long.toString(value));
1990 }
1991
1992 public static boolean readBooleanAttribute(XmlPullParser in, String name) {
1993 final String value = in.getAttributeValue(null, name);
1994 return Boolean.parseBoolean(value);
1995 }
1996
1997 public static void writeBooleanAttribute(XmlSerializer out, String name, boolean value)
1998 throws IOException {
1999 out.attribute(null, name, Boolean.toString(value));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002000 }
2001 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002002}