blob: 5ca724298b39c9c44ee07af1909950a17ab1d9b9 [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;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700109import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700110import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700111import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700112import android.os.MessageQueue.IdleHandler;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700113import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700114import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700115import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700116import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700117import android.provider.Settings;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700118import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700119import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700120import android.text.format.Time;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700121import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700122import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700123import android.util.NtpTrustedTime;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700124import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700125import android.util.SparseArray;
126import android.util.SparseBooleanArray;
127import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700128import android.util.TrustedTime;
129import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700130
Jeff Sharkey497e4432011-06-14 17:27:29 -0700131import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800132import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700133import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700134import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700135import com.android.internal.util.Objects;
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700136import com.android.server.IoThread;
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 Handler mHandler;
278
279 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700280
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700281 // TODO: keep whitelist of system-critical services that should never have
282 // rules enforced, such as system, phone, and radio UIDs.
283
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700284 // TODO: migrate notifications to SystemUI
285
Jeff Sharkey75279902011-05-24 18:39:45 -0700286 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700287 IPowerManager powerManager, INetworkStatsService networkStats,
288 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700289 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700290 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700291 }
292
293 private static File getSystemDir() {
294 return new File(Environment.getDataDirectory(), "system");
295 }
296
297 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700298 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700299 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
300 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700301 mContext = checkNotNull(context, "missing context");
302 mActivityManager = checkNotNull(activityManager, "missing activityManager");
303 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700304 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700305 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700306 mTime = checkNotNull(time, "missing TrustedTime");
307
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700308 mHandler = new Handler(IoThread.get().getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700309
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700310 mSuppressDefaultPolicy = suppressDefaultPolicy;
311
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700312 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
313 }
314
315 public void bindConnectivityManager(IConnectivityManager connManager) {
316 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700317 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700318
Jeff Sharkey497e4432011-06-14 17:27:29 -0700319 public void bindNotificationManager(INotificationManager notifManager) {
320 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
321 }
322
Jeff Sharkeya4620792011-05-20 15:29:23 -0700323 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700324 if (!isBandwidthControlEnabled()) {
325 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
326 return;
327 }
328
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700329 synchronized (mRulesLock) {
330 // read policy from disk
331 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700332
333 if (mRestrictBackground) {
334 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700335 updateNotificationsLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700336 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700337 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700338
Jeff Sharkeya4620792011-05-20 15:29:23 -0700339 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700340
Jeff Sharkeya4620792011-05-20 15:29:23 -0700341 try {
342 mActivityManager.registerProcessObserver(mProcessObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700343 mNetworkManager.registerObserver(mAlertObserver);
344 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700345 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700346 }
347
Jeff Sharkeya4620792011-05-20 15:29:23 -0700348 // TODO: traverse existing processes to know foreground state, or have
349 // activitymanager dispatch current state when new observer attached.
350
351 final IntentFilter screenFilter = new IntentFilter();
352 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
353 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700354 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700355
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700356 // watch for network interfaces to be claimed
Jeff Sharkey961e3042011-08-29 16:02:57 -0700357 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION_IMMEDIATE);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700358 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
359
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700360 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700361 final IntentFilter packageFilter = new IntentFilter();
362 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700363 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700364 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700365
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700366 // listen for UID changes to update policy
367 mContext.registerReceiver(
368 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
369
370 // listen for user changes to update policy
371 final IntentFilter userFilter = new IntentFilter();
372 userFilter.addAction(ACTION_USER_ADDED);
373 userFilter.addAction(ACTION_USER_REMOVED);
374 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
375
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700376 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700377 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
378 mContext.registerReceiver(
379 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
380
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700381 // listen for restrict background changes from notifications
382 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
383 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
384
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800385 // listen for snooze warning from notifications
386 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
387 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
388 MANAGE_NETWORK_POLICY, mHandler);
389
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700390 // listen for configured wifi networks to be removed
391 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
392 mContext.registerReceiver(
393 mWifiConfigReceiver, wifiConfigFilter, CONNECTIVITY_INTERNAL, mHandler);
394
395 // listen for wifi state changes to catch metered hint
396 final IntentFilter wifiStateFilter = new IntentFilter(
397 WifiManager.NETWORK_STATE_CHANGED_ACTION);
398 mContext.registerReceiver(
399 mWifiStateReceiver, wifiStateFilter, CONNECTIVITY_INTERNAL, mHandler);
400
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700401 }
402
Jeff Sharkeya4620792011-05-20 15:29:23 -0700403 private IProcessObserver mProcessObserver = new IProcessObserver.Stub() {
404 @Override
405 public void onForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700406 mHandler.obtainMessage(MSG_FOREGROUND_ACTIVITIES_CHANGED,
407 pid, uid, foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700408 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700409
410 @Override
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700411 public void onImportanceChanged(int pid, int uid, int importance) {
412 }
413
414 @Override
Jeff Sharkeya4620792011-05-20 15:29:23 -0700415 public void onProcessDied(int pid, int uid) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700416 mHandler.obtainMessage(MSG_PROCESS_DIED, pid, uid).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700417 }
418 };
419
420 private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
421 @Override
422 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800423 // screen-related broadcasts are protected by system, no need
424 // for permissions check.
425 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700426 }
427 };
428
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700429 private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700430 @Override
431 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700432 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700433
434 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700435 final int uid = intent.getIntExtra(EXTRA_UID, -1);
436 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700437
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700438 if (ACTION_PACKAGE_ADDED.equals(action)) {
439 // update rules for UID, since it might be subject to
440 // global background data policy
441 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
442 synchronized (mRulesLock) {
443 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700444 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700445 }
446 }
447 };
448
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700449 private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
450 @Override
451 public void onReceive(Context context, Intent intent) {
452 // on background handler thread, and UID_REMOVED is protected
453
454 final int uid = intent.getIntExtra(EXTRA_UID, -1);
455 if (uid == -1) return;
456
457 // remove any policy and update rules to clean up
458 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
459 synchronized (mRulesLock) {
460 mUidPolicy.delete(uid);
461 updateRulesForUidLocked(uid);
462 writePolicyLocked();
463 }
464 }
465 };
466
467 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
468 @Override
469 public void onReceive(Context context, Intent intent) {
470 // on background handler thread, and USER_ADDED and USER_REMOVED
471 // broadcasts are protected
472
473 final String action = intent.getAction();
474 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
475 if (userId == -1) return;
476
477 // Remove any policies for given user; both cleaning up after a
478 // USER_REMOVED, and one last sanity check during USER_ADDED
479 removePoliciesForUserLocked(userId);
480
481 // Update global restrict for new user
482 synchronized (mRulesLock) {
483 updateRulesForRestrictBackgroundLocked();
484 }
485 }
486 };
487
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700488 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700489 * Receiver that watches for {@link INetworkStatsService} updates, which we
490 * use to check against {@link NetworkPolicy#warningBytes}.
491 */
492 private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
493 @Override
494 public void onReceive(Context context, Intent intent) {
495 // on background handler thread, and verified
496 // READ_NETWORK_USAGE_HISTORY permission above.
497
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800498 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700499 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700500 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700501 updateNotificationsLocked();
502 }
503 }
504 };
505
506 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700507 * Receiver that watches for {@link Notification} control of
508 * {@link #mRestrictBackground}.
509 */
510 private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
511 @Override
512 public void onReceive(Context context, Intent intent) {
513 // on background handler thread, and verified MANAGE_NETWORK_POLICY
514 // permission above.
515
516 setRestrictBackground(false);
517 }
518 };
519
520 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800521 * Receiver that watches for {@link Notification} control of
522 * {@link NetworkPolicy#lastWarningSnooze}.
523 */
524 private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
525 @Override
526 public void onReceive(Context context, Intent intent) {
527 // on background handler thread, and verified MANAGE_NETWORK_POLICY
528 // permission above.
529
530 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
531 performSnooze(template, TYPE_WARNING);
532 }
533 };
534
535 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700536 * Receiver that watches for {@link WifiConfiguration} to be changed.
537 */
538 private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
539 @Override
540 public void onReceive(Context context, Intent intent) {
541 // on background handler thread, and verified CONNECTIVITY_INTERNAL
542 // permission above.
543
544 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
545 if (reason == CHANGE_REASON_REMOVED) {
546 final WifiConfiguration config = intent.getParcelableExtra(
547 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700548 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800549 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700550 synchronized (mRulesLock) {
551 if (mNetworkPolicy.containsKey(template)) {
552 mNetworkPolicy.remove(template);
553 writePolicyLocked();
554 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700555 }
556 }
557 }
558 }
559 };
560
561 /**
562 * Receiver that watches {@link WifiInfo} state changes to infer metered
563 * state. Ignores hints when policy is user-defined.
564 */
565 private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
566 @Override
567 public void onReceive(Context context, Intent intent) {
568 // on background handler thread, and verified CONNECTIVITY_INTERNAL
569 // permission above.
570
571 // ignore when not connected
572 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
573 if (!netInfo.isConnected()) return;
574
575 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
576 final boolean meteredHint = info.getMeteredHint();
577
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800578 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700579 synchronized (mRulesLock) {
580 NetworkPolicy policy = mNetworkPolicy.get(template);
581 if (policy == null && meteredHint) {
582 // policy doesn't exist, and AP is hinting that it's
583 // metered: create an inferred policy.
584 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
585 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
586 meteredHint, true);
587 addNetworkPolicyLocked(policy);
588
589 } else if (policy != null && policy.inferred) {
590 // policy exists, and was inferred: update its current
591 // metered state.
592 policy.metered = meteredHint;
593
594 // since this is inferred for each wifi session, just update
595 // rules without persisting.
596 updateNetworkRulesLocked();
597 }
598 }
599 }
600 };
601
602 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700603 * Observer that watches for {@link INetworkManagementService} alerts.
604 */
Jeff Sharkey216c1812012-08-05 14:29:23 -0700605 private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700606 @Override
607 public void limitReached(String limitName, String iface) {
608 // only someone like NMS should be calling us
609 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
610
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800611 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
612 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700613 }
614 }
615 };
616
617 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700618 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
619 * to show visible notifications as needed.
620 */
621 private void updateNotificationsLocked() {
622 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
623
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700624 // keep track of previously active notifications
625 final HashSet<String> beforeNotifs = Sets.newHashSet();
626 beforeNotifs.addAll(mActiveNotifs);
627 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700628
629 // TODO: when switching to kernel notifications, compute next future
630 // cycle boundary to recompute notifications.
631
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700632 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800633 final long currentTime = currentTimeMillis();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700634 for (NetworkPolicy policy : mNetworkPolicy.values()) {
635 // ignore policies that aren't relevant to user
636 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700637 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700638
Jeff Sharkey497e4432011-06-14 17:27:29 -0700639 final long start = computeLastCycleBoundary(currentTime, policy);
640 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700641 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700642
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700643 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800644 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700645 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
646 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700647 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
648 notifyOverLimitLocked(policy.template);
649 }
650
Jeff Sharkey497e4432011-06-14 17:27:29 -0700651 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700652 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700653
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800654 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700655 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700656 }
657 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700658 }
659
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700660 // ongoing notification when restricting background data
661 if (mRestrictBackground) {
662 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700663 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700664
665 // cancel stale notifications that we didn't renew above
666 for (String tag : beforeNotifs) {
667 if (!mActiveNotifs.contains(tag)) {
668 cancelNotification(tag);
669 }
670 }
671 }
672
673 /**
674 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700675 * current device state, such as when
676 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
677 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700678 */
679 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700680 final TelephonyManager tele = TelephonyManager.from(mContext);
681
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700682 switch (template.getMatchRule()) {
683 case MATCH_MOBILE_3G_LOWER:
684 case MATCH_MOBILE_4G:
685 case MATCH_MOBILE_ALL:
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700686 // mobile templates are relevant when SIM is ready and
687 // subscriberId matches.
688 if (tele.getSimState() == SIM_STATE_READY) {
689 return Objects.equal(tele.getSubscriberId(), template.getSubscriberId());
690 } else {
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700691 return false;
692 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700693 }
694 return true;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700695 }
696
697 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700698 * Notify that given {@link NetworkTemplate} is over
699 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
700 */
701 private void notifyOverLimitLocked(NetworkTemplate template) {
702 if (!mOverLimitNotified.contains(template)) {
703 mContext.startActivity(buildNetworkOverLimitIntent(template));
704 mOverLimitNotified.add(template);
705 }
706 }
707
708 private void notifyUnderLimitLocked(NetworkTemplate template) {
709 mOverLimitNotified.remove(template);
710 }
711
712 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700713 * Build unique tag that identifies an active {@link NetworkPolicy}
714 * notification of a specific type, like {@link #TYPE_LIMIT}.
715 */
716 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700717 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700718 }
719
720 /**
721 * Show notification for combined {@link NetworkPolicy} and specific type,
722 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
723 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700724 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700725 final String tag = buildNotificationTag(policy, type);
726 final Notification.Builder builder = new Notification.Builder(mContext);
727 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800728 builder.setWhen(0L);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700729
730 final Resources res = mContext.getResources();
731 switch (type) {
732 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700733 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700734 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700735
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700736 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700737 builder.setTicker(title);
738 builder.setContentTitle(title);
739 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700740
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800741 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
742 builder.setDeleteIntent(PendingIntent.getBroadcast(
743 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
744
745 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700746 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800747 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
748
Jeff Sharkey497e4432011-06-14 17:27:29 -0700749 break;
750 }
751 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700752 final CharSequence body = res.getText(R.string.data_usage_limit_body);
753
754 final CharSequence title;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700755 switch (policy.template.getMatchRule()) {
756 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700757 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700758 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700759 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700760 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700761 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700762 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700763 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700764 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700765 case MATCH_WIFI:
766 title = res.getText(R.string.data_usage_wifi_limit_title);
767 break;
768 default:
769 title = null;
770 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700771 }
772
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800773 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700774 builder.setSmallIcon(R.drawable.stat_notify_disabled);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700775 builder.setTicker(title);
776 builder.setContentTitle(title);
777 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700778
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700779 final Intent intent = buildNetworkOverLimitIntent(policy.template);
780 builder.setContentIntent(PendingIntent.getActivity(
781 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
782 break;
783 }
784 case TYPE_LIMIT_SNOOZED: {
785 final long overBytes = totalBytes - policy.limitBytes;
786 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
787 Formatter.formatFileSize(mContext, overBytes));
788
789 final CharSequence title;
790 switch (policy.template.getMatchRule()) {
791 case MATCH_MOBILE_3G_LOWER:
792 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
793 break;
794 case MATCH_MOBILE_4G:
795 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
796 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700797 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700798 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
799 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700800 case MATCH_WIFI:
801 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
802 break;
803 default:
804 title = null;
805 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700806 }
807
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800808 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700809 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700810 builder.setTicker(title);
811 builder.setContentTitle(title);
812 builder.setContentText(body);
813
814 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700815 builder.setContentIntent(PendingIntent.getActivity(
816 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700817 break;
818 }
819 }
820
821 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700822 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700823 try {
824 final String packageName = mContext.getPackageName();
825 final int[] idReceived = new int[1];
826 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800827 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Dianne Hackborn41203752012-08-31 14:05:51 -0700828 UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700829 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700830 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700831 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700832 }
833 }
834
835 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700836 * Show ongoing notification to reflect that {@link #mRestrictBackground}
837 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700838 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700839 private void enqueueRestrictedNotification(String tag) {
840 final Resources res = mContext.getResources();
841 final Notification.Builder builder = new Notification.Builder(mContext);
842
843 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
844 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
845
846 builder.setOnlyAlertOnce(true);
847 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700848 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700849 builder.setTicker(title);
850 builder.setContentTitle(title);
851 builder.setContentText(body);
852
853 final Intent intent = buildAllowBackgroundDataIntent();
854 builder.setContentIntent(
855 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700856
857 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700858 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700859 try {
860 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700861 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800862 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Dianne Hackborn41203752012-08-31 14:05:51 -0700863 0x0, builder.getNotification(), idReceived, UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700864 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700865 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700866 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700867 }
868 }
869
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700870 private void cancelNotification(String tag) {
871 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700872 // XXX what to do about multi-user?
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700873 try {
874 final String packageName = mContext.getPackageName();
875 mNotifManager.cancelNotificationWithTag(
Dianne Hackborn41203752012-08-31 14:05:51 -0700876 packageName, tag, 0x0, UserHandle.USER_OWNER);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700877 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700878 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700879 }
880 }
881
882 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700883 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700884 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700885 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700886 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700887 @Override
888 public void onReceive(Context context, Intent intent) {
889 // on background handler thread, and verified CONNECTIVITY_INTERNAL
890 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800891
892 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700893 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700894 ensureActiveMobilePolicyLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700895 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700896 updateNetworkRulesLocked();
897 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700898 }
899 }
900 };
901
902 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700903 * Proactively control network data connections when they exceed
904 * {@link NetworkPolicy#limitBytes}.
905 */
906 private void updateNetworkEnabledLocked() {
907 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
908
909 // TODO: reset any policy-disabled networks when any policy is removed
910 // completely, which is currently rare case.
911
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800912 final long currentTime = currentTimeMillis();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700913 for (NetworkPolicy policy : mNetworkPolicy.values()) {
914 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700915 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700916 setNetworkTemplateEnabled(policy.template, true);
917 continue;
918 }
919
920 final long start = computeLastCycleBoundary(currentTime, policy);
921 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700922 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700923
924 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800925 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
926 && policy.lastLimitSnooze < start;
927 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700928
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800929 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700930 }
931 }
932
933 /**
934 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}
935 * for the given {@link NetworkTemplate}.
936 */
937 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700938 final TelephonyManager tele = TelephonyManager.from(mContext);
939
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700940 switch (template.getMatchRule()) {
941 case MATCH_MOBILE_3G_LOWER:
942 case MATCH_MOBILE_4G:
943 case MATCH_MOBILE_ALL:
944 // TODO: offer more granular control over radio states once
945 // 4965893 is available.
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700946 if (tele.getSimState() == SIM_STATE_READY
947 && Objects.equal(tele.getSubscriberId(), template.getSubscriberId())) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700948 setPolicyDataEnable(TYPE_MOBILE, enabled);
949 setPolicyDataEnable(TYPE_WIMAX, enabled);
950 }
951 break;
952 case MATCH_WIFI:
953 setPolicyDataEnable(TYPE_WIFI, enabled);
954 break;
955 case MATCH_ETHERNET:
956 setPolicyDataEnable(TYPE_ETHERNET, enabled);
957 break;
958 default:
959 throw new IllegalArgumentException("unexpected template");
960 }
961 }
962
963 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700964 * Examine all connected {@link NetworkState}, looking for
965 * {@link NetworkPolicy} that need to be enforced. When matches found, set
966 * remaining quota based on usage cycle and historical stats.
967 */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700968 private void updateNetworkRulesLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700969 if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700970
971 final NetworkState[] states;
972 try {
973 states = mConnManager.getAllNetworkState();
974 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700975 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700976 return;
977 }
978
979 // first, derive identity for all connected networks, which can be used
980 // to match against templates.
981 final HashMap<NetworkIdentity, String> networks = Maps.newHashMap();
982 for (NetworkState state : states) {
983 // stash identity and iface away for later use
984 if (state.networkInfo.isConnected()) {
985 final String iface = state.linkProperties.getInterfaceName();
986 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
987 networks.put(ident, iface);
988 }
989 }
990
991 // build list of rules and ifaces to enforce them against
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700992 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700993 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700994 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700995
996 // collect all active ifaces that match this template
997 ifaceList.clear();
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700998 for (Map.Entry<NetworkIdentity, String> entry : networks.entrySet()) {
999 final NetworkIdentity ident = entry.getKey();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001000 if (policy.template.matches(ident)) {
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001001 final String iface = entry.getValue();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001002 ifaceList.add(iface);
1003 }
1004 }
1005
1006 if (ifaceList.size() > 0) {
1007 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001008 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001009 }
1010 }
1011
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001012 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001013 final HashSet<String> newMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001014
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001015 // apply each policy that we found ifaces for; compute remaining data
1016 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001017 final long currentTime = currentTimeMillis();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001018 for (NetworkPolicy policy : mNetworkRules.keySet()) {
1019 final String[] ifaces = mNetworkRules.get(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001020
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001021 final long start;
1022 final long totalBytes;
1023 if (policy.hasCycle()) {
1024 start = computeLastCycleBoundary(currentTime, policy);
1025 totalBytes = getTotalBytes(policy.template, start, currentTime);
1026 } else {
1027 start = Long.MAX_VALUE;
1028 totalBytes = 0;
1029 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001030
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001031 if (LOGD) {
1032 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001033 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001034 }
1035
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001036 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001037 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001038 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001039 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001040 if (!hasLimit) {
1041 // metered network, but no policy limit; we still need to
1042 // restrict apps, so push really high quota.
1043 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001044 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001045 // snoozing past quota, but we still need to restrict apps,
1046 // so push really high quota.
1047 quotaBytes = Long.MAX_VALUE;
1048 } else {
1049 // remaining "quota" bytes are based on total usage in
1050 // current cycle. kernel doesn't like 0-byte rules, so we
1051 // set 1-byte quota and disable the radio later.
1052 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1053 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001054
1055 if (ifaces.length > 1) {
1056 // TODO: switch to shared quota once NMS supports
1057 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001058 }
1059
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001060 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001061 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001062 setInterfaceQuota(iface, quotaBytes);
1063 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001064 }
1065 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001066
1067 // keep track of lowest warning or limit of active policies
1068 if (hasWarning && policy.warningBytes < lowestRule) {
1069 lowestRule = policy.warningBytes;
1070 }
1071 if (hasLimit && policy.limitBytes < lowestRule) {
1072 lowestRule = policy.limitBytes;
1073 }
1074 }
1075
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001076 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001077
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001078 // remove quota on any trailing interfaces
1079 for (String iface : mMeteredIfaces) {
1080 if (!newMeteredIfaces.contains(iface)) {
1081 removeInterfaceQuota(iface);
1082 }
1083 }
1084 mMeteredIfaces = newMeteredIfaces;
1085
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001086 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001087 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001088 }
1089
1090 /**
1091 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1092 * have at least a default mobile policy defined.
1093 */
1094 private void ensureActiveMobilePolicyLocked() {
1095 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001096 if (mSuppressDefaultPolicy) return;
1097
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001098 final TelephonyManager tele = TelephonyManager.from(mContext);
1099
1100 // avoid creating policy when SIM isn't ready
1101 if (tele.getSimState() != SIM_STATE_READY) return;
1102
1103 final String subscriberId = tele.getSubscriberId();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001104 final NetworkIdentity probeIdent = new NetworkIdentity(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001105 TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001106
1107 // examine to see if any policy is defined for active mobile
1108 boolean mobileDefined = false;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001109 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001110 if (policy.template.matches(probeIdent)) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001111 mobileDefined = true;
1112 }
1113 }
1114
1115 if (!mobileDefined) {
1116 Slog.i(TAG, "no policy for active mobile network; generating default policy");
1117
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001118 // build default mobile policy, and assume usage cycle starts today
1119 final long warningBytes = mContext.getResources().getInteger(
1120 com.android.internal.R.integer.config_networkPolicyDefaultWarning)
1121 * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001122
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001123 final Time time = new Time();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001124 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001125
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001126 final int cycleDay = time.monthDay;
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001127 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001128
Jeff Sharkey4e814c32011-07-14 20:37:37 -07001129 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001130 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1131 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1132 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001133 }
1134 }
1135
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001136 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001137 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001138
1139 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001140 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001141 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001142
1143 FileInputStream fis = null;
1144 try {
1145 fis = mPolicyFile.openRead();
1146 final XmlPullParser in = Xml.newPullParser();
1147 in.setInput(fis, null);
1148
1149 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001150 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001151 while ((type = in.next()) != END_DOCUMENT) {
1152 final String tag = in.getName();
1153 if (type == START_TAG) {
1154 if (TAG_POLICY_LIST.equals(tag)) {
1155 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001156 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1157 mRestrictBackground = readBooleanAttribute(
1158 in, ATTR_RESTRICT_BACKGROUND);
1159 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001160 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001161 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001162
1163 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1164 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1165 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001166 final String networkId;
1167 if (version >= VERSION_ADDED_NETWORK_ID) {
1168 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1169 } else {
1170 networkId = null;
1171 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001172 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001173 final String cycleTimezone;
1174 if (version >= VERSION_ADDED_TIMEZONE) {
1175 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1176 } else {
1177 cycleTimezone = Time.TIMEZONE_UTC;
1178 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001179 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1180 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001181 final long lastLimitSnooze;
1182 if (version >= VERSION_SPLIT_SNOOZE) {
1183 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1184 } else if (version >= VERSION_ADDED_SNOOZE) {
1185 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001186 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001187 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001188 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001189 final boolean metered;
1190 if (version >= VERSION_ADDED_METERED) {
1191 metered = readBooleanAttribute(in, ATTR_METERED);
1192 } else {
1193 switch (networkTemplate) {
1194 case MATCH_MOBILE_3G_LOWER:
1195 case MATCH_MOBILE_4G:
1196 case MATCH_MOBILE_ALL:
1197 metered = true;
1198 break;
1199 default:
1200 metered = false;
1201 }
1202 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001203 final long lastWarningSnooze;
1204 if (version >= VERSION_SPLIT_SNOOZE) {
1205 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1206 } else {
1207 lastWarningSnooze = SNOOZE_NEVER;
1208 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001209 final boolean inferred;
1210 if (version >= VERSION_ADDED_INFERRED) {
1211 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1212 } else {
1213 inferred = false;
1214 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001215
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001216 final NetworkTemplate template = new NetworkTemplate(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001217 networkTemplate, subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001218 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001219 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001220 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001221
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001222 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001223 final int uid = readIntAttribute(in, ATTR_UID);
1224 final int policy = readIntAttribute(in, ATTR_POLICY);
1225
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001226 if (UserHandle.isApp(uid)) {
1227 setUidPolicyUnchecked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001228 } else {
1229 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1230 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001231 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001232 final int appId = readIntAttribute(in, ATTR_APP_ID);
1233 final int policy = readIntAttribute(in, ATTR_POLICY);
1234
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001235 // TODO: set for other users during upgrade
1236 final int uid = UserHandle.getUid(UserHandle.USER_OWNER, appId);
1237 if (UserHandle.isApp(uid)) {
1238 setUidPolicyUnchecked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001239 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001240 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001241 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001242 }
1243 }
1244 }
1245
1246 } catch (FileNotFoundException e) {
1247 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001248 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001249 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001250 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001251 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001252 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001253 } finally {
1254 IoUtils.closeQuietly(fis);
1255 }
1256 }
1257
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001258 /**
1259 * Upgrade legacy background data flags, notifying listeners of one last
1260 * change to always-true.
1261 */
1262 private void upgradeLegacyBackgroundData() {
1263 mRestrictBackground = Settings.Secure.getInt(
1264 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1265
1266 // kick off one last broadcast if restricted
1267 if (mRestrictBackground) {
1268 final Intent broadcast = new Intent(
1269 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001270 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001271 }
1272 }
1273
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001274 private void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001275 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001276
1277 FileOutputStream fos = null;
1278 try {
1279 fos = mPolicyFile.startWrite();
1280
1281 XmlSerializer out = new FastXmlSerializer();
1282 out.setOutput(fos, "utf-8");
1283 out.startDocument(null, true);
1284
1285 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001286 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001287 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001288
1289 // write all known network policies
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001290 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001291 final NetworkTemplate template = policy.template;
1292
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001293 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001294 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1295 final String subscriberId = template.getSubscriberId();
1296 if (subscriberId != null) {
1297 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001298 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001299 final String networkId = template.getNetworkId();
1300 if (networkId != null) {
1301 out.attribute(null, ATTR_NETWORK_ID, networkId);
1302 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001303 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001304 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001305 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1306 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001307 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1308 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001309 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001310 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001311 out.endTag(null, TAG_NETWORK_POLICY);
1312 }
1313
1314 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001315 for (int i = 0; i < mUidPolicy.size(); i++) {
1316 final int uid = mUidPolicy.keyAt(i);
1317 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001318
Jeff Sharkey497e4432011-06-14 17:27:29 -07001319 // skip writing empty policies
1320 if (policy == POLICY_NONE) continue;
1321
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001322 out.startTag(null, TAG_UID_POLICY);
1323 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001324 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001325 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001326 }
1327
1328 out.endTag(null, TAG_POLICY_LIST);
1329 out.endDocument();
1330
1331 mPolicyFile.finishWrite(fos);
1332 } catch (IOException e) {
1333 if (fos != null) {
1334 mPolicyFile.failWrite(fos);
1335 }
1336 }
1337 }
1338
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001339 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001340 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001341 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001342
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001343 if (!UserHandle.isApp(uid)) {
1344 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001345 }
1346
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001347 setUidPolicyUnchecked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001348 }
1349
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001350 private void setUidPolicyUnchecked(int uid, int policy, boolean persist) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001351 final int oldPolicy;
Jeff Sharkeya4620792011-05-20 15:29:23 -07001352 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001353 oldPolicy = getUidPolicy(uid);
1354 mUidPolicy.put(uid, policy);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001355
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001356 // uid policy changed, recompute rules and persist policy.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001357 updateRulesForUidLocked(uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001358 if (persist) {
1359 writePolicyLocked();
1360 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001361 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001362 }
1363
1364 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001365 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001366 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1367
Jeff Sharkeya4620792011-05-20 15:29:23 -07001368 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001369 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001370 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001371 }
1372
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001373 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001374 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001375 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1376
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001377 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001378 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001379 for (int i = 0; i < mUidPolicy.size(); i++) {
1380 final int uid = mUidPolicy.keyAt(i);
1381 final int uidPolicy = mUidPolicy.valueAt(i);
1382 if (uidPolicy == policy) {
1383 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001384 }
1385 }
1386 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001387 return uids;
1388 }
1389
1390 /**
1391 * Remove any policies associated with given {@link UserHandle}, persisting
1392 * if any changes are made.
1393 */
1394 private void removePoliciesForUserLocked(int userId) {
1395 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1396
1397 int[] uids = new int[0];
1398 for (int i = 0; i < mUidPolicy.size(); i++) {
1399 final int uid = mUidPolicy.keyAt(i);
1400 if (UserHandle.getUserId(uid) == userId) {
1401 uids = appendInt(uids, uid);
1402 }
1403 }
1404
1405 if (uids.length > 0) {
1406 for (int uid : uids) {
1407 mUidPolicy.delete(uid);
1408 updateRulesForUidLocked(uid);
1409 }
1410 writePolicyLocked();
1411 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001412 }
1413
1414 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001415 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001416 // TODO: create permission for observing network policy
1417 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1418
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001419 mListeners.register(listener);
1420
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001421 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001422 }
1423
1424 @Override
1425 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001426 // TODO: create permission for observing network policy
1427 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1428
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001429 mListeners.unregister(listener);
1430 }
1431
Jeff Sharkey1b861272011-05-22 00:34:52 -07001432 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001433 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001434 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1435
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001436 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001437 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001438 mNetworkPolicy.clear();
1439 for (NetworkPolicy policy : policies) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001440 mNetworkPolicy.put(policy.template, policy);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001441 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001442
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001443 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001444 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001445 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001446 writePolicyLocked();
1447 }
1448 }
1449
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001450 private void addNetworkPolicyLocked(NetworkPolicy policy) {
1451 mNetworkPolicy.put(policy.template, policy);
1452
1453 updateNetworkEnabledLocked();
1454 updateNetworkRulesLocked();
1455 updateNotificationsLocked();
1456 writePolicyLocked();
1457 }
1458
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001459 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001460 public NetworkPolicy[] getNetworkPolicies() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001461 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001462 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001463
1464 synchronized (mRulesLock) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001465 return mNetworkPolicy.values().toArray(new NetworkPolicy[mNetworkPolicy.size()]);
1466 }
1467 }
1468
1469 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001470 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001471 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001472
1473 final long token = Binder.clearCallingIdentity();
1474 try {
1475 performSnooze(template, TYPE_LIMIT);
1476 } finally {
1477 Binder.restoreCallingIdentity(token);
1478 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001479 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001480
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001481 private void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001482 maybeRefreshTrustedTime();
1483 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001484 synchronized (mRulesLock) {
1485 // find and snooze local policy that matches
1486 final NetworkPolicy policy = mNetworkPolicy.get(template);
1487 if (policy == null) {
1488 throw new IllegalArgumentException("unable to find policy for " + template);
1489 }
1490
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001491 switch (type) {
1492 case TYPE_WARNING:
1493 policy.lastWarningSnooze = currentTime;
1494 break;
1495 case TYPE_LIMIT:
1496 policy.lastLimitSnooze = currentTime;
1497 break;
1498 default:
1499 throw new IllegalArgumentException("unexpected type");
1500 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001501
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001502 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001503 updateNetworkRulesLocked();
1504 updateNotificationsLocked();
1505 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001506 }
1507 }
1508
1509 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001510 public void setRestrictBackground(boolean restrictBackground) {
1511 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1512
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001513 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001514 synchronized (mRulesLock) {
1515 mRestrictBackground = restrictBackground;
1516 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001517 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001518 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001519 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001520
1521 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1522 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001523 }
1524
1525 @Override
1526 public boolean getRestrictBackground() {
1527 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1528
1529 synchronized (mRulesLock) {
1530 return mRestrictBackground;
1531 }
1532 }
1533
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001534 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
1535 for (NetworkPolicy policy : mNetworkPolicy.values()) {
1536 if (policy.template.matches(ident)) {
1537 return policy;
1538 }
1539 }
1540 return null;
1541 }
1542
1543 @Override
1544 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1545 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1546
1547 // only returns usage summary, so we don't require caller to have
1548 // READ_NETWORK_USAGE_HISTORY.
1549 final long token = Binder.clearCallingIdentity();
1550 try {
1551 return getNetworkQuotaInfoUnchecked(state);
1552 } finally {
1553 Binder.restoreCallingIdentity(token);
1554 }
1555 }
1556
1557 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1558 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1559
1560 final NetworkPolicy policy;
1561 synchronized (mRulesLock) {
1562 policy = findPolicyForNetworkLocked(ident);
1563 }
1564
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001565 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001566 // missing policy means we can't derive useful quota info
1567 return null;
1568 }
1569
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001570 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001571
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001572 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001573 final long start = computeLastCycleBoundary(currentTime, policy);
1574 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001575 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001576
1577 // report soft and hard limits under policy
1578 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1579 : NetworkQuotaInfo.NO_LIMIT;
1580 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1581 : NetworkQuotaInfo.NO_LIMIT;
1582
1583 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1584 }
1585
Jeff Sharkey46645002011-07-27 21:11:21 -07001586 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001587 public boolean isNetworkMetered(NetworkState state) {
1588 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1589
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001590 // roaming networks are always considered metered
1591 if (ident.getRoaming()) {
1592 return true;
1593 }
1594
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001595 final NetworkPolicy policy;
1596 synchronized (mRulesLock) {
1597 policy = findPolicyForNetworkLocked(ident);
1598 }
1599
1600 if (policy != null) {
1601 return policy.metered;
1602 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001603 final int type = state.networkInfo.getType();
1604 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1605 return true;
1606 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001607 return false;
1608 }
1609 }
1610
1611 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001612 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001613 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001614
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001615 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1616
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001617 final HashSet<String> argSet = new HashSet<String>();
1618 for (String arg : args) {
1619 argSet.add(arg);
1620 }
1621
Jeff Sharkey1b861272011-05-22 00:34:52 -07001622 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001623 if (argSet.contains("--unsnooze")) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001624 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001625 policy.clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001626 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001627
1628 updateNetworkEnabledLocked();
1629 updateNetworkRulesLocked();
1630 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001631 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001632
1633 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001634 return;
1635 }
1636
Jeff Sharkey46645002011-07-27 21:11:21 -07001637 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001638 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001639 fout.increaseIndent();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001640 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001641 fout.println(policy.toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001642 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001643 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001644
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001645 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001646 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001647 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001648 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001649 final int uid = mUidPolicy.keyAt(i);
1650 final int policy = mUidPolicy.valueAt(i);
1651 fout.print("UID=");
1652 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001653 fout.print(" policy=");
1654 dumpPolicy(fout, policy);
1655 fout.println();
1656 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001657 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001658
1659 final SparseBooleanArray knownUids = new SparseBooleanArray();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001660 collectKeys(mUidForeground, knownUids);
1661 collectKeys(mUidRules, knownUids);
1662
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001663 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001664 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001665 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001666 for (int i = 0; i < size; i++) {
1667 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001668 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001669 fout.print(uid);
1670
Jeff Sharkey1b861272011-05-22 00:34:52 -07001671 fout.print(" foreground=");
1672 final int foregroundIndex = mUidPidForeground.indexOfKey(uid);
1673 if (foregroundIndex < 0) {
1674 fout.print("UNKNOWN");
1675 } else {
1676 dumpSparseBooleanArray(fout, mUidPidForeground.valueAt(foregroundIndex));
1677 }
1678
1679 fout.print(" rules=");
1680 final int rulesIndex = mUidRules.indexOfKey(uid);
1681 if (rulesIndex < 0) {
1682 fout.print("UNKNOWN");
1683 } else {
1684 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1685 }
1686
1687 fout.println();
1688 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001689 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001690 }
1691 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001692
1693 @Override
1694 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001695 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1696
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001697 synchronized (mRulesLock) {
1698 // only really in foreground when screen is also on
1699 return mUidForeground.get(uid, false) && mScreenOn;
1700 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001701 }
1702
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001703 /**
1704 * Foreground for PID changed; recompute foreground at UID level. If
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001705 * changed, will trigger {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001706 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001707 private void computeUidForegroundLocked(int uid) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001708 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1709
1710 // current pid is dropping foreground; examine other pids
1711 boolean uidForeground = false;
1712 final int size = pidForeground.size();
1713 for (int i = 0; i < size; i++) {
1714 if (pidForeground.valueAt(i)) {
1715 uidForeground = true;
1716 break;
1717 }
1718 }
1719
1720 final boolean oldUidForeground = mUidForeground.get(uid, false);
1721 if (oldUidForeground != uidForeground) {
1722 // foreground changed, push updated rules
1723 mUidForeground.put(uid, uidForeground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001724 updateRulesForUidLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001725 }
1726 }
1727
Jeff Sharkeya4620792011-05-20 15:29:23 -07001728 private void updateScreenOn() {
1729 synchronized (mRulesLock) {
1730 try {
1731 mScreenOn = mPowerManager.isScreenOn();
1732 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001733 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07001734 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001735 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001736 }
1737 }
1738
1739 /**
1740 * Update rules that might be changed by {@link #mScreenOn} value.
1741 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001742 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07001743 // only update rules for anyone with foreground activities
1744 final int size = mUidForeground.size();
1745 for (int i = 0; i < size; i++) {
1746 if (mUidForeground.valueAt(i)) {
1747 final int uid = mUidForeground.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001748 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001749 }
1750 }
1751 }
1752
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001753 /**
Jeff Sharkey46645002011-07-27 21:11:21 -07001754 * Update rules that might be changed by {@link #mRestrictBackground} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001755 */
Jeff Sharkey46645002011-07-27 21:11:21 -07001756 private void updateRulesForRestrictBackgroundLocked() {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001757 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001758 final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1759
1760 // update rules for all installed applications
1761 final List<UserInfo> users = um.getUsers();
1762 final List<ApplicationInfo> apps = pm.getInstalledApplications(
1763 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
1764
1765 for (UserInfo user : users) {
1766 for (ApplicationInfo app : apps) {
1767 final int uid = UserHandle.getUid(user.id, app.uid);
1768 updateRulesForUidLocked(uid);
1769 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001770 }
1771
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001772 // limit data usage for some internal system services
1773 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
1774 updateRulesForUidLocked(android.os.Process.DRM_UID);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001775 }
1776
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001777 private static boolean isUidValidForRules(int uid) {
1778 // allow rules on specific system services, and any apps
1779 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001780 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001781 return true;
1782 }
1783
1784 return false;
1785 }
1786
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001787 private void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001788 if (!isUidValidForRules(uid)) return;
1789
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001790 final int uidPolicy = getUidPolicy(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001791 final boolean uidForeground = isUidForeground(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001792
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001793 // derive active rules based on policy and active state
1794 int uidRules = RULE_ALLOW_ALL;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001795 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001796 // uid in background, and policy says to block metered data
1797 uidRules = RULE_REJECT_METERED;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001798 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001799 if (!uidForeground && mRestrictBackground) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001800 // uid in background, and global background disabled
1801 uidRules = RULE_REJECT_METERED;
1802 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001803
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001804 // TODO: only dispatch when rules actually change
1805
Jeff Sharkey350083e2011-06-29 10:45:16 -07001806 if (uidRules == RULE_ALLOW_ALL) {
1807 mUidRules.delete(uid);
1808 } else {
1809 mUidRules.put(uid, uidRules);
1810 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001811
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001812 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001813 setUidNetworkRules(uid, rejectMetered);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001814
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001815 // dispatch changed rule to existing listeners
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001816 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001817
1818 try {
1819 // adjust stats accounting based on foreground status
1820 mNetworkStats.setUidForeground(uid, uidForeground);
1821 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001822 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001823 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001824 }
1825
1826 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001827 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001828 public boolean handleMessage(Message msg) {
1829 switch (msg.what) {
1830 case MSG_RULES_CHANGED: {
1831 final int uid = msg.arg1;
1832 final int uidRules = msg.arg2;
1833 final int length = mListeners.beginBroadcast();
1834 for (int i = 0; i < length; i++) {
1835 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1836 if (listener != null) {
1837 try {
1838 listener.onUidRulesChanged(uid, uidRules);
1839 } catch (RemoteException e) {
1840 }
1841 }
1842 }
1843 mListeners.finishBroadcast();
1844 return true;
1845 }
1846 case MSG_METERED_IFACES_CHANGED: {
1847 final String[] meteredIfaces = (String[]) msg.obj;
1848 final int length = mListeners.beginBroadcast();
1849 for (int i = 0; i < length; i++) {
1850 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1851 if (listener != null) {
1852 try {
1853 listener.onMeteredIfacesChanged(meteredIfaces);
1854 } catch (RemoteException e) {
1855 }
1856 }
1857 }
1858 mListeners.finishBroadcast();
1859 return true;
1860 }
Jeff Sharkey6f7af032011-11-01 18:25:15 -07001861 case MSG_FOREGROUND_ACTIVITIES_CHANGED: {
1862 final int pid = msg.arg1;
1863 final int uid = msg.arg2;
1864 final boolean foregroundActivities = (Boolean) msg.obj;
1865
1866 synchronized (mRulesLock) {
1867 // because a uid can have multiple pids running inside, we need to
1868 // remember all pid states and summarize foreground at uid level.
1869
1870 // record foreground for this specific pid
1871 SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1872 if (pidForeground == null) {
1873 pidForeground = new SparseBooleanArray(2);
1874 mUidPidForeground.put(uid, pidForeground);
1875 }
1876 pidForeground.put(pid, foregroundActivities);
1877 computeUidForegroundLocked(uid);
1878 }
1879 return true;
1880 }
1881 case MSG_PROCESS_DIED: {
1882 final int pid = msg.arg1;
1883 final int uid = msg.arg2;
1884
1885 synchronized (mRulesLock) {
1886 // clear records and recompute, when they exist
1887 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1888 if (pidForeground != null) {
1889 pidForeground.delete(pid);
1890 computeUidForegroundLocked(uid);
1891 }
1892 }
1893 return true;
1894 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001895 case MSG_LIMIT_REACHED: {
1896 final String iface = (String) msg.obj;
1897
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001898 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001899 synchronized (mRulesLock) {
1900 if (mMeteredIfaces.contains(iface)) {
1901 try {
1902 // force stats update to make sure we have
1903 // numbers that caused alert to trigger.
1904 mNetworkStats.forceUpdate();
1905 } catch (RemoteException e) {
1906 // ignored; service lives in system_server
1907 }
1908
1909 updateNetworkEnabledLocked();
1910 updateNotificationsLocked();
1911 }
1912 }
1913 return true;
1914 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001915 case MSG_RESTRICT_BACKGROUND_CHANGED: {
1916 final boolean restrictBackground = msg.arg1 != 0;
1917 final int length = mListeners.beginBroadcast();
1918 for (int i = 0; i < length; i++) {
1919 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1920 if (listener != null) {
1921 try {
1922 listener.onRestrictBackgroundChanged(restrictBackground);
1923 } catch (RemoteException e) {
1924 }
1925 }
1926 }
1927 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001928 return true;
1929 }
1930 case MSG_ADVISE_PERSIST_THRESHOLD: {
1931 final long lowestRule = (Long) msg.obj;
1932 try {
1933 // make sure stats are recorded frequently enough; we aim
1934 // for 2MB threshold for 2GB/month rules.
1935 final long persistThreshold = lowestRule / 1000;
1936 mNetworkStats.advisePersistThreshold(persistThreshold);
1937 } catch (RemoteException e) {
1938 // ignored; service lives in system_server
1939 }
1940 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001941 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07001942 case MSG_SCREEN_ON_CHANGED: {
1943 updateScreenOn();
1944 return true;
1945 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001946 default: {
1947 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07001948 }
1949 }
1950 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001951 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001952
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001953 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001954 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001955 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001956 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001957 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001958 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001959 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001960 }
1961 }
1962
1963 private void removeInterfaceQuota(String iface) {
1964 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001965 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001966 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001967 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001968 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001969 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001970 }
1971 }
1972
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001973 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1974 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001975 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001976 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001977 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001978 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001979 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001980 }
1981 }
1982
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001983 /**
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001984 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001985 */
1986 private void setPolicyDataEnable(int networkType, boolean enabled) {
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001987 try {
1988 mConnManager.setPolicyDataEnable(networkType, enabled);
1989 } catch (RemoteException e) {
1990 // ignored; service lives in system_server
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001991 }
1992 }
1993
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001994 private long getTotalBytes(NetworkTemplate template, long start, long end) {
1995 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07001996 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001997 } catch (RuntimeException e) {
1998 Slog.w(TAG, "problem reading network stats: " + e);
1999 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002000 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002001 // ignored; service lives in system_server
2002 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002003 }
2004 }
2005
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002006 private boolean isBandwidthControlEnabled() {
2007 final long token = Binder.clearCallingIdentity();
2008 try {
2009 return mNetworkManager.isBandwidthControlEnabled();
2010 } catch (RemoteException e) {
2011 // ignored; service lives in system_server
2012 return false;
2013 } finally {
2014 Binder.restoreCallingIdentity(token);
2015 }
2016 }
2017
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002018 /**
2019 * Try refreshing {@link #mTime} when stale.
2020 */
2021 private void maybeRefreshTrustedTime() {
2022 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002023 mTime.forceRefresh();
2024 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002025 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002026
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002027 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002028 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2029 }
2030
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002031 private static Intent buildAllowBackgroundDataIntent() {
2032 return new Intent(ACTION_ALLOW_BACKGROUND);
2033 }
2034
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002035 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2036 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2037 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2038 return intent;
2039 }
2040
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002041 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2042 final Intent intent = new Intent();
2043 intent.setComponent(new ComponentName(
2044 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2045 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2046 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2047 return intent;
2048 }
2049
2050 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2051 final Intent intent = new Intent();
2052 intent.setComponent(new ComponentName(
2053 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2054 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2055 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2056 return intent;
2057 }
2058
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002059 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002060 public void addIdleHandler(IdleHandler handler) {
2061 mHandler.getLooper().getQueue().addIdleHandler(handler);
2062 }
2063
Jeff Sharkey1b861272011-05-22 00:34:52 -07002064 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2065 final int size = source.size();
2066 for (int i = 0; i < size; i++) {
2067 target.put(source.keyAt(i), true);
2068 }
2069 }
2070
2071 private static void collectKeys(SparseBooleanArray source, SparseBooleanArray target) {
2072 final int size = source.size();
2073 for (int i = 0; i < size; i++) {
2074 target.put(source.keyAt(i), true);
2075 }
2076 }
2077
2078 private static void dumpSparseBooleanArray(PrintWriter fout, SparseBooleanArray value) {
2079 fout.print("[");
2080 final int size = value.size();
2081 for (int i = 0; i < size; i++) {
2082 fout.print(value.keyAt(i) + "=" + value.valueAt(i));
2083 if (i < size - 1) fout.print(",");
2084 }
2085 fout.print("]");
2086 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002087}