blob: b83933152effe0b5a51c1baf8804167d7cf8fd6f [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.WifiInfo.removeDoubleQuotes;
56import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
57import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
58import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
59import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
60import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
61import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
62import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070063import static android.telephony.TelephonyManager.SIM_STATE_READY;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070064import static android.text.format.DateUtils.DAY_IN_MILLIS;
Jeff Sharkey854b2b12012-04-13 16:03:40 -070065import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070066import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey961e3042011-08-29 16:02:57 -070067import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey46645002011-07-27 21:11:21 -070068import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.readBooleanAttribute;
69import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.readIntAttribute;
70import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.readLongAttribute;
71import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.writeBooleanAttribute;
72import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.writeIntAttribute;
73import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.writeLongAttribute;
Jeff Sharkey497e4432011-06-14 17:27:29 -070074import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070075import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
76import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070077
Jeff Sharkeya4620792011-05-20 15:29:23 -070078import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070079import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070080import android.app.IProcessObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070081import android.app.Notification;
82import android.app.PendingIntent;
Jeff Sharkeya4620792011-05-20 15:29:23 -070083import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070084import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070085import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070086import android.content.Intent;
87import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070088import android.content.pm.ApplicationInfo;
89import android.content.pm.PackageManager;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -070090import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -070091import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070092import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070093import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070094import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070095import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070096import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -070097import android.net.INetworkStatsService;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070098import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070099import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700100import android.net.NetworkPolicy;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700101import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700102import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700103import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700104import android.net.wifi.WifiConfiguration;
105import android.net.wifi.WifiInfo;
106import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700107import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700108import android.os.Environment;
109import android.os.Handler;
110import android.os.HandlerThread;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700111import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700112import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700113import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700114import android.os.MessageQueue.IdleHandler;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700115import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700116import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700117import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700118import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700119import android.provider.Settings;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700120import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700121import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700122import android.text.format.Time;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700123import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700124import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700125import android.util.NtpTrustedTime;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700126import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700127import android.util.SparseArray;
128import android.util.SparseBooleanArray;
129import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700130import android.util.TrustedTime;
131import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700132
Jeff Sharkey497e4432011-06-14 17:27:29 -0700133import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800134import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700135import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700136import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700137import com.android.internal.util.Objects;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700138import com.google.android.collect.Lists;
139import com.google.android.collect.Maps;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700140import com.google.android.collect.Sets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700141
142import org.xmlpull.v1.XmlPullParser;
143import org.xmlpull.v1.XmlPullParserException;
144import org.xmlpull.v1.XmlSerializer;
145
146import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700147import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700148import java.io.FileInputStream;
149import java.io.FileNotFoundException;
150import java.io.FileOutputStream;
151import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700152import java.io.PrintWriter;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700153import java.net.ProtocolException;
154import java.util.ArrayList;
155import java.util.Arrays;
156import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700157import java.util.HashSet;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700158import java.util.List;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700159import java.util.Map;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700160
161import libcore.io.IoUtils;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700162
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700163/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700164 * Service that maintains low-level network policy rules, using
165 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700166 * <p>
167 * Derives active rules by combining a given policy with other system status,
168 * and delivers to listeners, such as {@link ConnectivityManager}, for
169 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700170 */
171public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
172 private static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700173 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700174 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700175
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700176 private static final int VERSION_INIT = 1;
177 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700178 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800179 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800180 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800181 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700182 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700183 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700184 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700185 private static final int VERSION_SWITCH_UID = 10;
186 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700187
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800188 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700189 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800190 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700191 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800192 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700193 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700194
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700195 private static final String TAG_POLICY_LIST = "policy-list";
196 private static final String TAG_NETWORK_POLICY = "network-policy";
197 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700198 private static final String TAG_APP_POLICY = "app-policy";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700199
200 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700201 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700202 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
203 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700204 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700205 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800206 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700207 private static final String ATTR_WARNING_BYTES = "warningBytes";
208 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700209 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800210 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
211 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800212 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700213 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700214 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700215 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700216 private static final String ATTR_POLICY = "policy";
217
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700218 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
219
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800220 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800221 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800222 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800223 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700224
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700225 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
226
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700227 private static final int MSG_RULES_CHANGED = 1;
228 private static final int MSG_METERED_IFACES_CHANGED = 2;
229 private static final int MSG_FOREGROUND_ACTIVITIES_CHANGED = 3;
230 private static final int MSG_PROCESS_DIED = 4;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800231 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800232 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700233 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700234 private static final int MSG_SCREEN_ON_CHANGED = 8;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700235
Jeff Sharkey75279902011-05-24 18:39:45 -0700236 private final Context mContext;
237 private final IActivityManager mActivityManager;
238 private final IPowerManager mPowerManager;
239 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700240 private final INetworkManagementService mNetworkManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700241 private final TrustedTime mTime;
242
243 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700244 private INotificationManager mNotifManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700245
Jeff Sharkey75279902011-05-24 18:39:45 -0700246 private final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700247
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700248 private volatile boolean mScreenOn;
249 private volatile boolean mRestrictBackground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700250
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700251 private final boolean mSuppressDefaultPolicy;
252
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700253 /** Defined network policies. */
254 private HashMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = Maps.newHashMap();
255 /** Currently active network rules for ifaces. */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700256 private HashMap<NetworkPolicy, String[]> mNetworkRules = Maps.newHashMap();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700257
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700258 /** Defined UID policies. */
259 private SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700260 /** Currently derived rules for each UID. */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700261 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700262
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700263 /** Set of ifaces that are metered. */
264 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700265 /** Set of over-limit templates that have been notified. */
266 private HashSet<NetworkTemplate> mOverLimitNotified = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700267
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700268 /** Set of currently active {@link Notification} tags. */
269 private HashSet<String> mActiveNotifs = Sets.newHashSet();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700270
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700271 /** Foreground at both UID and PID granularity. */
Jeff Sharkeya4620792011-05-20 15:29:23 -0700272 private SparseBooleanArray mUidForeground = new SparseBooleanArray();
273 private SparseArray<SparseBooleanArray> mUidPidForeground = new SparseArray<
274 SparseBooleanArray>();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700275
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700276 private final RemoteCallbackList<INetworkPolicyListener> mListeners = new RemoteCallbackList<
277 INetworkPolicyListener>();
278
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700279 private final HandlerThread mHandlerThread;
280 private final Handler mHandler;
281
282 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700283
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700284 // TODO: keep whitelist of system-critical services that should never have
285 // rules enforced, such as system, phone, and radio UIDs.
286
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700287 // TODO: migrate notifications to SystemUI
288
Jeff Sharkey75279902011-05-24 18:39:45 -0700289 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700290 IPowerManager powerManager, INetworkStatsService networkStats,
291 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700292 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700293 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700294 }
295
296 private static File getSystemDir() {
297 return new File(Environment.getDataDirectory(), "system");
298 }
299
300 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700301 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700302 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
303 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700304 mContext = checkNotNull(context, "missing context");
305 mActivityManager = checkNotNull(activityManager, "missing activityManager");
306 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700307 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700308 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700309 mTime = checkNotNull(time, "missing TrustedTime");
310
311 mHandlerThread = new HandlerThread(TAG);
312 mHandlerThread.start();
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700313 mHandler = new Handler(mHandlerThread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700314
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700315 mSuppressDefaultPolicy = suppressDefaultPolicy;
316
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700317 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
318 }
319
320 public void bindConnectivityManager(IConnectivityManager connManager) {
321 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700322 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700323
Jeff Sharkey497e4432011-06-14 17:27:29 -0700324 public void bindNotificationManager(INotificationManager notifManager) {
325 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
326 }
327
Jeff Sharkeya4620792011-05-20 15:29:23 -0700328 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700329 if (!isBandwidthControlEnabled()) {
330 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
331 return;
332 }
333
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700334 synchronized (mRulesLock) {
335 // read policy from disk
336 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700337
338 if (mRestrictBackground) {
339 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700340 updateNotificationsLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700341 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700342 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700343
Jeff Sharkeya4620792011-05-20 15:29:23 -0700344 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700345
Jeff Sharkeya4620792011-05-20 15:29:23 -0700346 try {
347 mActivityManager.registerProcessObserver(mProcessObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700348 mNetworkManager.registerObserver(mAlertObserver);
349 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700350 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700351 }
352
Jeff Sharkeya4620792011-05-20 15:29:23 -0700353 // TODO: traverse existing processes to know foreground state, or have
354 // activitymanager dispatch current state when new observer attached.
355
356 final IntentFilter screenFilter = new IntentFilter();
357 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
358 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700359 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700360
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700361 // watch for network interfaces to be claimed
Jeff Sharkey961e3042011-08-29 16:02:57 -0700362 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION_IMMEDIATE);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700363 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
364
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700365 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700366 final IntentFilter packageFilter = new IntentFilter();
367 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700368 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700369 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700370
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700371 // listen for UID changes to update policy
372 mContext.registerReceiver(
373 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
374
375 // listen for user changes to update policy
376 final IntentFilter userFilter = new IntentFilter();
377 userFilter.addAction(ACTION_USER_ADDED);
378 userFilter.addAction(ACTION_USER_REMOVED);
379 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
380
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700381 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700382 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
383 mContext.registerReceiver(
384 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
385
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700386 // listen for restrict background changes from notifications
387 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
388 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
389
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800390 // listen for snooze warning from notifications
391 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
392 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
393 MANAGE_NETWORK_POLICY, mHandler);
394
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700395 // listen for configured wifi networks to be removed
396 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
397 mContext.registerReceiver(
398 mWifiConfigReceiver, wifiConfigFilter, CONNECTIVITY_INTERNAL, mHandler);
399
400 // listen for wifi state changes to catch metered hint
401 final IntentFilter wifiStateFilter = new IntentFilter(
402 WifiManager.NETWORK_STATE_CHANGED_ACTION);
403 mContext.registerReceiver(
404 mWifiStateReceiver, wifiStateFilter, CONNECTIVITY_INTERNAL, mHandler);
405
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700406 }
407
Jeff Sharkeya4620792011-05-20 15:29:23 -0700408 private IProcessObserver mProcessObserver = new IProcessObserver.Stub() {
409 @Override
410 public void onForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700411 mHandler.obtainMessage(MSG_FOREGROUND_ACTIVITIES_CHANGED,
412 pid, uid, foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700413 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700414
415 @Override
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700416 public void onImportanceChanged(int pid, int uid, int importance) {
417 }
418
419 @Override
Jeff Sharkeya4620792011-05-20 15:29:23 -0700420 public void onProcessDied(int pid, int uid) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700421 mHandler.obtainMessage(MSG_PROCESS_DIED, pid, uid).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700422 }
423 };
424
425 private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
426 @Override
427 public void onReceive(Context context, Intent intent) {
428 synchronized (mRulesLock) {
429 // screen-related broadcasts are protected by system, no need
430 // for permissions check.
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700431 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700432 }
433 }
434 };
435
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700436 private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700437 @Override
438 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700439 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700440
441 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700442 final int uid = intent.getIntExtra(EXTRA_UID, -1);
443 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700444
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700445 if (ACTION_PACKAGE_ADDED.equals(action)) {
446 // update rules for UID, since it might be subject to
447 // global background data policy
448 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
449 synchronized (mRulesLock) {
450 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700451 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700452 }
453 }
454 };
455
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700456 private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
457 @Override
458 public void onReceive(Context context, Intent intent) {
459 // on background handler thread, and UID_REMOVED is protected
460
461 final int uid = intent.getIntExtra(EXTRA_UID, -1);
462 if (uid == -1) return;
463
464 // remove any policy and update rules to clean up
465 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
466 synchronized (mRulesLock) {
467 mUidPolicy.delete(uid);
468 updateRulesForUidLocked(uid);
469 writePolicyLocked();
470 }
471 }
472 };
473
474 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
475 @Override
476 public void onReceive(Context context, Intent intent) {
477 // on background handler thread, and USER_ADDED and USER_REMOVED
478 // broadcasts are protected
479
480 final String action = intent.getAction();
481 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
482 if (userId == -1) return;
483
484 // Remove any policies for given user; both cleaning up after a
485 // USER_REMOVED, and one last sanity check during USER_ADDED
486 removePoliciesForUserLocked(userId);
487
488 // Update global restrict for new user
489 synchronized (mRulesLock) {
490 updateRulesForRestrictBackgroundLocked();
491 }
492 }
493 };
494
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700495 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700496 * Receiver that watches for {@link INetworkStatsService} updates, which we
497 * use to check against {@link NetworkPolicy#warningBytes}.
498 */
499 private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
500 @Override
501 public void onReceive(Context context, Intent intent) {
502 // on background handler thread, and verified
503 // READ_NETWORK_USAGE_HISTORY permission above.
504
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800505 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700506 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700507 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700508 updateNotificationsLocked();
509 }
510 }
511 };
512
513 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700514 * Receiver that watches for {@link Notification} control of
515 * {@link #mRestrictBackground}.
516 */
517 private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
518 @Override
519 public void onReceive(Context context, Intent intent) {
520 // on background handler thread, and verified MANAGE_NETWORK_POLICY
521 // permission above.
522
523 setRestrictBackground(false);
524 }
525 };
526
527 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800528 * Receiver that watches for {@link Notification} control of
529 * {@link NetworkPolicy#lastWarningSnooze}.
530 */
531 private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
532 @Override
533 public void onReceive(Context context, Intent intent) {
534 // on background handler thread, and verified MANAGE_NETWORK_POLICY
535 // permission above.
536
537 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
538 performSnooze(template, TYPE_WARNING);
539 }
540 };
541
542 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700543 * Receiver that watches for {@link WifiConfiguration} to be changed.
544 */
545 private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
546 @Override
547 public void onReceive(Context context, Intent intent) {
548 // on background handler thread, and verified CONNECTIVITY_INTERNAL
549 // permission above.
550
551 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
552 if (reason == CHANGE_REASON_REMOVED) {
553 final WifiConfiguration config = intent.getParcelableExtra(
554 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700555 if (config.SSID != null) {
556 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(
557 removeDoubleQuotes(config.SSID));
558 synchronized (mRulesLock) {
559 if (mNetworkPolicy.containsKey(template)) {
560 mNetworkPolicy.remove(template);
561 writePolicyLocked();
562 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700563 }
564 }
565 }
566 }
567 };
568
569 /**
570 * Receiver that watches {@link WifiInfo} state changes to infer metered
571 * state. Ignores hints when policy is user-defined.
572 */
573 private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
574 @Override
575 public void onReceive(Context context, Intent intent) {
576 // on background handler thread, and verified CONNECTIVITY_INTERNAL
577 // permission above.
578
579 // ignore when not connected
580 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
581 if (!netInfo.isConnected()) return;
582
583 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
584 final boolean meteredHint = info.getMeteredHint();
585
586 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(
587 removeDoubleQuotes(info.getSSID()));
588 synchronized (mRulesLock) {
589 NetworkPolicy policy = mNetworkPolicy.get(template);
590 if (policy == null && meteredHint) {
591 // policy doesn't exist, and AP is hinting that it's
592 // metered: create an inferred policy.
593 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
594 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
595 meteredHint, true);
596 addNetworkPolicyLocked(policy);
597
598 } else if (policy != null && policy.inferred) {
599 // policy exists, and was inferred: update its current
600 // metered state.
601 policy.metered = meteredHint;
602
603 // since this is inferred for each wifi session, just update
604 // rules without persisting.
605 updateNetworkRulesLocked();
606 }
607 }
608 }
609 };
610
611 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700612 * Observer that watches for {@link INetworkManagementService} alerts.
613 */
Jeff Sharkey216c1812012-08-05 14:29:23 -0700614 private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700615 @Override
616 public void limitReached(String limitName, String iface) {
617 // only someone like NMS should be calling us
618 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
619
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800620 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
621 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700622 }
623 }
624 };
625
626 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700627 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
628 * to show visible notifications as needed.
629 */
630 private void updateNotificationsLocked() {
631 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
632
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700633 // keep track of previously active notifications
634 final HashSet<String> beforeNotifs = Sets.newHashSet();
635 beforeNotifs.addAll(mActiveNotifs);
636 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700637
638 // TODO: when switching to kernel notifications, compute next future
639 // cycle boundary to recompute notifications.
640
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700641 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800642 final long currentTime = currentTimeMillis();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700643 for (NetworkPolicy policy : mNetworkPolicy.values()) {
644 // ignore policies that aren't relevant to user
645 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700646 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700647
Jeff Sharkey497e4432011-06-14 17:27:29 -0700648 final long start = computeLastCycleBoundary(currentTime, policy);
649 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700650 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700651
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700652 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800653 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700654 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
655 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700656 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
657 notifyOverLimitLocked(policy.template);
658 }
659
Jeff Sharkey497e4432011-06-14 17:27:29 -0700660 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700661 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700662
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800663 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700664 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700665 }
666 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700667 }
668
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700669 // ongoing notification when restricting background data
670 if (mRestrictBackground) {
671 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700672 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700673
674 // cancel stale notifications that we didn't renew above
675 for (String tag : beforeNotifs) {
676 if (!mActiveNotifs.contains(tag)) {
677 cancelNotification(tag);
678 }
679 }
680 }
681
682 /**
683 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700684 * current device state, such as when
685 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
686 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700687 */
688 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700689 final TelephonyManager tele = TelephonyManager.from(mContext);
690
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700691 switch (template.getMatchRule()) {
692 case MATCH_MOBILE_3G_LOWER:
693 case MATCH_MOBILE_4G:
694 case MATCH_MOBILE_ALL:
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700695 // mobile templates are relevant when SIM is ready and
696 // subscriberId matches.
697 if (tele.getSimState() == SIM_STATE_READY) {
698 return Objects.equal(tele.getSubscriberId(), template.getSubscriberId());
699 } else {
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700700 return false;
701 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700702 }
703 return true;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700704 }
705
706 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700707 * Notify that given {@link NetworkTemplate} is over
708 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
709 */
710 private void notifyOverLimitLocked(NetworkTemplate template) {
711 if (!mOverLimitNotified.contains(template)) {
712 mContext.startActivity(buildNetworkOverLimitIntent(template));
713 mOverLimitNotified.add(template);
714 }
715 }
716
717 private void notifyUnderLimitLocked(NetworkTemplate template) {
718 mOverLimitNotified.remove(template);
719 }
720
721 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700722 * Build unique tag that identifies an active {@link NetworkPolicy}
723 * notification of a specific type, like {@link #TYPE_LIMIT}.
724 */
725 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700726 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700727 }
728
729 /**
730 * Show notification for combined {@link NetworkPolicy} and specific type,
731 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
732 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700733 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700734 final String tag = buildNotificationTag(policy, type);
735 final Notification.Builder builder = new Notification.Builder(mContext);
736 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800737 builder.setWhen(0L);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700738
739 final Resources res = mContext.getResources();
740 switch (type) {
741 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700742 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700743 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700744
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700745 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700746 builder.setTicker(title);
747 builder.setContentTitle(title);
748 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700749
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800750 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
751 builder.setDeleteIntent(PendingIntent.getBroadcast(
752 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
753
754 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700755 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800756 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
757
Jeff Sharkey497e4432011-06-14 17:27:29 -0700758 break;
759 }
760 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700761 final CharSequence body = res.getText(R.string.data_usage_limit_body);
762
763 final CharSequence title;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700764 switch (policy.template.getMatchRule()) {
765 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700766 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700767 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700768 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700769 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700770 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700771 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700772 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700773 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700774 case MATCH_WIFI:
775 title = res.getText(R.string.data_usage_wifi_limit_title);
776 break;
777 default:
778 title = null;
779 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700780 }
781
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800782 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700783 builder.setSmallIcon(R.drawable.stat_notify_disabled);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700784 builder.setTicker(title);
785 builder.setContentTitle(title);
786 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700787
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700788 final Intent intent = buildNetworkOverLimitIntent(policy.template);
789 builder.setContentIntent(PendingIntent.getActivity(
790 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
791 break;
792 }
793 case TYPE_LIMIT_SNOOZED: {
794 final long overBytes = totalBytes - policy.limitBytes;
795 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
796 Formatter.formatFileSize(mContext, overBytes));
797
798 final CharSequence title;
799 switch (policy.template.getMatchRule()) {
800 case MATCH_MOBILE_3G_LOWER:
801 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
802 break;
803 case MATCH_MOBILE_4G:
804 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
805 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700806 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700807 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
808 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700809 case MATCH_WIFI:
810 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
811 break;
812 default:
813 title = null;
814 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700815 }
816
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800817 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700818 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700819 builder.setTicker(title);
820 builder.setContentTitle(title);
821 builder.setContentText(body);
822
823 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700824 builder.setContentIntent(PendingIntent.getActivity(
825 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700826 break;
827 }
828 }
829
830 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700831 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700832 try {
833 final String packageName = mContext.getPackageName();
834 final int[] idReceived = new int[1];
835 mNotifManager.enqueueNotificationWithTag(
Dianne Hackborn41203752012-08-31 14:05:51 -0700836 packageName, tag, 0x0, builder.getNotification(), idReceived,
837 UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700838 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700839 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700840 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700841 }
842 }
843
844 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700845 * Show ongoing notification to reflect that {@link #mRestrictBackground}
846 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700847 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700848 private void enqueueRestrictedNotification(String tag) {
849 final Resources res = mContext.getResources();
850 final Notification.Builder builder = new Notification.Builder(mContext);
851
852 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
853 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
854
855 builder.setOnlyAlertOnce(true);
856 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700857 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700858 builder.setTicker(title);
859 builder.setContentTitle(title);
860 builder.setContentText(body);
861
862 final Intent intent = buildAllowBackgroundDataIntent();
863 builder.setContentIntent(
864 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700865
866 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700867 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700868 try {
869 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700870 final int[] idReceived = new int[1];
871 mNotifManager.enqueueNotificationWithTag(packageName, tag,
Dianne Hackborn41203752012-08-31 14:05:51 -0700872 0x0, builder.getNotification(), idReceived, UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700873 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700874 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700875 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700876 }
877 }
878
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700879 private void cancelNotification(String tag) {
880 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700881 // XXX what to do about multi-user?
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700882 try {
883 final String packageName = mContext.getPackageName();
884 mNotifManager.cancelNotificationWithTag(
Dianne Hackborn41203752012-08-31 14:05:51 -0700885 packageName, tag, 0x0, UserHandle.USER_OWNER);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700886 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700887 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700888 }
889 }
890
891 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700892 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700893 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700894 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700895 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700896 @Override
897 public void onReceive(Context context, Intent intent) {
898 // on background handler thread, and verified CONNECTIVITY_INTERNAL
899 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800900
901 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700902 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700903 ensureActiveMobilePolicyLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700904 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700905 updateNetworkRulesLocked();
906 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700907 }
908 }
909 };
910
911 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700912 * Proactively control network data connections when they exceed
913 * {@link NetworkPolicy#limitBytes}.
914 */
915 private void updateNetworkEnabledLocked() {
916 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
917
918 // TODO: reset any policy-disabled networks when any policy is removed
919 // completely, which is currently rare case.
920
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800921 final long currentTime = currentTimeMillis();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700922 for (NetworkPolicy policy : mNetworkPolicy.values()) {
923 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700924 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700925 setNetworkTemplateEnabled(policy.template, true);
926 continue;
927 }
928
929 final long start = computeLastCycleBoundary(currentTime, policy);
930 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700931 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700932
933 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800934 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
935 && policy.lastLimitSnooze < start;
936 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700937
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800938 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700939 }
940 }
941
942 /**
943 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}
944 * for the given {@link NetworkTemplate}.
945 */
946 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700947 final TelephonyManager tele = TelephonyManager.from(mContext);
948
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700949 switch (template.getMatchRule()) {
950 case MATCH_MOBILE_3G_LOWER:
951 case MATCH_MOBILE_4G:
952 case MATCH_MOBILE_ALL:
953 // TODO: offer more granular control over radio states once
954 // 4965893 is available.
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700955 if (tele.getSimState() == SIM_STATE_READY
956 && Objects.equal(tele.getSubscriberId(), template.getSubscriberId())) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700957 setPolicyDataEnable(TYPE_MOBILE, enabled);
958 setPolicyDataEnable(TYPE_WIMAX, enabled);
959 }
960 break;
961 case MATCH_WIFI:
962 setPolicyDataEnable(TYPE_WIFI, enabled);
963 break;
964 case MATCH_ETHERNET:
965 setPolicyDataEnable(TYPE_ETHERNET, enabled);
966 break;
967 default:
968 throw new IllegalArgumentException("unexpected template");
969 }
970 }
971
972 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700973 * Examine all connected {@link NetworkState}, looking for
974 * {@link NetworkPolicy} that need to be enforced. When matches found, set
975 * remaining quota based on usage cycle and historical stats.
976 */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700977 private void updateNetworkRulesLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700978 if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700979
980 final NetworkState[] states;
981 try {
982 states = mConnManager.getAllNetworkState();
983 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700984 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700985 return;
986 }
987
988 // first, derive identity for all connected networks, which can be used
989 // to match against templates.
990 final HashMap<NetworkIdentity, String> networks = Maps.newHashMap();
991 for (NetworkState state : states) {
992 // stash identity and iface away for later use
993 if (state.networkInfo.isConnected()) {
994 final String iface = state.linkProperties.getInterfaceName();
995 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
996 networks.put(ident, iface);
997 }
998 }
999
1000 // build list of rules and ifaces to enforce them against
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001001 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001002 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001003 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001004
1005 // collect all active ifaces that match this template
1006 ifaceList.clear();
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001007 for (Map.Entry<NetworkIdentity, String> entry : networks.entrySet()) {
1008 final NetworkIdentity ident = entry.getKey();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001009 if (policy.template.matches(ident)) {
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001010 final String iface = entry.getValue();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001011 ifaceList.add(iface);
1012 }
1013 }
1014
1015 if (ifaceList.size() > 0) {
1016 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001017 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001018 }
1019 }
1020
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001021 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001022 final HashSet<String> newMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001023
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001024 // apply each policy that we found ifaces for; compute remaining data
1025 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001026 final long currentTime = currentTimeMillis();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001027 for (NetworkPolicy policy : mNetworkRules.keySet()) {
1028 final String[] ifaces = mNetworkRules.get(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001029
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001030 final long start;
1031 final long totalBytes;
1032 if (policy.hasCycle()) {
1033 start = computeLastCycleBoundary(currentTime, policy);
1034 totalBytes = getTotalBytes(policy.template, start, currentTime);
1035 } else {
1036 start = Long.MAX_VALUE;
1037 totalBytes = 0;
1038 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001039
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001040 if (LOGD) {
1041 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001042 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001043 }
1044
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001045 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001046 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001047 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001048 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001049 if (!hasLimit) {
1050 // metered network, but no policy limit; we still need to
1051 // restrict apps, so push really high quota.
1052 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001053 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001054 // snoozing past quota, but we still need to restrict apps,
1055 // so push really high quota.
1056 quotaBytes = Long.MAX_VALUE;
1057 } else {
1058 // remaining "quota" bytes are based on total usage in
1059 // current cycle. kernel doesn't like 0-byte rules, so we
1060 // set 1-byte quota and disable the radio later.
1061 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1062 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001063
1064 if (ifaces.length > 1) {
1065 // TODO: switch to shared quota once NMS supports
1066 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001067 }
1068
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001069 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001070 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001071 setInterfaceQuota(iface, quotaBytes);
1072 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001073 }
1074 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001075
1076 // keep track of lowest warning or limit of active policies
1077 if (hasWarning && policy.warningBytes < lowestRule) {
1078 lowestRule = policy.warningBytes;
1079 }
1080 if (hasLimit && policy.limitBytes < lowestRule) {
1081 lowestRule = policy.limitBytes;
1082 }
1083 }
1084
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001085 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001086
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001087 // remove quota on any trailing interfaces
1088 for (String iface : mMeteredIfaces) {
1089 if (!newMeteredIfaces.contains(iface)) {
1090 removeInterfaceQuota(iface);
1091 }
1092 }
1093 mMeteredIfaces = newMeteredIfaces;
1094
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001095 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001096 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001097 }
1098
1099 /**
1100 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1101 * have at least a default mobile policy defined.
1102 */
1103 private void ensureActiveMobilePolicyLocked() {
1104 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001105 if (mSuppressDefaultPolicy) return;
1106
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001107 final TelephonyManager tele = TelephonyManager.from(mContext);
1108
1109 // avoid creating policy when SIM isn't ready
1110 if (tele.getSimState() != SIM_STATE_READY) return;
1111
1112 final String subscriberId = tele.getSubscriberId();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001113 final NetworkIdentity probeIdent = new NetworkIdentity(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001114 TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001115
1116 // examine to see if any policy is defined for active mobile
1117 boolean mobileDefined = false;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001118 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001119 if (policy.template.matches(probeIdent)) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001120 mobileDefined = true;
1121 }
1122 }
1123
1124 if (!mobileDefined) {
1125 Slog.i(TAG, "no policy for active mobile network; generating default policy");
1126
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001127 // build default mobile policy, and assume usage cycle starts today
1128 final long warningBytes = mContext.getResources().getInteger(
1129 com.android.internal.R.integer.config_networkPolicyDefaultWarning)
1130 * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001131
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001132 final Time time = new Time();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001133 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001134
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001135 final int cycleDay = time.monthDay;
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001136 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001137
Jeff Sharkey4e814c32011-07-14 20:37:37 -07001138 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001139 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1140 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1141 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001142 }
1143 }
1144
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001145 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001146 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001147
1148 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001149 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001150 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001151
1152 FileInputStream fis = null;
1153 try {
1154 fis = mPolicyFile.openRead();
1155 final XmlPullParser in = Xml.newPullParser();
1156 in.setInput(fis, null);
1157
1158 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001159 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001160 while ((type = in.next()) != END_DOCUMENT) {
1161 final String tag = in.getName();
1162 if (type == START_TAG) {
1163 if (TAG_POLICY_LIST.equals(tag)) {
1164 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001165 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1166 mRestrictBackground = readBooleanAttribute(
1167 in, ATTR_RESTRICT_BACKGROUND);
1168 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001169 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001170 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001171
1172 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1173 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1174 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001175 final String networkId;
1176 if (version >= VERSION_ADDED_NETWORK_ID) {
1177 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1178 } else {
1179 networkId = null;
1180 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001181 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001182 final String cycleTimezone;
1183 if (version >= VERSION_ADDED_TIMEZONE) {
1184 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1185 } else {
1186 cycleTimezone = Time.TIMEZONE_UTC;
1187 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001188 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1189 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001190 final long lastLimitSnooze;
1191 if (version >= VERSION_SPLIT_SNOOZE) {
1192 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1193 } else if (version >= VERSION_ADDED_SNOOZE) {
1194 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001195 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001196 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001197 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001198 final boolean metered;
1199 if (version >= VERSION_ADDED_METERED) {
1200 metered = readBooleanAttribute(in, ATTR_METERED);
1201 } else {
1202 switch (networkTemplate) {
1203 case MATCH_MOBILE_3G_LOWER:
1204 case MATCH_MOBILE_4G:
1205 case MATCH_MOBILE_ALL:
1206 metered = true;
1207 break;
1208 default:
1209 metered = false;
1210 }
1211 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001212 final long lastWarningSnooze;
1213 if (version >= VERSION_SPLIT_SNOOZE) {
1214 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1215 } else {
1216 lastWarningSnooze = SNOOZE_NEVER;
1217 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001218 final boolean inferred;
1219 if (version >= VERSION_ADDED_INFERRED) {
1220 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1221 } else {
1222 inferred = false;
1223 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001224
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001225 final NetworkTemplate template = new NetworkTemplate(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001226 networkTemplate, subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001227 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001228 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001229 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001230
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001231 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001232 final int uid = readIntAttribute(in, ATTR_UID);
1233 final int policy = readIntAttribute(in, ATTR_POLICY);
1234
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001235 if (UserHandle.isApp(uid)) {
1236 setUidPolicyUnchecked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001237 } else {
1238 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1239 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001240 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001241 final int appId = readIntAttribute(in, ATTR_APP_ID);
1242 final int policy = readIntAttribute(in, ATTR_POLICY);
1243
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001244 // TODO: set for other users during upgrade
1245 final int uid = UserHandle.getUid(UserHandle.USER_OWNER, appId);
1246 if (UserHandle.isApp(uid)) {
1247 setUidPolicyUnchecked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001248 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001249 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001250 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001251 }
1252 }
1253 }
1254
1255 } catch (FileNotFoundException e) {
1256 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001257 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001258 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001259 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001260 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001261 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001262 } finally {
1263 IoUtils.closeQuietly(fis);
1264 }
1265 }
1266
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001267 /**
1268 * Upgrade legacy background data flags, notifying listeners of one last
1269 * change to always-true.
1270 */
1271 private void upgradeLegacyBackgroundData() {
1272 mRestrictBackground = Settings.Secure.getInt(
1273 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1274
1275 // kick off one last broadcast if restricted
1276 if (mRestrictBackground) {
1277 final Intent broadcast = new Intent(
1278 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001279 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001280 }
1281 }
1282
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001283 private void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001284 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001285
1286 FileOutputStream fos = null;
1287 try {
1288 fos = mPolicyFile.startWrite();
1289
1290 XmlSerializer out = new FastXmlSerializer();
1291 out.setOutput(fos, "utf-8");
1292 out.startDocument(null, true);
1293
1294 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001295 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001296 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001297
1298 // write all known network policies
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001299 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001300 final NetworkTemplate template = policy.template;
1301
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001302 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001303 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1304 final String subscriberId = template.getSubscriberId();
1305 if (subscriberId != null) {
1306 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001307 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001308 final String networkId = template.getNetworkId();
1309 if (networkId != null) {
1310 out.attribute(null, ATTR_NETWORK_ID, networkId);
1311 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001312 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001313 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001314 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1315 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001316 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1317 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001318 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001319 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001320 out.endTag(null, TAG_NETWORK_POLICY);
1321 }
1322
1323 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001324 for (int i = 0; i < mUidPolicy.size(); i++) {
1325 final int uid = mUidPolicy.keyAt(i);
1326 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001327
Jeff Sharkey497e4432011-06-14 17:27:29 -07001328 // skip writing empty policies
1329 if (policy == POLICY_NONE) continue;
1330
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001331 out.startTag(null, TAG_UID_POLICY);
1332 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001333 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001334 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001335 }
1336
1337 out.endTag(null, TAG_POLICY_LIST);
1338 out.endDocument();
1339
1340 mPolicyFile.finishWrite(fos);
1341 } catch (IOException e) {
1342 if (fos != null) {
1343 mPolicyFile.failWrite(fos);
1344 }
1345 }
1346 }
1347
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001348 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001349 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001350 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001351
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001352 if (!UserHandle.isApp(uid)) {
1353 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001354 }
1355
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001356 setUidPolicyUnchecked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001357 }
1358
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001359 private void setUidPolicyUnchecked(int uid, int policy, boolean persist) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001360 final int oldPolicy;
Jeff Sharkeya4620792011-05-20 15:29:23 -07001361 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001362 oldPolicy = getUidPolicy(uid);
1363 mUidPolicy.put(uid, policy);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001364
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001365 // uid policy changed, recompute rules and persist policy.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001366 updateRulesForUidLocked(uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001367 if (persist) {
1368 writePolicyLocked();
1369 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001370 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001371 }
1372
1373 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001374 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001375 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1376
Jeff Sharkeya4620792011-05-20 15:29:23 -07001377 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001378 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001379 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001380 }
1381
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001382 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001383 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001384 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1385
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001386 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001387 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001388 for (int i = 0; i < mUidPolicy.size(); i++) {
1389 final int uid = mUidPolicy.keyAt(i);
1390 final int uidPolicy = mUidPolicy.valueAt(i);
1391 if (uidPolicy == policy) {
1392 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001393 }
1394 }
1395 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001396 return uids;
1397 }
1398
1399 /**
1400 * Remove any policies associated with given {@link UserHandle}, persisting
1401 * if any changes are made.
1402 */
1403 private void removePoliciesForUserLocked(int userId) {
1404 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1405
1406 int[] uids = new int[0];
1407 for (int i = 0; i < mUidPolicy.size(); i++) {
1408 final int uid = mUidPolicy.keyAt(i);
1409 if (UserHandle.getUserId(uid) == userId) {
1410 uids = appendInt(uids, uid);
1411 }
1412 }
1413
1414 if (uids.length > 0) {
1415 for (int uid : uids) {
1416 mUidPolicy.delete(uid);
1417 updateRulesForUidLocked(uid);
1418 }
1419 writePolicyLocked();
1420 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001421 }
1422
1423 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001424 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001425 // TODO: create permission for observing network policy
1426 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1427
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001428 mListeners.register(listener);
1429
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001430 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001431 }
1432
1433 @Override
1434 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001435 // TODO: create permission for observing network policy
1436 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1437
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001438 mListeners.unregister(listener);
1439 }
1440
Jeff Sharkey1b861272011-05-22 00:34:52 -07001441 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001442 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001443 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1444
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001445 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001446 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001447 mNetworkPolicy.clear();
1448 for (NetworkPolicy policy : policies) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001449 mNetworkPolicy.put(policy.template, policy);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001450 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001451
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001452 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001453 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001454 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001455 writePolicyLocked();
1456 }
1457 }
1458
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001459 private void addNetworkPolicyLocked(NetworkPolicy policy) {
1460 mNetworkPolicy.put(policy.template, policy);
1461
1462 updateNetworkEnabledLocked();
1463 updateNetworkRulesLocked();
1464 updateNotificationsLocked();
1465 writePolicyLocked();
1466 }
1467
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001468 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001469 public NetworkPolicy[] getNetworkPolicies() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001470 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001471 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001472
1473 synchronized (mRulesLock) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001474 return mNetworkPolicy.values().toArray(new NetworkPolicy[mNetworkPolicy.size()]);
1475 }
1476 }
1477
1478 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001479 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001480 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001481
1482 final long token = Binder.clearCallingIdentity();
1483 try {
1484 performSnooze(template, TYPE_LIMIT);
1485 } finally {
1486 Binder.restoreCallingIdentity(token);
1487 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001488 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001489
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001490 private void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001491 maybeRefreshTrustedTime();
1492 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001493 synchronized (mRulesLock) {
1494 // find and snooze local policy that matches
1495 final NetworkPolicy policy = mNetworkPolicy.get(template);
1496 if (policy == null) {
1497 throw new IllegalArgumentException("unable to find policy for " + template);
1498 }
1499
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001500 switch (type) {
1501 case TYPE_WARNING:
1502 policy.lastWarningSnooze = currentTime;
1503 break;
1504 case TYPE_LIMIT:
1505 policy.lastLimitSnooze = currentTime;
1506 break;
1507 default:
1508 throw new IllegalArgumentException("unexpected type");
1509 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001510
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001511 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001512 updateNetworkRulesLocked();
1513 updateNotificationsLocked();
1514 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001515 }
1516 }
1517
1518 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001519 public void setRestrictBackground(boolean restrictBackground) {
1520 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1521
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001522 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001523 synchronized (mRulesLock) {
1524 mRestrictBackground = restrictBackground;
1525 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001526 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001527 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001528 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001529
1530 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1531 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001532 }
1533
1534 @Override
1535 public boolean getRestrictBackground() {
1536 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1537
1538 synchronized (mRulesLock) {
1539 return mRestrictBackground;
1540 }
1541 }
1542
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001543 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
1544 for (NetworkPolicy policy : mNetworkPolicy.values()) {
1545 if (policy.template.matches(ident)) {
1546 return policy;
1547 }
1548 }
1549 return null;
1550 }
1551
1552 @Override
1553 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1554 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1555
1556 // only returns usage summary, so we don't require caller to have
1557 // READ_NETWORK_USAGE_HISTORY.
1558 final long token = Binder.clearCallingIdentity();
1559 try {
1560 return getNetworkQuotaInfoUnchecked(state);
1561 } finally {
1562 Binder.restoreCallingIdentity(token);
1563 }
1564 }
1565
1566 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1567 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1568
1569 final NetworkPolicy policy;
1570 synchronized (mRulesLock) {
1571 policy = findPolicyForNetworkLocked(ident);
1572 }
1573
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001574 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001575 // missing policy means we can't derive useful quota info
1576 return null;
1577 }
1578
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001579 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001580
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001581 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001582 final long start = computeLastCycleBoundary(currentTime, policy);
1583 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001584 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001585
1586 // report soft and hard limits under policy
1587 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1588 : NetworkQuotaInfo.NO_LIMIT;
1589 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1590 : NetworkQuotaInfo.NO_LIMIT;
1591
1592 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1593 }
1594
Jeff Sharkey46645002011-07-27 21:11:21 -07001595 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001596 public boolean isNetworkMetered(NetworkState state) {
1597 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1598
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001599 // roaming networks are always considered metered
1600 if (ident.getRoaming()) {
1601 return true;
1602 }
1603
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001604 final NetworkPolicy policy;
1605 synchronized (mRulesLock) {
1606 policy = findPolicyForNetworkLocked(ident);
1607 }
1608
1609 if (policy != null) {
1610 return policy.metered;
1611 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001612 final int type = state.networkInfo.getType();
1613 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1614 return true;
1615 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001616 return false;
1617 }
1618 }
1619
1620 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001621 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001622 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001623
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001624 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1625
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001626 final HashSet<String> argSet = new HashSet<String>();
1627 for (String arg : args) {
1628 argSet.add(arg);
1629 }
1630
Jeff Sharkey1b861272011-05-22 00:34:52 -07001631 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001632 if (argSet.contains("--unsnooze")) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001633 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001634 policy.clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001635 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001636
1637 updateNetworkEnabledLocked();
1638 updateNetworkRulesLocked();
1639 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001640 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001641
1642 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001643 return;
1644 }
1645
Jeff Sharkey46645002011-07-27 21:11:21 -07001646 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001647 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001648 fout.increaseIndent();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001649 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001650 fout.println(policy.toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001651 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001652 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001653
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001654 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001655 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001656 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001657 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001658 final int uid = mUidPolicy.keyAt(i);
1659 final int policy = mUidPolicy.valueAt(i);
1660 fout.print("UID=");
1661 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001662 fout.print(" policy=");
1663 dumpPolicy(fout, policy);
1664 fout.println();
1665 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001666 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001667
1668 final SparseBooleanArray knownUids = new SparseBooleanArray();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001669 collectKeys(mUidForeground, knownUids);
1670 collectKeys(mUidRules, knownUids);
1671
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001672 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001673 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001674 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001675 for (int i = 0; i < size; i++) {
1676 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001677 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001678 fout.print(uid);
1679
Jeff Sharkey1b861272011-05-22 00:34:52 -07001680 fout.print(" foreground=");
1681 final int foregroundIndex = mUidPidForeground.indexOfKey(uid);
1682 if (foregroundIndex < 0) {
1683 fout.print("UNKNOWN");
1684 } else {
1685 dumpSparseBooleanArray(fout, mUidPidForeground.valueAt(foregroundIndex));
1686 }
1687
1688 fout.print(" rules=");
1689 final int rulesIndex = mUidRules.indexOfKey(uid);
1690 if (rulesIndex < 0) {
1691 fout.print("UNKNOWN");
1692 } else {
1693 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1694 }
1695
1696 fout.println();
1697 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001698 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001699 }
1700 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001701
1702 @Override
1703 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001704 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1705
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001706 synchronized (mRulesLock) {
1707 // only really in foreground when screen is also on
1708 return mUidForeground.get(uid, false) && mScreenOn;
1709 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001710 }
1711
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001712 /**
1713 * Foreground for PID changed; recompute foreground at UID level. If
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001714 * changed, will trigger {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001715 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001716 private void computeUidForegroundLocked(int uid) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001717 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1718
1719 // current pid is dropping foreground; examine other pids
1720 boolean uidForeground = false;
1721 final int size = pidForeground.size();
1722 for (int i = 0; i < size; i++) {
1723 if (pidForeground.valueAt(i)) {
1724 uidForeground = true;
1725 break;
1726 }
1727 }
1728
1729 final boolean oldUidForeground = mUidForeground.get(uid, false);
1730 if (oldUidForeground != uidForeground) {
1731 // foreground changed, push updated rules
1732 mUidForeground.put(uid, uidForeground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001733 updateRulesForUidLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001734 }
1735 }
1736
Jeff Sharkeya4620792011-05-20 15:29:23 -07001737 private void updateScreenOn() {
1738 synchronized (mRulesLock) {
1739 try {
1740 mScreenOn = mPowerManager.isScreenOn();
1741 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001742 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07001743 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001744 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001745 }
1746 }
1747
1748 /**
1749 * Update rules that might be changed by {@link #mScreenOn} value.
1750 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001751 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07001752 // only update rules for anyone with foreground activities
1753 final int size = mUidForeground.size();
1754 for (int i = 0; i < size; i++) {
1755 if (mUidForeground.valueAt(i)) {
1756 final int uid = mUidForeground.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001757 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001758 }
1759 }
1760 }
1761
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001762 /**
Jeff Sharkey46645002011-07-27 21:11:21 -07001763 * Update rules that might be changed by {@link #mRestrictBackground} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001764 */
Jeff Sharkey46645002011-07-27 21:11:21 -07001765 private void updateRulesForRestrictBackgroundLocked() {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001766 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001767 final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1768
1769 // update rules for all installed applications
1770 final List<UserInfo> users = um.getUsers();
1771 final List<ApplicationInfo> apps = pm.getInstalledApplications(
1772 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
1773
1774 for (UserInfo user : users) {
1775 for (ApplicationInfo app : apps) {
1776 final int uid = UserHandle.getUid(user.id, app.uid);
1777 updateRulesForUidLocked(uid);
1778 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001779 }
1780
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001781 // limit data usage for some internal system services
1782 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
1783 updateRulesForUidLocked(android.os.Process.DRM_UID);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001784 }
1785
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001786 private static boolean isUidValidForRules(int uid) {
1787 // allow rules on specific system services, and any apps
1788 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001789 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001790 return true;
1791 }
1792
1793 return false;
1794 }
1795
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001796 private void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001797 if (!isUidValidForRules(uid)) return;
1798
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001799 final int uidPolicy = getUidPolicy(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001800 final boolean uidForeground = isUidForeground(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001801
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001802 // derive active rules based on policy and active state
1803 int uidRules = RULE_ALLOW_ALL;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001804 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001805 // uid in background, and policy says to block metered data
1806 uidRules = RULE_REJECT_METERED;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001807 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001808 if (!uidForeground && mRestrictBackground) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001809 // uid in background, and global background disabled
1810 uidRules = RULE_REJECT_METERED;
1811 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001812
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001813 // TODO: only dispatch when rules actually change
1814
Jeff Sharkey350083e2011-06-29 10:45:16 -07001815 if (uidRules == RULE_ALLOW_ALL) {
1816 mUidRules.delete(uid);
1817 } else {
1818 mUidRules.put(uid, uidRules);
1819 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001820
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001821 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001822 setUidNetworkRules(uid, rejectMetered);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001823
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001824 // dispatch changed rule to existing listeners
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001825 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001826
1827 try {
1828 // adjust stats accounting based on foreground status
1829 mNetworkStats.setUidForeground(uid, uidForeground);
1830 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001831 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001832 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001833 }
1834
1835 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001836 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001837 public boolean handleMessage(Message msg) {
1838 switch (msg.what) {
1839 case MSG_RULES_CHANGED: {
1840 final int uid = msg.arg1;
1841 final int uidRules = msg.arg2;
1842 final int length = mListeners.beginBroadcast();
1843 for (int i = 0; i < length; i++) {
1844 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1845 if (listener != null) {
1846 try {
1847 listener.onUidRulesChanged(uid, uidRules);
1848 } catch (RemoteException e) {
1849 }
1850 }
1851 }
1852 mListeners.finishBroadcast();
1853 return true;
1854 }
1855 case MSG_METERED_IFACES_CHANGED: {
1856 final String[] meteredIfaces = (String[]) msg.obj;
1857 final int length = mListeners.beginBroadcast();
1858 for (int i = 0; i < length; i++) {
1859 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1860 if (listener != null) {
1861 try {
1862 listener.onMeteredIfacesChanged(meteredIfaces);
1863 } catch (RemoteException e) {
1864 }
1865 }
1866 }
1867 mListeners.finishBroadcast();
1868 return true;
1869 }
Jeff Sharkey6f7af032011-11-01 18:25:15 -07001870 case MSG_FOREGROUND_ACTIVITIES_CHANGED: {
1871 final int pid = msg.arg1;
1872 final int uid = msg.arg2;
1873 final boolean foregroundActivities = (Boolean) msg.obj;
1874
1875 synchronized (mRulesLock) {
1876 // because a uid can have multiple pids running inside, we need to
1877 // remember all pid states and summarize foreground at uid level.
1878
1879 // record foreground for this specific pid
1880 SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1881 if (pidForeground == null) {
1882 pidForeground = new SparseBooleanArray(2);
1883 mUidPidForeground.put(uid, pidForeground);
1884 }
1885 pidForeground.put(pid, foregroundActivities);
1886 computeUidForegroundLocked(uid);
1887 }
1888 return true;
1889 }
1890 case MSG_PROCESS_DIED: {
1891 final int pid = msg.arg1;
1892 final int uid = msg.arg2;
1893
1894 synchronized (mRulesLock) {
1895 // clear records and recompute, when they exist
1896 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1897 if (pidForeground != null) {
1898 pidForeground.delete(pid);
1899 computeUidForegroundLocked(uid);
1900 }
1901 }
1902 return true;
1903 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001904 case MSG_LIMIT_REACHED: {
1905 final String iface = (String) msg.obj;
1906
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001907 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001908 synchronized (mRulesLock) {
1909 if (mMeteredIfaces.contains(iface)) {
1910 try {
1911 // force stats update to make sure we have
1912 // numbers that caused alert to trigger.
1913 mNetworkStats.forceUpdate();
1914 } catch (RemoteException e) {
1915 // ignored; service lives in system_server
1916 }
1917
1918 updateNetworkEnabledLocked();
1919 updateNotificationsLocked();
1920 }
1921 }
1922 return true;
1923 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001924 case MSG_RESTRICT_BACKGROUND_CHANGED: {
1925 final boolean restrictBackground = msg.arg1 != 0;
1926 final int length = mListeners.beginBroadcast();
1927 for (int i = 0; i < length; i++) {
1928 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1929 if (listener != null) {
1930 try {
1931 listener.onRestrictBackgroundChanged(restrictBackground);
1932 } catch (RemoteException e) {
1933 }
1934 }
1935 }
1936 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001937 return true;
1938 }
1939 case MSG_ADVISE_PERSIST_THRESHOLD: {
1940 final long lowestRule = (Long) msg.obj;
1941 try {
1942 // make sure stats are recorded frequently enough; we aim
1943 // for 2MB threshold for 2GB/month rules.
1944 final long persistThreshold = lowestRule / 1000;
1945 mNetworkStats.advisePersistThreshold(persistThreshold);
1946 } catch (RemoteException e) {
1947 // ignored; service lives in system_server
1948 }
1949 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001950 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07001951 case MSG_SCREEN_ON_CHANGED: {
1952 updateScreenOn();
1953 return true;
1954 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001955 default: {
1956 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07001957 }
1958 }
1959 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001960 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001961
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001962 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001963 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001964 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001965 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001966 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001967 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001968 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001969 }
1970 }
1971
1972 private void removeInterfaceQuota(String iface) {
1973 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001974 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001975 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001976 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001977 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001978 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001979 }
1980 }
1981
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001982 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1983 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001984 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001985 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001986 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001987 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001988 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001989 }
1990 }
1991
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001992 /**
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001993 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001994 */
1995 private void setPolicyDataEnable(int networkType, boolean enabled) {
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001996 try {
1997 mConnManager.setPolicyDataEnable(networkType, enabled);
1998 } catch (RemoteException e) {
1999 // ignored; service lives in system_server
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002000 }
2001 }
2002
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002003 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2004 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002005 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002006 } catch (RuntimeException e) {
2007 Slog.w(TAG, "problem reading network stats: " + e);
2008 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002009 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002010 // ignored; service lives in system_server
2011 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002012 }
2013 }
2014
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002015 private boolean isBandwidthControlEnabled() {
2016 final long token = Binder.clearCallingIdentity();
2017 try {
2018 return mNetworkManager.isBandwidthControlEnabled();
2019 } catch (RemoteException e) {
2020 // ignored; service lives in system_server
2021 return false;
2022 } finally {
2023 Binder.restoreCallingIdentity(token);
2024 }
2025 }
2026
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002027 /**
2028 * Try refreshing {@link #mTime} when stale.
2029 */
2030 private void maybeRefreshTrustedTime() {
2031 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002032 mTime.forceRefresh();
2033 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002034 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002035
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002036 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002037 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2038 }
2039
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002040 private static Intent buildAllowBackgroundDataIntent() {
2041 return new Intent(ACTION_ALLOW_BACKGROUND);
2042 }
2043
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002044 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2045 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2046 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2047 return intent;
2048 }
2049
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002050 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2051 final Intent intent = new Intent();
2052 intent.setComponent(new ComponentName(
2053 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2054 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2055 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2056 return intent;
2057 }
2058
2059 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2060 final Intent intent = new Intent();
2061 intent.setComponent(new ComponentName(
2062 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2063 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2064 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2065 return intent;
2066 }
2067
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002068 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002069 public void addIdleHandler(IdleHandler handler) {
2070 mHandler.getLooper().getQueue().addIdleHandler(handler);
2071 }
2072
Jeff Sharkey1b861272011-05-22 00:34:52 -07002073 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2074 final int size = source.size();
2075 for (int i = 0; i < size; i++) {
2076 target.put(source.keyAt(i), true);
2077 }
2078 }
2079
2080 private static void collectKeys(SparseBooleanArray source, SparseBooleanArray target) {
2081 final int size = source.size();
2082 for (int i = 0; i < size; i++) {
2083 target.put(source.keyAt(i), true);
2084 }
2085 }
2086
2087 private static void dumpSparseBooleanArray(PrintWriter fout, SparseBooleanArray value) {
2088 fout.print("[");
2089 final int size = value.size();
2090 for (int i = 0; i < size; i++) {
2091 fout.print(value.keyAt(i) + "=" + value.valueAt(i));
2092 if (i < size - 1) fout.print(",");
2093 }
2094 fout.print("]");
2095 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002096
Jeff Sharkey46645002011-07-27 21:11:21 -07002097 public static class XmlUtils {
2098 public static int readIntAttribute(XmlPullParser in, String name) throws IOException {
2099 final String value = in.getAttributeValue(null, name);
2100 try {
2101 return Integer.parseInt(value);
2102 } catch (NumberFormatException e) {
2103 throw new ProtocolException("problem parsing " + name + "=" + value + " as int");
2104 }
2105 }
2106
2107 public static void writeIntAttribute(XmlSerializer out, String name, int value)
2108 throws IOException {
2109 out.attribute(null, name, Integer.toString(value));
2110 }
2111
2112 public static long readLongAttribute(XmlPullParser in, String name) throws IOException {
2113 final String value = in.getAttributeValue(null, name);
2114 try {
2115 return Long.parseLong(value);
2116 } catch (NumberFormatException e) {
2117 throw new ProtocolException("problem parsing " + name + "=" + value + " as long");
2118 }
2119 }
2120
2121 public static void writeLongAttribute(XmlSerializer out, String name, long value)
2122 throws IOException {
2123 out.attribute(null, name, Long.toString(value));
2124 }
2125
2126 public static boolean readBooleanAttribute(XmlPullParser in, String name) {
2127 final String value = in.getAttributeValue(null, name);
2128 return Boolean.parseBoolean(value);
2129 }
2130
2131 public static void writeBooleanAttribute(XmlSerializer out, String name, boolean value)
2132 throws IOException {
2133 out.attribute(null, name, Boolean.toString(value));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002134 }
2135 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002136}