blob: a82f421c90ec39dd74e0c864d63e1d61c33a1bdc [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;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070027import static android.content.Intent.ACTION_USER_ADDED;
28import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070029import static android.content.Intent.EXTRA_UID;
Jeff Sharkey961e3042011-08-29 16:02:57 -070030import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070031import static android.net.ConnectivityManager.TYPE_ETHERNET;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070032import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070033import static android.net.ConnectivityManager.TYPE_WIFI;
34import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070035import static android.net.ConnectivityManager.isNetworkTypeMobile;
36import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070037import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070038import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070039import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070040import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070041import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070042import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070043import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070044import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070045import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Jeff Sharkey1b861272011-05-22 00:34:52 -070046import static android.net.NetworkPolicyManager.dumpPolicy;
47import static android.net.NetworkPolicyManager.dumpRules;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070048import static android.net.NetworkTemplate.MATCH_ETHERNET;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070049import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
50import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070051import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
52import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070053import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080054import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070055import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
56import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
57import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
58import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
59import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
60import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
61import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070062import static android.telephony.TelephonyManager.SIM_STATE_READY;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070063import static android.text.format.DateUtils.DAY_IN_MILLIS;
Jeff Sharkey854b2b12012-04-13 16:03:40 -070064import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070065import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070066import static com.android.internal.util.XmlUtils.readBooleanAttribute;
67import static com.android.internal.util.XmlUtils.readIntAttribute;
68import static com.android.internal.util.XmlUtils.readLongAttribute;
69import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
70import static com.android.internal.util.XmlUtils.writeIntAttribute;
71import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070072import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070073import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070074import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
75import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070076
Jeff Sharkeya4620792011-05-20 15:29:23 -070077import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070078import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070079import android.app.IProcessObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070080import android.app.Notification;
81import android.app.PendingIntent;
Jeff Sharkeya4620792011-05-20 15:29:23 -070082import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070083import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070084import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070085import android.content.Intent;
86import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070087import android.content.pm.ApplicationInfo;
88import android.content.pm.PackageManager;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -070089import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -070090import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070091import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070092import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070093import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070094import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070095import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -070096import android.net.INetworkStatsService;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070097import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070098import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070099import android.net.NetworkPolicy;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700100import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700101import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700102import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700103import android.net.wifi.WifiConfiguration;
104import android.net.wifi.WifiInfo;
105import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700106import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700107import android.os.Environment;
108import android.os.Handler;
109import android.os.HandlerThread;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700110import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700111import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700112import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700113import android.os.MessageQueue.IdleHandler;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700114import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700115import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700116import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700117import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700118import android.provider.Settings;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700119import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700120import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700121import android.text.format.Time;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700122import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700123import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700124import android.util.NtpTrustedTime;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700125import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700126import android.util.SparseArray;
127import android.util.SparseBooleanArray;
128import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700129import android.util.TrustedTime;
130import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700131
Jeff Sharkey497e4432011-06-14 17:27:29 -0700132import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800133import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700134import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700135import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700136import com.android.internal.util.Objects;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700137import com.google.android.collect.Lists;
138import com.google.android.collect.Maps;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700139import com.google.android.collect.Sets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700140
141import org.xmlpull.v1.XmlPullParser;
142import org.xmlpull.v1.XmlPullParserException;
143import org.xmlpull.v1.XmlSerializer;
144
145import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700146import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700147import java.io.FileInputStream;
148import java.io.FileNotFoundException;
149import java.io.FileOutputStream;
150import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700151import java.io.PrintWriter;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700152import java.util.ArrayList;
153import java.util.Arrays;
154import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700155import java.util.HashSet;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700156import java.util.List;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700157import java.util.Map;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700158
159import libcore.io.IoUtils;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700160
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700161/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700162 * Service that maintains low-level network policy rules, using
163 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700164 * <p>
165 * Derives active rules by combining a given policy with other system status,
166 * and delivers to listeners, such as {@link ConnectivityManager}, for
167 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700168 */
169public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
170 private static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700171 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700172 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700173
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700174 private static final int VERSION_INIT = 1;
175 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700176 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800177 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800178 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800179 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700180 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700181 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700182 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700183 private static final int VERSION_SWITCH_UID = 10;
184 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700185
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800186 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700187 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800188 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700189 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800190 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700191 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700192
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700193 private static final String TAG_POLICY_LIST = "policy-list";
194 private static final String TAG_NETWORK_POLICY = "network-policy";
195 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700196 private static final String TAG_APP_POLICY = "app-policy";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700197
198 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700199 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700200 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
201 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700202 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700203 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800204 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700205 private static final String ATTR_WARNING_BYTES = "warningBytes";
206 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700207 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800208 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
209 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800210 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700211 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700212 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700213 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700214 private static final String ATTR_POLICY = "policy";
215
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700216 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
217
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800218 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800219 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800220 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800221 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700222
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700223 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
224
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700225 private static final int MSG_RULES_CHANGED = 1;
226 private static final int MSG_METERED_IFACES_CHANGED = 2;
227 private static final int MSG_FOREGROUND_ACTIVITIES_CHANGED = 3;
228 private static final int MSG_PROCESS_DIED = 4;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800229 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800230 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700231 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700232 private static final int MSG_SCREEN_ON_CHANGED = 8;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700233
Jeff Sharkey75279902011-05-24 18:39:45 -0700234 private final Context mContext;
235 private final IActivityManager mActivityManager;
236 private final IPowerManager mPowerManager;
237 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700238 private final INetworkManagementService mNetworkManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700239 private final TrustedTime mTime;
240
241 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700242 private INotificationManager mNotifManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700243
Jeff Sharkey75279902011-05-24 18:39:45 -0700244 private final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700245
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700246 private volatile boolean mScreenOn;
247 private volatile boolean mRestrictBackground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700248
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700249 private final boolean mSuppressDefaultPolicy;
250
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700251 /** Defined network policies. */
252 private HashMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = Maps.newHashMap();
253 /** Currently active network rules for ifaces. */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700254 private HashMap<NetworkPolicy, String[]> mNetworkRules = Maps.newHashMap();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700255
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700256 /** Defined UID policies. */
257 private SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700258 /** Currently derived rules for each UID. */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700259 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700260
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700261 /** Set of ifaces that are metered. */
262 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700263 /** Set of over-limit templates that have been notified. */
264 private HashSet<NetworkTemplate> mOverLimitNotified = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700265
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700266 /** Set of currently active {@link Notification} tags. */
267 private HashSet<String> mActiveNotifs = Sets.newHashSet();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700268
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700269 /** Foreground at both UID and PID granularity. */
Jeff Sharkeya4620792011-05-20 15:29:23 -0700270 private SparseBooleanArray mUidForeground = new SparseBooleanArray();
271 private SparseArray<SparseBooleanArray> mUidPidForeground = new SparseArray<
272 SparseBooleanArray>();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700273
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700274 private final RemoteCallbackList<INetworkPolicyListener> mListeners = new RemoteCallbackList<
275 INetworkPolicyListener>();
276
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700277 private final HandlerThread mHandlerThread;
278 private final Handler mHandler;
279
280 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700281
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700282 // TODO: keep whitelist of system-critical services that should never have
283 // rules enforced, such as system, phone, and radio UIDs.
284
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700285 // TODO: migrate notifications to SystemUI
286
Jeff Sharkey75279902011-05-24 18:39:45 -0700287 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700288 IPowerManager powerManager, INetworkStatsService networkStats,
289 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700290 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700291 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700292 }
293
294 private static File getSystemDir() {
295 return new File(Environment.getDataDirectory(), "system");
296 }
297
298 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700299 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700300 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
301 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700302 mContext = checkNotNull(context, "missing context");
303 mActivityManager = checkNotNull(activityManager, "missing activityManager");
304 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700305 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700306 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700307 mTime = checkNotNull(time, "missing TrustedTime");
308
309 mHandlerThread = new HandlerThread(TAG);
310 mHandlerThread.start();
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700311 mHandler = new Handler(mHandlerThread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700312
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700313 mSuppressDefaultPolicy = suppressDefaultPolicy;
314
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700315 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
316 }
317
318 public void bindConnectivityManager(IConnectivityManager connManager) {
319 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700320 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700321
Jeff Sharkey497e4432011-06-14 17:27:29 -0700322 public void bindNotificationManager(INotificationManager notifManager) {
323 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
324 }
325
Jeff Sharkeya4620792011-05-20 15:29:23 -0700326 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700327 if (!isBandwidthControlEnabled()) {
328 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
329 return;
330 }
331
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700332 synchronized (mRulesLock) {
333 // read policy from disk
334 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700335
336 if (mRestrictBackground) {
337 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700338 updateNotificationsLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700339 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700340 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700341
Jeff Sharkeya4620792011-05-20 15:29:23 -0700342 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700343
Jeff Sharkeya4620792011-05-20 15:29:23 -0700344 try {
345 mActivityManager.registerProcessObserver(mProcessObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700346 mNetworkManager.registerObserver(mAlertObserver);
347 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700348 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700349 }
350
Jeff Sharkeya4620792011-05-20 15:29:23 -0700351 // TODO: traverse existing processes to know foreground state, or have
352 // activitymanager dispatch current state when new observer attached.
353
354 final IntentFilter screenFilter = new IntentFilter();
355 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
356 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700357 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700358
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700359 // watch for network interfaces to be claimed
Jeff Sharkey961e3042011-08-29 16:02:57 -0700360 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION_IMMEDIATE);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700361 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
362
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700363 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700364 final IntentFilter packageFilter = new IntentFilter();
365 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700366 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700367 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700368
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700369 // listen for UID changes to update policy
370 mContext.registerReceiver(
371 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
372
373 // listen for user changes to update policy
374 final IntentFilter userFilter = new IntentFilter();
375 userFilter.addAction(ACTION_USER_ADDED);
376 userFilter.addAction(ACTION_USER_REMOVED);
377 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
378
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700379 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700380 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
381 mContext.registerReceiver(
382 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
383
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700384 // listen for restrict background changes from notifications
385 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
386 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
387
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800388 // listen for snooze warning from notifications
389 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
390 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
391 MANAGE_NETWORK_POLICY, mHandler);
392
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700393 // listen for configured wifi networks to be removed
394 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
395 mContext.registerReceiver(
396 mWifiConfigReceiver, wifiConfigFilter, CONNECTIVITY_INTERNAL, mHandler);
397
398 // listen for wifi state changes to catch metered hint
399 final IntentFilter wifiStateFilter = new IntentFilter(
400 WifiManager.NETWORK_STATE_CHANGED_ACTION);
401 mContext.registerReceiver(
402 mWifiStateReceiver, wifiStateFilter, CONNECTIVITY_INTERNAL, mHandler);
403
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700404 }
405
Jeff Sharkeya4620792011-05-20 15:29:23 -0700406 private IProcessObserver mProcessObserver = new IProcessObserver.Stub() {
407 @Override
408 public void onForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700409 mHandler.obtainMessage(MSG_FOREGROUND_ACTIVITIES_CHANGED,
410 pid, uid, foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700411 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700412
413 @Override
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700414 public void onImportanceChanged(int pid, int uid, int importance) {
415 }
416
417 @Override
Jeff Sharkeya4620792011-05-20 15:29:23 -0700418 public void onProcessDied(int pid, int uid) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700419 mHandler.obtainMessage(MSG_PROCESS_DIED, pid, uid).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700420 }
421 };
422
423 private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
424 @Override
425 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800426 // screen-related broadcasts are protected by system, no need
427 // for permissions check.
428 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700429 }
430 };
431
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700432 private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700433 @Override
434 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700435 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700436
437 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700438 final int uid = intent.getIntExtra(EXTRA_UID, -1);
439 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700440
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700441 if (ACTION_PACKAGE_ADDED.equals(action)) {
442 // update rules for UID, since it might be subject to
443 // global background data policy
444 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
445 synchronized (mRulesLock) {
446 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700447 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700448 }
449 }
450 };
451
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700452 private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
453 @Override
454 public void onReceive(Context context, Intent intent) {
455 // on background handler thread, and UID_REMOVED is protected
456
457 final int uid = intent.getIntExtra(EXTRA_UID, -1);
458 if (uid == -1) return;
459
460 // remove any policy and update rules to clean up
461 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
462 synchronized (mRulesLock) {
463 mUidPolicy.delete(uid);
464 updateRulesForUidLocked(uid);
465 writePolicyLocked();
466 }
467 }
468 };
469
470 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
471 @Override
472 public void onReceive(Context context, Intent intent) {
473 // on background handler thread, and USER_ADDED and USER_REMOVED
474 // broadcasts are protected
475
476 final String action = intent.getAction();
477 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
478 if (userId == -1) return;
479
480 // Remove any policies for given user; both cleaning up after a
481 // USER_REMOVED, and one last sanity check during USER_ADDED
482 removePoliciesForUserLocked(userId);
483
484 // Update global restrict for new user
485 synchronized (mRulesLock) {
486 updateRulesForRestrictBackgroundLocked();
487 }
488 }
489 };
490
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700491 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700492 * Receiver that watches for {@link INetworkStatsService} updates, which we
493 * use to check against {@link NetworkPolicy#warningBytes}.
494 */
495 private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
496 @Override
497 public void onReceive(Context context, Intent intent) {
498 // on background handler thread, and verified
499 // READ_NETWORK_USAGE_HISTORY permission above.
500
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800501 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700502 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700503 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700504 updateNotificationsLocked();
505 }
506 }
507 };
508
509 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700510 * Receiver that watches for {@link Notification} control of
511 * {@link #mRestrictBackground}.
512 */
513 private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
514 @Override
515 public void onReceive(Context context, Intent intent) {
516 // on background handler thread, and verified MANAGE_NETWORK_POLICY
517 // permission above.
518
519 setRestrictBackground(false);
520 }
521 };
522
523 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800524 * Receiver that watches for {@link Notification} control of
525 * {@link NetworkPolicy#lastWarningSnooze}.
526 */
527 private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
528 @Override
529 public void onReceive(Context context, Intent intent) {
530 // on background handler thread, and verified MANAGE_NETWORK_POLICY
531 // permission above.
532
533 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
534 performSnooze(template, TYPE_WARNING);
535 }
536 };
537
538 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700539 * Receiver that watches for {@link WifiConfiguration} to be changed.
540 */
541 private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
542 @Override
543 public void onReceive(Context context, Intent intent) {
544 // on background handler thread, and verified CONNECTIVITY_INTERNAL
545 // permission above.
546
547 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
548 if (reason == CHANGE_REASON_REMOVED) {
549 final WifiConfiguration config = intent.getParcelableExtra(
550 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700551 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800552 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700553 synchronized (mRulesLock) {
554 if (mNetworkPolicy.containsKey(template)) {
555 mNetworkPolicy.remove(template);
556 writePolicyLocked();
557 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700558 }
559 }
560 }
561 }
562 };
563
564 /**
565 * Receiver that watches {@link WifiInfo} state changes to infer metered
566 * state. Ignores hints when policy is user-defined.
567 */
568 private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
569 @Override
570 public void onReceive(Context context, Intent intent) {
571 // on background handler thread, and verified CONNECTIVITY_INTERNAL
572 // permission above.
573
574 // ignore when not connected
575 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
576 if (!netInfo.isConnected()) return;
577
578 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
579 final boolean meteredHint = info.getMeteredHint();
580
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800581 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700582 synchronized (mRulesLock) {
583 NetworkPolicy policy = mNetworkPolicy.get(template);
584 if (policy == null && meteredHint) {
585 // policy doesn't exist, and AP is hinting that it's
586 // metered: create an inferred policy.
587 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
588 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
589 meteredHint, true);
590 addNetworkPolicyLocked(policy);
591
592 } else if (policy != null && policy.inferred) {
593 // policy exists, and was inferred: update its current
594 // metered state.
595 policy.metered = meteredHint;
596
597 // since this is inferred for each wifi session, just update
598 // rules without persisting.
599 updateNetworkRulesLocked();
600 }
601 }
602 }
603 };
604
605 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700606 * Observer that watches for {@link INetworkManagementService} alerts.
607 */
Jeff Sharkey216c1812012-08-05 14:29:23 -0700608 private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700609 @Override
610 public void limitReached(String limitName, String iface) {
611 // only someone like NMS should be calling us
612 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
613
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800614 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
615 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700616 }
617 }
618 };
619
620 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700621 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
622 * to show visible notifications as needed.
623 */
624 private void updateNotificationsLocked() {
625 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
626
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700627 // keep track of previously active notifications
628 final HashSet<String> beforeNotifs = Sets.newHashSet();
629 beforeNotifs.addAll(mActiveNotifs);
630 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700631
632 // TODO: when switching to kernel notifications, compute next future
633 // cycle boundary to recompute notifications.
634
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700635 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800636 final long currentTime = currentTimeMillis();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700637 for (NetworkPolicy policy : mNetworkPolicy.values()) {
638 // ignore policies that aren't relevant to user
639 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700640 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700641
Jeff Sharkey497e4432011-06-14 17:27:29 -0700642 final long start = computeLastCycleBoundary(currentTime, policy);
643 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700644 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700645
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700646 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800647 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700648 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
649 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700650 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
651 notifyOverLimitLocked(policy.template);
652 }
653
Jeff Sharkey497e4432011-06-14 17:27:29 -0700654 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700655 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700656
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800657 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700658 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700659 }
660 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700661 }
662
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700663 // ongoing notification when restricting background data
664 if (mRestrictBackground) {
665 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700666 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700667
668 // cancel stale notifications that we didn't renew above
669 for (String tag : beforeNotifs) {
670 if (!mActiveNotifs.contains(tag)) {
671 cancelNotification(tag);
672 }
673 }
674 }
675
676 /**
677 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700678 * current device state, such as when
679 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
680 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700681 */
682 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700683 final TelephonyManager tele = TelephonyManager.from(mContext);
684
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700685 switch (template.getMatchRule()) {
686 case MATCH_MOBILE_3G_LOWER:
687 case MATCH_MOBILE_4G:
688 case MATCH_MOBILE_ALL:
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700689 // mobile templates are relevant when SIM is ready and
690 // subscriberId matches.
691 if (tele.getSimState() == SIM_STATE_READY) {
692 return Objects.equal(tele.getSubscriberId(), template.getSubscriberId());
693 } else {
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700694 return false;
695 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700696 }
697 return true;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700698 }
699
700 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700701 * Notify that given {@link NetworkTemplate} is over
702 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
703 */
704 private void notifyOverLimitLocked(NetworkTemplate template) {
705 if (!mOverLimitNotified.contains(template)) {
706 mContext.startActivity(buildNetworkOverLimitIntent(template));
707 mOverLimitNotified.add(template);
708 }
709 }
710
711 private void notifyUnderLimitLocked(NetworkTemplate template) {
712 mOverLimitNotified.remove(template);
713 }
714
715 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700716 * Build unique tag that identifies an active {@link NetworkPolicy}
717 * notification of a specific type, like {@link #TYPE_LIMIT}.
718 */
719 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700720 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700721 }
722
723 /**
724 * Show notification for combined {@link NetworkPolicy} and specific type,
725 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
726 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700727 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700728 final String tag = buildNotificationTag(policy, type);
729 final Notification.Builder builder = new Notification.Builder(mContext);
730 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800731 builder.setWhen(0L);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700732
733 final Resources res = mContext.getResources();
734 switch (type) {
735 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700736 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700737 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700738
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700739 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700740 builder.setTicker(title);
741 builder.setContentTitle(title);
742 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700743
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800744 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
745 builder.setDeleteIntent(PendingIntent.getBroadcast(
746 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
747
748 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700749 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800750 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
751
Jeff Sharkey497e4432011-06-14 17:27:29 -0700752 break;
753 }
754 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700755 final CharSequence body = res.getText(R.string.data_usage_limit_body);
756
757 final CharSequence title;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700758 switch (policy.template.getMatchRule()) {
759 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700760 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700761 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700762 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700763 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700764 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700765 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700766 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700767 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700768 case MATCH_WIFI:
769 title = res.getText(R.string.data_usage_wifi_limit_title);
770 break;
771 default:
772 title = null;
773 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700774 }
775
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800776 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700777 builder.setSmallIcon(R.drawable.stat_notify_disabled);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700778 builder.setTicker(title);
779 builder.setContentTitle(title);
780 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700781
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700782 final Intent intent = buildNetworkOverLimitIntent(policy.template);
783 builder.setContentIntent(PendingIntent.getActivity(
784 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
785 break;
786 }
787 case TYPE_LIMIT_SNOOZED: {
788 final long overBytes = totalBytes - policy.limitBytes;
789 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
790 Formatter.formatFileSize(mContext, overBytes));
791
792 final CharSequence title;
793 switch (policy.template.getMatchRule()) {
794 case MATCH_MOBILE_3G_LOWER:
795 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
796 break;
797 case MATCH_MOBILE_4G:
798 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
799 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700800 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700801 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
802 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700803 case MATCH_WIFI:
804 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
805 break;
806 default:
807 title = null;
808 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700809 }
810
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800811 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700812 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700813 builder.setTicker(title);
814 builder.setContentTitle(title);
815 builder.setContentText(body);
816
817 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700818 builder.setContentIntent(PendingIntent.getActivity(
819 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700820 break;
821 }
822 }
823
824 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700825 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700826 try {
827 final String packageName = mContext.getPackageName();
828 final int[] idReceived = new int[1];
829 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800830 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Dianne Hackborn41203752012-08-31 14:05:51 -0700831 UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700832 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700833 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700834 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700835 }
836 }
837
838 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700839 * Show ongoing notification to reflect that {@link #mRestrictBackground}
840 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700841 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700842 private void enqueueRestrictedNotification(String tag) {
843 final Resources res = mContext.getResources();
844 final Notification.Builder builder = new Notification.Builder(mContext);
845
846 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
847 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
848
849 builder.setOnlyAlertOnce(true);
850 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700851 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700852 builder.setTicker(title);
853 builder.setContentTitle(title);
854 builder.setContentText(body);
855
856 final Intent intent = buildAllowBackgroundDataIntent();
857 builder.setContentIntent(
858 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700859
860 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700861 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700862 try {
863 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700864 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800865 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Dianne Hackborn41203752012-08-31 14:05:51 -0700866 0x0, builder.getNotification(), idReceived, UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700867 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700868 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700869 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700870 }
871 }
872
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700873 private void cancelNotification(String tag) {
874 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700875 // XXX what to do about multi-user?
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700876 try {
877 final String packageName = mContext.getPackageName();
878 mNotifManager.cancelNotificationWithTag(
Dianne Hackborn41203752012-08-31 14:05:51 -0700879 packageName, tag, 0x0, UserHandle.USER_OWNER);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700880 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700881 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700882 }
883 }
884
885 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700886 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700887 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700888 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700889 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700890 @Override
891 public void onReceive(Context context, Intent intent) {
892 // on background handler thread, and verified CONNECTIVITY_INTERNAL
893 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800894
895 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700896 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700897 ensureActiveMobilePolicyLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700898 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700899 updateNetworkRulesLocked();
900 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700901 }
902 }
903 };
904
905 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700906 * Proactively control network data connections when they exceed
907 * {@link NetworkPolicy#limitBytes}.
908 */
909 private void updateNetworkEnabledLocked() {
910 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
911
912 // TODO: reset any policy-disabled networks when any policy is removed
913 // completely, which is currently rare case.
914
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800915 final long currentTime = currentTimeMillis();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700916 for (NetworkPolicy policy : mNetworkPolicy.values()) {
917 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700918 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700919 setNetworkTemplateEnabled(policy.template, true);
920 continue;
921 }
922
923 final long start = computeLastCycleBoundary(currentTime, policy);
924 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700925 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700926
927 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800928 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
929 && policy.lastLimitSnooze < start;
930 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700931
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800932 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700933 }
934 }
935
936 /**
937 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}
938 * for the given {@link NetworkTemplate}.
939 */
940 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700941 final TelephonyManager tele = TelephonyManager.from(mContext);
942
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700943 switch (template.getMatchRule()) {
944 case MATCH_MOBILE_3G_LOWER:
945 case MATCH_MOBILE_4G:
946 case MATCH_MOBILE_ALL:
947 // TODO: offer more granular control over radio states once
948 // 4965893 is available.
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700949 if (tele.getSimState() == SIM_STATE_READY
950 && Objects.equal(tele.getSubscriberId(), template.getSubscriberId())) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700951 setPolicyDataEnable(TYPE_MOBILE, enabled);
952 setPolicyDataEnable(TYPE_WIMAX, enabled);
953 }
954 break;
955 case MATCH_WIFI:
956 setPolicyDataEnable(TYPE_WIFI, enabled);
957 break;
958 case MATCH_ETHERNET:
959 setPolicyDataEnable(TYPE_ETHERNET, enabled);
960 break;
961 default:
962 throw new IllegalArgumentException("unexpected template");
963 }
964 }
965
966 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700967 * Examine all connected {@link NetworkState}, looking for
968 * {@link NetworkPolicy} that need to be enforced. When matches found, set
969 * remaining quota based on usage cycle and historical stats.
970 */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700971 private void updateNetworkRulesLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700972 if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700973
974 final NetworkState[] states;
975 try {
976 states = mConnManager.getAllNetworkState();
977 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700978 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700979 return;
980 }
981
982 // first, derive identity for all connected networks, which can be used
983 // to match against templates.
984 final HashMap<NetworkIdentity, String> networks = Maps.newHashMap();
985 for (NetworkState state : states) {
986 // stash identity and iface away for later use
987 if (state.networkInfo.isConnected()) {
988 final String iface = state.linkProperties.getInterfaceName();
989 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
990 networks.put(ident, iface);
991 }
992 }
993
994 // build list of rules and ifaces to enforce them against
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700995 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700996 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700997 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700998
999 // collect all active ifaces that match this template
1000 ifaceList.clear();
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001001 for (Map.Entry<NetworkIdentity, String> entry : networks.entrySet()) {
1002 final NetworkIdentity ident = entry.getKey();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001003 if (policy.template.matches(ident)) {
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001004 final String iface = entry.getValue();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001005 ifaceList.add(iface);
1006 }
1007 }
1008
1009 if (ifaceList.size() > 0) {
1010 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001011 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001012 }
1013 }
1014
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001015 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001016 final HashSet<String> newMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001017
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001018 // apply each policy that we found ifaces for; compute remaining data
1019 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001020 final long currentTime = currentTimeMillis();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001021 for (NetworkPolicy policy : mNetworkRules.keySet()) {
1022 final String[] ifaces = mNetworkRules.get(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001023
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001024 final long start;
1025 final long totalBytes;
1026 if (policy.hasCycle()) {
1027 start = computeLastCycleBoundary(currentTime, policy);
1028 totalBytes = getTotalBytes(policy.template, start, currentTime);
1029 } else {
1030 start = Long.MAX_VALUE;
1031 totalBytes = 0;
1032 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001033
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001034 if (LOGD) {
1035 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001036 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001037 }
1038
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001039 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001040 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001041 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001042 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001043 if (!hasLimit) {
1044 // metered network, but no policy limit; we still need to
1045 // restrict apps, so push really high quota.
1046 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001047 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001048 // snoozing past quota, but we still need to restrict apps,
1049 // so push really high quota.
1050 quotaBytes = Long.MAX_VALUE;
1051 } else {
1052 // remaining "quota" bytes are based on total usage in
1053 // current cycle. kernel doesn't like 0-byte rules, so we
1054 // set 1-byte quota and disable the radio later.
1055 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1056 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001057
1058 if (ifaces.length > 1) {
1059 // TODO: switch to shared quota once NMS supports
1060 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001061 }
1062
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001063 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001064 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001065 setInterfaceQuota(iface, quotaBytes);
1066 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001067 }
1068 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001069
1070 // keep track of lowest warning or limit of active policies
1071 if (hasWarning && policy.warningBytes < lowestRule) {
1072 lowestRule = policy.warningBytes;
1073 }
1074 if (hasLimit && policy.limitBytes < lowestRule) {
1075 lowestRule = policy.limitBytes;
1076 }
1077 }
1078
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001079 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001080
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001081 // remove quota on any trailing interfaces
1082 for (String iface : mMeteredIfaces) {
1083 if (!newMeteredIfaces.contains(iface)) {
1084 removeInterfaceQuota(iface);
1085 }
1086 }
1087 mMeteredIfaces = newMeteredIfaces;
1088
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001089 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001090 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001091 }
1092
1093 /**
1094 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1095 * have at least a default mobile policy defined.
1096 */
1097 private void ensureActiveMobilePolicyLocked() {
1098 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001099 if (mSuppressDefaultPolicy) return;
1100
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001101 final TelephonyManager tele = TelephonyManager.from(mContext);
1102
1103 // avoid creating policy when SIM isn't ready
1104 if (tele.getSimState() != SIM_STATE_READY) return;
1105
1106 final String subscriberId = tele.getSubscriberId();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001107 final NetworkIdentity probeIdent = new NetworkIdentity(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001108 TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001109
1110 // examine to see if any policy is defined for active mobile
1111 boolean mobileDefined = false;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001112 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001113 if (policy.template.matches(probeIdent)) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001114 mobileDefined = true;
1115 }
1116 }
1117
1118 if (!mobileDefined) {
1119 Slog.i(TAG, "no policy for active mobile network; generating default policy");
1120
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001121 // build default mobile policy, and assume usage cycle starts today
1122 final long warningBytes = mContext.getResources().getInteger(
1123 com.android.internal.R.integer.config_networkPolicyDefaultWarning)
1124 * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001125
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001126 final Time time = new Time();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001127 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001128
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001129 final int cycleDay = time.monthDay;
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001130 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001131
Jeff Sharkey4e814c32011-07-14 20:37:37 -07001132 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001133 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1134 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1135 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001136 }
1137 }
1138
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001139 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001140 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001141
1142 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001143 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001144 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001145
1146 FileInputStream fis = null;
1147 try {
1148 fis = mPolicyFile.openRead();
1149 final XmlPullParser in = Xml.newPullParser();
1150 in.setInput(fis, null);
1151
1152 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001153 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001154 while ((type = in.next()) != END_DOCUMENT) {
1155 final String tag = in.getName();
1156 if (type == START_TAG) {
1157 if (TAG_POLICY_LIST.equals(tag)) {
1158 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001159 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1160 mRestrictBackground = readBooleanAttribute(
1161 in, ATTR_RESTRICT_BACKGROUND);
1162 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001163 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001164 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001165
1166 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1167 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1168 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001169 final String networkId;
1170 if (version >= VERSION_ADDED_NETWORK_ID) {
1171 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1172 } else {
1173 networkId = null;
1174 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001175 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001176 final String cycleTimezone;
1177 if (version >= VERSION_ADDED_TIMEZONE) {
1178 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1179 } else {
1180 cycleTimezone = Time.TIMEZONE_UTC;
1181 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001182 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1183 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001184 final long lastLimitSnooze;
1185 if (version >= VERSION_SPLIT_SNOOZE) {
1186 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1187 } else if (version >= VERSION_ADDED_SNOOZE) {
1188 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001189 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001190 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001191 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001192 final boolean metered;
1193 if (version >= VERSION_ADDED_METERED) {
1194 metered = readBooleanAttribute(in, ATTR_METERED);
1195 } else {
1196 switch (networkTemplate) {
1197 case MATCH_MOBILE_3G_LOWER:
1198 case MATCH_MOBILE_4G:
1199 case MATCH_MOBILE_ALL:
1200 metered = true;
1201 break;
1202 default:
1203 metered = false;
1204 }
1205 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001206 final long lastWarningSnooze;
1207 if (version >= VERSION_SPLIT_SNOOZE) {
1208 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1209 } else {
1210 lastWarningSnooze = SNOOZE_NEVER;
1211 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001212 final boolean inferred;
1213 if (version >= VERSION_ADDED_INFERRED) {
1214 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1215 } else {
1216 inferred = false;
1217 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001218
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001219 final NetworkTemplate template = new NetworkTemplate(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001220 networkTemplate, subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001221 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001222 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001223 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001224
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001225 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001226 final int uid = readIntAttribute(in, ATTR_UID);
1227 final int policy = readIntAttribute(in, ATTR_POLICY);
1228
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001229 if (UserHandle.isApp(uid)) {
1230 setUidPolicyUnchecked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001231 } else {
1232 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1233 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001234 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001235 final int appId = readIntAttribute(in, ATTR_APP_ID);
1236 final int policy = readIntAttribute(in, ATTR_POLICY);
1237
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001238 // TODO: set for other users during upgrade
1239 final int uid = UserHandle.getUid(UserHandle.USER_OWNER, appId);
1240 if (UserHandle.isApp(uid)) {
1241 setUidPolicyUnchecked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001242 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001243 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001244 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001245 }
1246 }
1247 }
1248
1249 } catch (FileNotFoundException e) {
1250 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001251 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001252 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001253 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001254 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001255 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001256 } finally {
1257 IoUtils.closeQuietly(fis);
1258 }
1259 }
1260
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001261 /**
1262 * Upgrade legacy background data flags, notifying listeners of one last
1263 * change to always-true.
1264 */
1265 private void upgradeLegacyBackgroundData() {
1266 mRestrictBackground = Settings.Secure.getInt(
1267 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1268
1269 // kick off one last broadcast if restricted
1270 if (mRestrictBackground) {
1271 final Intent broadcast = new Intent(
1272 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001273 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001274 }
1275 }
1276
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001277 private void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001278 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001279
1280 FileOutputStream fos = null;
1281 try {
1282 fos = mPolicyFile.startWrite();
1283
1284 XmlSerializer out = new FastXmlSerializer();
1285 out.setOutput(fos, "utf-8");
1286 out.startDocument(null, true);
1287
1288 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001289 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001290 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001291
1292 // write all known network policies
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001293 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001294 final NetworkTemplate template = policy.template;
1295
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001296 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001297 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1298 final String subscriberId = template.getSubscriberId();
1299 if (subscriberId != null) {
1300 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001301 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001302 final String networkId = template.getNetworkId();
1303 if (networkId != null) {
1304 out.attribute(null, ATTR_NETWORK_ID, networkId);
1305 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001306 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001307 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001308 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1309 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001310 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1311 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001312 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001313 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001314 out.endTag(null, TAG_NETWORK_POLICY);
1315 }
1316
1317 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001318 for (int i = 0; i < mUidPolicy.size(); i++) {
1319 final int uid = mUidPolicy.keyAt(i);
1320 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001321
Jeff Sharkey497e4432011-06-14 17:27:29 -07001322 // skip writing empty policies
1323 if (policy == POLICY_NONE) continue;
1324
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001325 out.startTag(null, TAG_UID_POLICY);
1326 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001327 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001328 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001329 }
1330
1331 out.endTag(null, TAG_POLICY_LIST);
1332 out.endDocument();
1333
1334 mPolicyFile.finishWrite(fos);
1335 } catch (IOException e) {
1336 if (fos != null) {
1337 mPolicyFile.failWrite(fos);
1338 }
1339 }
1340 }
1341
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001342 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001343 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001344 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001345
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001346 if (!UserHandle.isApp(uid)) {
1347 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001348 }
1349
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001350 setUidPolicyUnchecked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001351 }
1352
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001353 private void setUidPolicyUnchecked(int uid, int policy, boolean persist) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001354 final int oldPolicy;
Jeff Sharkeya4620792011-05-20 15:29:23 -07001355 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001356 oldPolicy = getUidPolicy(uid);
1357 mUidPolicy.put(uid, policy);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001358
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001359 // uid policy changed, recompute rules and persist policy.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001360 updateRulesForUidLocked(uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001361 if (persist) {
1362 writePolicyLocked();
1363 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001364 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001365 }
1366
1367 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001368 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001369 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1370
Jeff Sharkeya4620792011-05-20 15:29:23 -07001371 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001372 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001373 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001374 }
1375
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001376 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001377 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001378 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1379
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001380 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001381 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001382 for (int i = 0; i < mUidPolicy.size(); i++) {
1383 final int uid = mUidPolicy.keyAt(i);
1384 final int uidPolicy = mUidPolicy.valueAt(i);
1385 if (uidPolicy == policy) {
1386 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001387 }
1388 }
1389 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001390 return uids;
1391 }
1392
1393 /**
1394 * Remove any policies associated with given {@link UserHandle}, persisting
1395 * if any changes are made.
1396 */
1397 private void removePoliciesForUserLocked(int userId) {
1398 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1399
1400 int[] uids = new int[0];
1401 for (int i = 0; i < mUidPolicy.size(); i++) {
1402 final int uid = mUidPolicy.keyAt(i);
1403 if (UserHandle.getUserId(uid) == userId) {
1404 uids = appendInt(uids, uid);
1405 }
1406 }
1407
1408 if (uids.length > 0) {
1409 for (int uid : uids) {
1410 mUidPolicy.delete(uid);
1411 updateRulesForUidLocked(uid);
1412 }
1413 writePolicyLocked();
1414 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001415 }
1416
1417 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001418 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001419 // TODO: create permission for observing network policy
1420 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1421
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001422 mListeners.register(listener);
1423
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001424 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001425 }
1426
1427 @Override
1428 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001429 // TODO: create permission for observing network policy
1430 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1431
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001432 mListeners.unregister(listener);
1433 }
1434
Jeff Sharkey1b861272011-05-22 00:34:52 -07001435 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001436 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001437 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1438
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001439 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001440 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001441 mNetworkPolicy.clear();
1442 for (NetworkPolicy policy : policies) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001443 mNetworkPolicy.put(policy.template, policy);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001444 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001445
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001446 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001447 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001448 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001449 writePolicyLocked();
1450 }
1451 }
1452
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001453 private void addNetworkPolicyLocked(NetworkPolicy policy) {
1454 mNetworkPolicy.put(policy.template, policy);
1455
1456 updateNetworkEnabledLocked();
1457 updateNetworkRulesLocked();
1458 updateNotificationsLocked();
1459 writePolicyLocked();
1460 }
1461
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001462 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001463 public NetworkPolicy[] getNetworkPolicies() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001464 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001465 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001466
1467 synchronized (mRulesLock) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001468 return mNetworkPolicy.values().toArray(new NetworkPolicy[mNetworkPolicy.size()]);
1469 }
1470 }
1471
1472 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001473 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001474 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001475
1476 final long token = Binder.clearCallingIdentity();
1477 try {
1478 performSnooze(template, TYPE_LIMIT);
1479 } finally {
1480 Binder.restoreCallingIdentity(token);
1481 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001482 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001483
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001484 private void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001485 maybeRefreshTrustedTime();
1486 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001487 synchronized (mRulesLock) {
1488 // find and snooze local policy that matches
1489 final NetworkPolicy policy = mNetworkPolicy.get(template);
1490 if (policy == null) {
1491 throw new IllegalArgumentException("unable to find policy for " + template);
1492 }
1493
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001494 switch (type) {
1495 case TYPE_WARNING:
1496 policy.lastWarningSnooze = currentTime;
1497 break;
1498 case TYPE_LIMIT:
1499 policy.lastLimitSnooze = currentTime;
1500 break;
1501 default:
1502 throw new IllegalArgumentException("unexpected type");
1503 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001504
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001505 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001506 updateNetworkRulesLocked();
1507 updateNotificationsLocked();
1508 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001509 }
1510 }
1511
1512 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001513 public void setRestrictBackground(boolean restrictBackground) {
1514 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1515
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001516 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001517 synchronized (mRulesLock) {
1518 mRestrictBackground = restrictBackground;
1519 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001520 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001521 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001522 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001523
1524 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1525 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001526 }
1527
1528 @Override
1529 public boolean getRestrictBackground() {
1530 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1531
1532 synchronized (mRulesLock) {
1533 return mRestrictBackground;
1534 }
1535 }
1536
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001537 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
1538 for (NetworkPolicy policy : mNetworkPolicy.values()) {
1539 if (policy.template.matches(ident)) {
1540 return policy;
1541 }
1542 }
1543 return null;
1544 }
1545
1546 @Override
1547 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1548 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1549
1550 // only returns usage summary, so we don't require caller to have
1551 // READ_NETWORK_USAGE_HISTORY.
1552 final long token = Binder.clearCallingIdentity();
1553 try {
1554 return getNetworkQuotaInfoUnchecked(state);
1555 } finally {
1556 Binder.restoreCallingIdentity(token);
1557 }
1558 }
1559
1560 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1561 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1562
1563 final NetworkPolicy policy;
1564 synchronized (mRulesLock) {
1565 policy = findPolicyForNetworkLocked(ident);
1566 }
1567
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001568 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001569 // missing policy means we can't derive useful quota info
1570 return null;
1571 }
1572
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001573 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001574
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001575 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001576 final long start = computeLastCycleBoundary(currentTime, policy);
1577 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001578 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001579
1580 // report soft and hard limits under policy
1581 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1582 : NetworkQuotaInfo.NO_LIMIT;
1583 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1584 : NetworkQuotaInfo.NO_LIMIT;
1585
1586 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1587 }
1588
Jeff Sharkey46645002011-07-27 21:11:21 -07001589 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001590 public boolean isNetworkMetered(NetworkState state) {
1591 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1592
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001593 // roaming networks are always considered metered
1594 if (ident.getRoaming()) {
1595 return true;
1596 }
1597
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001598 final NetworkPolicy policy;
1599 synchronized (mRulesLock) {
1600 policy = findPolicyForNetworkLocked(ident);
1601 }
1602
1603 if (policy != null) {
1604 return policy.metered;
1605 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001606 final int type = state.networkInfo.getType();
1607 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1608 return true;
1609 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001610 return false;
1611 }
1612 }
1613
1614 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001615 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001616 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001617
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001618 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1619
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001620 final HashSet<String> argSet = new HashSet<String>();
1621 for (String arg : args) {
1622 argSet.add(arg);
1623 }
1624
Jeff Sharkey1b861272011-05-22 00:34:52 -07001625 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001626 if (argSet.contains("--unsnooze")) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001627 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001628 policy.clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001629 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001630
1631 updateNetworkEnabledLocked();
1632 updateNetworkRulesLocked();
1633 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001634 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001635
1636 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001637 return;
1638 }
1639
Jeff Sharkey46645002011-07-27 21:11:21 -07001640 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001641 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001642 fout.increaseIndent();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001643 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001644 fout.println(policy.toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001645 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001646 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001647
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001648 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001649 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001650 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001651 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001652 final int uid = mUidPolicy.keyAt(i);
1653 final int policy = mUidPolicy.valueAt(i);
1654 fout.print("UID=");
1655 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001656 fout.print(" policy=");
1657 dumpPolicy(fout, policy);
1658 fout.println();
1659 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001660 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001661
1662 final SparseBooleanArray knownUids = new SparseBooleanArray();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001663 collectKeys(mUidForeground, knownUids);
1664 collectKeys(mUidRules, knownUids);
1665
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001666 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001667 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001668 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001669 for (int i = 0; i < size; i++) {
1670 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001671 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001672 fout.print(uid);
1673
Jeff Sharkey1b861272011-05-22 00:34:52 -07001674 fout.print(" foreground=");
1675 final int foregroundIndex = mUidPidForeground.indexOfKey(uid);
1676 if (foregroundIndex < 0) {
1677 fout.print("UNKNOWN");
1678 } else {
1679 dumpSparseBooleanArray(fout, mUidPidForeground.valueAt(foregroundIndex));
1680 }
1681
1682 fout.print(" rules=");
1683 final int rulesIndex = mUidRules.indexOfKey(uid);
1684 if (rulesIndex < 0) {
1685 fout.print("UNKNOWN");
1686 } else {
1687 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1688 }
1689
1690 fout.println();
1691 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001692 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001693 }
1694 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001695
1696 @Override
1697 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001698 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1699
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001700 synchronized (mRulesLock) {
1701 // only really in foreground when screen is also on
1702 return mUidForeground.get(uid, false) && mScreenOn;
1703 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001704 }
1705
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001706 /**
1707 * Foreground for PID changed; recompute foreground at UID level. If
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001708 * changed, will trigger {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001709 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001710 private void computeUidForegroundLocked(int uid) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001711 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1712
1713 // current pid is dropping foreground; examine other pids
1714 boolean uidForeground = false;
1715 final int size = pidForeground.size();
1716 for (int i = 0; i < size; i++) {
1717 if (pidForeground.valueAt(i)) {
1718 uidForeground = true;
1719 break;
1720 }
1721 }
1722
1723 final boolean oldUidForeground = mUidForeground.get(uid, false);
1724 if (oldUidForeground != uidForeground) {
1725 // foreground changed, push updated rules
1726 mUidForeground.put(uid, uidForeground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001727 updateRulesForUidLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001728 }
1729 }
1730
Jeff Sharkeya4620792011-05-20 15:29:23 -07001731 private void updateScreenOn() {
1732 synchronized (mRulesLock) {
1733 try {
1734 mScreenOn = mPowerManager.isScreenOn();
1735 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001736 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07001737 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001738 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001739 }
1740 }
1741
1742 /**
1743 * Update rules that might be changed by {@link #mScreenOn} value.
1744 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001745 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07001746 // only update rules for anyone with foreground activities
1747 final int size = mUidForeground.size();
1748 for (int i = 0; i < size; i++) {
1749 if (mUidForeground.valueAt(i)) {
1750 final int uid = mUidForeground.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001751 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001752 }
1753 }
1754 }
1755
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001756 /**
Jeff Sharkey46645002011-07-27 21:11:21 -07001757 * Update rules that might be changed by {@link #mRestrictBackground} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001758 */
Jeff Sharkey46645002011-07-27 21:11:21 -07001759 private void updateRulesForRestrictBackgroundLocked() {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001760 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001761 final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1762
1763 // update rules for all installed applications
1764 final List<UserInfo> users = um.getUsers();
1765 final List<ApplicationInfo> apps = pm.getInstalledApplications(
1766 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
1767
1768 for (UserInfo user : users) {
1769 for (ApplicationInfo app : apps) {
1770 final int uid = UserHandle.getUid(user.id, app.uid);
1771 updateRulesForUidLocked(uid);
1772 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001773 }
1774
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001775 // limit data usage for some internal system services
1776 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
1777 updateRulesForUidLocked(android.os.Process.DRM_UID);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001778 }
1779
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001780 private static boolean isUidValidForRules(int uid) {
1781 // allow rules on specific system services, and any apps
1782 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001783 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001784 return true;
1785 }
1786
1787 return false;
1788 }
1789
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001790 private void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001791 if (!isUidValidForRules(uid)) return;
1792
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001793 final int uidPolicy = getUidPolicy(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001794 final boolean uidForeground = isUidForeground(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001795
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001796 // derive active rules based on policy and active state
1797 int uidRules = RULE_ALLOW_ALL;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001798 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001799 // uid in background, and policy says to block metered data
1800 uidRules = RULE_REJECT_METERED;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001801 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001802 if (!uidForeground && mRestrictBackground) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001803 // uid in background, and global background disabled
1804 uidRules = RULE_REJECT_METERED;
1805 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001806
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001807 // TODO: only dispatch when rules actually change
1808
Jeff Sharkey350083e2011-06-29 10:45:16 -07001809 if (uidRules == RULE_ALLOW_ALL) {
1810 mUidRules.delete(uid);
1811 } else {
1812 mUidRules.put(uid, uidRules);
1813 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001814
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001815 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001816 setUidNetworkRules(uid, rejectMetered);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001817
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001818 // dispatch changed rule to existing listeners
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001819 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001820
1821 try {
1822 // adjust stats accounting based on foreground status
1823 mNetworkStats.setUidForeground(uid, uidForeground);
1824 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001825 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001826 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001827 }
1828
1829 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001830 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001831 public boolean handleMessage(Message msg) {
1832 switch (msg.what) {
1833 case MSG_RULES_CHANGED: {
1834 final int uid = msg.arg1;
1835 final int uidRules = msg.arg2;
1836 final int length = mListeners.beginBroadcast();
1837 for (int i = 0; i < length; i++) {
1838 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1839 if (listener != null) {
1840 try {
1841 listener.onUidRulesChanged(uid, uidRules);
1842 } catch (RemoteException e) {
1843 }
1844 }
1845 }
1846 mListeners.finishBroadcast();
1847 return true;
1848 }
1849 case MSG_METERED_IFACES_CHANGED: {
1850 final String[] meteredIfaces = (String[]) msg.obj;
1851 final int length = mListeners.beginBroadcast();
1852 for (int i = 0; i < length; i++) {
1853 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1854 if (listener != null) {
1855 try {
1856 listener.onMeteredIfacesChanged(meteredIfaces);
1857 } catch (RemoteException e) {
1858 }
1859 }
1860 }
1861 mListeners.finishBroadcast();
1862 return true;
1863 }
Jeff Sharkey6f7af032011-11-01 18:25:15 -07001864 case MSG_FOREGROUND_ACTIVITIES_CHANGED: {
1865 final int pid = msg.arg1;
1866 final int uid = msg.arg2;
1867 final boolean foregroundActivities = (Boolean) msg.obj;
1868
1869 synchronized (mRulesLock) {
1870 // because a uid can have multiple pids running inside, we need to
1871 // remember all pid states and summarize foreground at uid level.
1872
1873 // record foreground for this specific pid
1874 SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1875 if (pidForeground == null) {
1876 pidForeground = new SparseBooleanArray(2);
1877 mUidPidForeground.put(uid, pidForeground);
1878 }
1879 pidForeground.put(pid, foregroundActivities);
1880 computeUidForegroundLocked(uid);
1881 }
1882 return true;
1883 }
1884 case MSG_PROCESS_DIED: {
1885 final int pid = msg.arg1;
1886 final int uid = msg.arg2;
1887
1888 synchronized (mRulesLock) {
1889 // clear records and recompute, when they exist
1890 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1891 if (pidForeground != null) {
1892 pidForeground.delete(pid);
1893 computeUidForegroundLocked(uid);
1894 }
1895 }
1896 return true;
1897 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001898 case MSG_LIMIT_REACHED: {
1899 final String iface = (String) msg.obj;
1900
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001901 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001902 synchronized (mRulesLock) {
1903 if (mMeteredIfaces.contains(iface)) {
1904 try {
1905 // force stats update to make sure we have
1906 // numbers that caused alert to trigger.
1907 mNetworkStats.forceUpdate();
1908 } catch (RemoteException e) {
1909 // ignored; service lives in system_server
1910 }
1911
1912 updateNetworkEnabledLocked();
1913 updateNotificationsLocked();
1914 }
1915 }
1916 return true;
1917 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001918 case MSG_RESTRICT_BACKGROUND_CHANGED: {
1919 final boolean restrictBackground = msg.arg1 != 0;
1920 final int length = mListeners.beginBroadcast();
1921 for (int i = 0; i < length; i++) {
1922 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1923 if (listener != null) {
1924 try {
1925 listener.onRestrictBackgroundChanged(restrictBackground);
1926 } catch (RemoteException e) {
1927 }
1928 }
1929 }
1930 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001931 return true;
1932 }
1933 case MSG_ADVISE_PERSIST_THRESHOLD: {
1934 final long lowestRule = (Long) msg.obj;
1935 try {
1936 // make sure stats are recorded frequently enough; we aim
1937 // for 2MB threshold for 2GB/month rules.
1938 final long persistThreshold = lowestRule / 1000;
1939 mNetworkStats.advisePersistThreshold(persistThreshold);
1940 } catch (RemoteException e) {
1941 // ignored; service lives in system_server
1942 }
1943 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001944 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07001945 case MSG_SCREEN_ON_CHANGED: {
1946 updateScreenOn();
1947 return true;
1948 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001949 default: {
1950 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07001951 }
1952 }
1953 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001954 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001955
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001956 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001957 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001958 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001959 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001960 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001961 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001962 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001963 }
1964 }
1965
1966 private void removeInterfaceQuota(String iface) {
1967 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001968 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001969 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001970 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001971 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001972 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001973 }
1974 }
1975
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001976 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1977 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001978 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001979 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001980 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001981 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001982 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001983 }
1984 }
1985
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001986 /**
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001987 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001988 */
1989 private void setPolicyDataEnable(int networkType, boolean enabled) {
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001990 try {
1991 mConnManager.setPolicyDataEnable(networkType, enabled);
1992 } catch (RemoteException e) {
1993 // ignored; service lives in system_server
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001994 }
1995 }
1996
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001997 private long getTotalBytes(NetworkTemplate template, long start, long end) {
1998 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07001999 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002000 } catch (RuntimeException e) {
2001 Slog.w(TAG, "problem reading network stats: " + e);
2002 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002003 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002004 // ignored; service lives in system_server
2005 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002006 }
2007 }
2008
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002009 private boolean isBandwidthControlEnabled() {
2010 final long token = Binder.clearCallingIdentity();
2011 try {
2012 return mNetworkManager.isBandwidthControlEnabled();
2013 } catch (RemoteException e) {
2014 // ignored; service lives in system_server
2015 return false;
2016 } finally {
2017 Binder.restoreCallingIdentity(token);
2018 }
2019 }
2020
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002021 /**
2022 * Try refreshing {@link #mTime} when stale.
2023 */
2024 private void maybeRefreshTrustedTime() {
2025 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002026 mTime.forceRefresh();
2027 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002028 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002029
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002030 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002031 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2032 }
2033
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002034 private static Intent buildAllowBackgroundDataIntent() {
2035 return new Intent(ACTION_ALLOW_BACKGROUND);
2036 }
2037
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002038 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2039 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2040 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2041 return intent;
2042 }
2043
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002044 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2045 final Intent intent = new Intent();
2046 intent.setComponent(new ComponentName(
2047 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2048 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2049 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2050 return intent;
2051 }
2052
2053 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2054 final Intent intent = new Intent();
2055 intent.setComponent(new ComponentName(
2056 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2057 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2058 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2059 return intent;
2060 }
2061
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002062 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002063 public void addIdleHandler(IdleHandler handler) {
2064 mHandler.getLooper().getQueue().addIdleHandler(handler);
2065 }
2066
Jeff Sharkey1b861272011-05-22 00:34:52 -07002067 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2068 final int size = source.size();
2069 for (int i = 0; i < size; i++) {
2070 target.put(source.keyAt(i), true);
2071 }
2072 }
2073
2074 private static void collectKeys(SparseBooleanArray source, SparseBooleanArray target) {
2075 final int size = source.size();
2076 for (int i = 0; i < size; i++) {
2077 target.put(source.keyAt(i), true);
2078 }
2079 }
2080
2081 private static void dumpSparseBooleanArray(PrintWriter fout, SparseBooleanArray value) {
2082 fout.print("[");
2083 final int size = value.size();
2084 for (int i = 0; i < size; i++) {
2085 fout.print(value.keyAt(i) + "=" + value.valueAt(i));
2086 if (i < size - 1) fout.print(",");
2087 }
2088 fout.print("]");
2089 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002090}