blob: 3ae652a473d8d313018ec5e1e79639ecefa18ed0 [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey1b861272011-05-22 00:34:52 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070022import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070025import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070026import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070027import static android.content.Intent.ACTION_USER_ADDED;
28import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070029import static android.content.Intent.EXTRA_UID;
Jeff Sharkey961e3042011-08-29 16:02:57 -070030import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070031import static android.net.ConnectivityManager.TYPE_ETHERNET;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070032import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070033import static android.net.ConnectivityManager.TYPE_WIFI;
34import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070035import static android.net.ConnectivityManager.isNetworkTypeMobile;
36import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070037import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070038import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070039import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070040import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070041import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070042import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070043import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070044import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070045import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Jeff Sharkey1b861272011-05-22 00:34:52 -070046import static android.net.NetworkPolicyManager.dumpPolicy;
47import static android.net.NetworkPolicyManager.dumpRules;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070048import static android.net.NetworkTemplate.MATCH_ETHERNET;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070049import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
50import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070051import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
52import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070053import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080054import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070055import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
56import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
57import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
58import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
59import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
60import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
61import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070062import static android.telephony.TelephonyManager.SIM_STATE_READY;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070063import static android.text.format.DateUtils.DAY_IN_MILLIS;
Jeff Sharkey854b2b12012-04-13 16:03:40 -070064import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070065import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey961e3042011-08-29 16:02:57 -070066import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey46645002011-07-27 21:11:21 -070067import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.readBooleanAttribute;
68import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.readIntAttribute;
69import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.readLongAttribute;
70import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.writeBooleanAttribute;
71import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.writeIntAttribute;
72import static com.android.server.net.NetworkPolicyManagerService.XmlUtils.writeLongAttribute;
Jeff Sharkey497e4432011-06-14 17:27:29 -070073import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070074import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
75import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070076
Jeff Sharkeya4620792011-05-20 15:29:23 -070077import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070078import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070079import android.app.IProcessObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070080import android.app.Notification;
81import android.app.PendingIntent;
Jeff Sharkeya4620792011-05-20 15:29:23 -070082import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070083import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070084import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070085import android.content.Intent;
86import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070087import android.content.pm.ApplicationInfo;
88import android.content.pm.PackageManager;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -070089import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -070090import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070091import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070092import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070093import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070094import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070095import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -070096import android.net.INetworkStatsService;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070097import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070098import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070099import android.net.NetworkPolicy;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700100import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700101import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700102import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700103import android.net.wifi.WifiConfiguration;
104import android.net.wifi.WifiInfo;
105import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700106import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700107import android.os.Environment;
108import android.os.Handler;
109import android.os.HandlerThread;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700110import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700111import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700112import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700113import android.os.MessageQueue.IdleHandler;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700114import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700115import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700116import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700117import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700118import android.provider.Settings;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700119import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700120import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700121import android.text.format.Time;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700122import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700123import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700124import android.util.NtpTrustedTime;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700125import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700126import android.util.SparseArray;
127import android.util.SparseBooleanArray;
128import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700129import android.util.TrustedTime;
130import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700131
Jeff Sharkey497e4432011-06-14 17:27:29 -0700132import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800133import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700134import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700135import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700136import com.android.internal.util.Objects;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700137import com.google.android.collect.Lists;
138import com.google.android.collect.Maps;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700139import com.google.android.collect.Sets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700140
141import org.xmlpull.v1.XmlPullParser;
142import org.xmlpull.v1.XmlPullParserException;
143import org.xmlpull.v1.XmlSerializer;
144
145import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700146import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700147import java.io.FileInputStream;
148import java.io.FileNotFoundException;
149import java.io.FileOutputStream;
150import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700151import java.io.PrintWriter;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700152import java.net.ProtocolException;
153import java.util.ArrayList;
154import java.util.Arrays;
155import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700156import java.util.HashSet;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700157import java.util.List;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700158import java.util.Map;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700159
160import libcore.io.IoUtils;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700161
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700162/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700163 * Service that maintains low-level network policy rules, using
164 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700165 * <p>
166 * Derives active rules by combining a given policy with other system status,
167 * and delivers to listeners, such as {@link ConnectivityManager}, for
168 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700169 */
170public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
171 private static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700172 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700173 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700174
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700175 private static final int VERSION_INIT = 1;
176 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700177 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800178 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800179 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800180 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700181 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700182 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700183 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700184 private static final int VERSION_SWITCH_UID = 10;
185 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700186
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800187 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700188 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800189 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700190 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800191 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700192 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700193
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700194 private static final String TAG_POLICY_LIST = "policy-list";
195 private static final String TAG_NETWORK_POLICY = "network-policy";
196 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700197 private static final String TAG_APP_POLICY = "app-policy";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700198
199 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700200 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700201 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
202 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700203 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700204 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800205 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700206 private static final String ATTR_WARNING_BYTES = "warningBytes";
207 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700208 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800209 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
210 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800211 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700212 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700213 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700214 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700215 private static final String ATTR_POLICY = "policy";
216
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700217 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
218
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800219 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800220 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800221 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800222 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700223
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700224 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
225
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700226 private static final int MSG_RULES_CHANGED = 1;
227 private static final int MSG_METERED_IFACES_CHANGED = 2;
228 private static final int MSG_FOREGROUND_ACTIVITIES_CHANGED = 3;
229 private static final int MSG_PROCESS_DIED = 4;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800230 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800231 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700232 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700233 private static final int MSG_SCREEN_ON_CHANGED = 8;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700234
Jeff Sharkey75279902011-05-24 18:39:45 -0700235 private final Context mContext;
236 private final IActivityManager mActivityManager;
237 private final IPowerManager mPowerManager;
238 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700239 private final INetworkManagementService mNetworkManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700240 private final TrustedTime mTime;
241
242 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700243 private INotificationManager mNotifManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700244
Jeff Sharkey75279902011-05-24 18:39:45 -0700245 private final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700246
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700247 private volatile boolean mScreenOn;
248 private volatile boolean mRestrictBackground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700249
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700250 private final boolean mSuppressDefaultPolicy;
251
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700252 /** Defined network policies. */
253 private HashMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = Maps.newHashMap();
254 /** Currently active network rules for ifaces. */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700255 private HashMap<NetworkPolicy, String[]> mNetworkRules = Maps.newHashMap();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700256
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700257 /** Defined UID policies. */
258 private SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700259 /** Currently derived rules for each UID. */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700260 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700261
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700262 /** Set of ifaces that are metered. */
263 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700264 /** Set of over-limit templates that have been notified. */
265 private HashSet<NetworkTemplate> mOverLimitNotified = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700266
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700267 /** Set of currently active {@link Notification} tags. */
268 private HashSet<String> mActiveNotifs = Sets.newHashSet();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700269
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700270 /** Foreground at both UID and PID granularity. */
Jeff Sharkeya4620792011-05-20 15:29:23 -0700271 private SparseBooleanArray mUidForeground = new SparseBooleanArray();
272 private SparseArray<SparseBooleanArray> mUidPidForeground = new SparseArray<
273 SparseBooleanArray>();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700274
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700275 private final RemoteCallbackList<INetworkPolicyListener> mListeners = new RemoteCallbackList<
276 INetworkPolicyListener>();
277
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700278 private final HandlerThread mHandlerThread;
279 private final Handler mHandler;
280
281 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700282
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700283 // TODO: keep whitelist of system-critical services that should never have
284 // rules enforced, such as system, phone, and radio UIDs.
285
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700286 // TODO: migrate notifications to SystemUI
287
Jeff Sharkey75279902011-05-24 18:39:45 -0700288 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700289 IPowerManager powerManager, INetworkStatsService networkStats,
290 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700291 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700292 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700293 }
294
295 private static File getSystemDir() {
296 return new File(Environment.getDataDirectory(), "system");
297 }
298
299 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700300 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700301 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
302 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700303 mContext = checkNotNull(context, "missing context");
304 mActivityManager = checkNotNull(activityManager, "missing activityManager");
305 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700306 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700307 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700308 mTime = checkNotNull(time, "missing TrustedTime");
309
310 mHandlerThread = new HandlerThread(TAG);
311 mHandlerThread.start();
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700312 mHandler = new Handler(mHandlerThread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700313
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700314 mSuppressDefaultPolicy = suppressDefaultPolicy;
315
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700316 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
317 }
318
319 public void bindConnectivityManager(IConnectivityManager connManager) {
320 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700321 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700322
Jeff Sharkey497e4432011-06-14 17:27:29 -0700323 public void bindNotificationManager(INotificationManager notifManager) {
324 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
325 }
326
Jeff Sharkeya4620792011-05-20 15:29:23 -0700327 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700328 if (!isBandwidthControlEnabled()) {
329 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
330 return;
331 }
332
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700333 synchronized (mRulesLock) {
334 // read policy from disk
335 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700336
337 if (mRestrictBackground) {
338 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700339 updateNotificationsLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700340 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700341 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700342
Jeff Sharkeya4620792011-05-20 15:29:23 -0700343 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700344
Jeff Sharkeya4620792011-05-20 15:29:23 -0700345 try {
346 mActivityManager.registerProcessObserver(mProcessObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700347 mNetworkManager.registerObserver(mAlertObserver);
348 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700349 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700350 }
351
Jeff Sharkeya4620792011-05-20 15:29:23 -0700352 // TODO: traverse existing processes to know foreground state, or have
353 // activitymanager dispatch current state when new observer attached.
354
355 final IntentFilter screenFilter = new IntentFilter();
356 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
357 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700358 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700359
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700360 // watch for network interfaces to be claimed
Jeff Sharkey961e3042011-08-29 16:02:57 -0700361 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION_IMMEDIATE);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700362 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
363
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700364 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700365 final IntentFilter packageFilter = new IntentFilter();
366 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700367 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700368 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700369
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700370 // listen for UID changes to update policy
371 mContext.registerReceiver(
372 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
373
374 // listen for user changes to update policy
375 final IntentFilter userFilter = new IntentFilter();
376 userFilter.addAction(ACTION_USER_ADDED);
377 userFilter.addAction(ACTION_USER_REMOVED);
378 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
379
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700380 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700381 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
382 mContext.registerReceiver(
383 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
384
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700385 // listen for restrict background changes from notifications
386 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
387 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
388
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800389 // listen for snooze warning from notifications
390 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
391 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
392 MANAGE_NETWORK_POLICY, mHandler);
393
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700394 // listen for configured wifi networks to be removed
395 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
396 mContext.registerReceiver(
397 mWifiConfigReceiver, wifiConfigFilter, CONNECTIVITY_INTERNAL, mHandler);
398
399 // listen for wifi state changes to catch metered hint
400 final IntentFilter wifiStateFilter = new IntentFilter(
401 WifiManager.NETWORK_STATE_CHANGED_ACTION);
402 mContext.registerReceiver(
403 mWifiStateReceiver, wifiStateFilter, CONNECTIVITY_INTERNAL, mHandler);
404
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700405 }
406
Jeff Sharkeya4620792011-05-20 15:29:23 -0700407 private IProcessObserver mProcessObserver = new IProcessObserver.Stub() {
408 @Override
409 public void onForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700410 mHandler.obtainMessage(MSG_FOREGROUND_ACTIVITIES_CHANGED,
411 pid, uid, foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700412 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700413
414 @Override
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700415 public void onImportanceChanged(int pid, int uid, int importance) {
416 }
417
418 @Override
Jeff Sharkeya4620792011-05-20 15:29:23 -0700419 public void onProcessDied(int pid, int uid) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700420 mHandler.obtainMessage(MSG_PROCESS_DIED, pid, uid).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700421 }
422 };
423
424 private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
425 @Override
426 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800427 // screen-related broadcasts are protected by system, no need
428 // for permissions check.
429 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700430 }
431 };
432
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700433 private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700434 @Override
435 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700436 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700437
438 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700439 final int uid = intent.getIntExtra(EXTRA_UID, -1);
440 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700441
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700442 if (ACTION_PACKAGE_ADDED.equals(action)) {
443 // update rules for UID, since it might be subject to
444 // global background data policy
445 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
446 synchronized (mRulesLock) {
447 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700448 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700449 }
450 }
451 };
452
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700453 private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
454 @Override
455 public void onReceive(Context context, Intent intent) {
456 // on background handler thread, and UID_REMOVED is protected
457
458 final int uid = intent.getIntExtra(EXTRA_UID, -1);
459 if (uid == -1) return;
460
461 // remove any policy and update rules to clean up
462 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
463 synchronized (mRulesLock) {
464 mUidPolicy.delete(uid);
465 updateRulesForUidLocked(uid);
466 writePolicyLocked();
467 }
468 }
469 };
470
471 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
472 @Override
473 public void onReceive(Context context, Intent intent) {
474 // on background handler thread, and USER_ADDED and USER_REMOVED
475 // broadcasts are protected
476
477 final String action = intent.getAction();
478 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
479 if (userId == -1) return;
480
481 // Remove any policies for given user; both cleaning up after a
482 // USER_REMOVED, and one last sanity check during USER_ADDED
483 removePoliciesForUserLocked(userId);
484
485 // Update global restrict for new user
486 synchronized (mRulesLock) {
487 updateRulesForRestrictBackgroundLocked();
488 }
489 }
490 };
491
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700492 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700493 * Receiver that watches for {@link INetworkStatsService} updates, which we
494 * use to check against {@link NetworkPolicy#warningBytes}.
495 */
496 private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
497 @Override
498 public void onReceive(Context context, Intent intent) {
499 // on background handler thread, and verified
500 // READ_NETWORK_USAGE_HISTORY permission above.
501
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800502 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700503 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700504 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700505 updateNotificationsLocked();
506 }
507 }
508 };
509
510 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700511 * Receiver that watches for {@link Notification} control of
512 * {@link #mRestrictBackground}.
513 */
514 private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
515 @Override
516 public void onReceive(Context context, Intent intent) {
517 // on background handler thread, and verified MANAGE_NETWORK_POLICY
518 // permission above.
519
520 setRestrictBackground(false);
521 }
522 };
523
524 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800525 * Receiver that watches for {@link Notification} control of
526 * {@link NetworkPolicy#lastWarningSnooze}.
527 */
528 private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
529 @Override
530 public void onReceive(Context context, Intent intent) {
531 // on background handler thread, and verified MANAGE_NETWORK_POLICY
532 // permission above.
533
534 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
535 performSnooze(template, TYPE_WARNING);
536 }
537 };
538
539 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700540 * Receiver that watches for {@link WifiConfiguration} to be changed.
541 */
542 private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
543 @Override
544 public void onReceive(Context context, Intent intent) {
545 // on background handler thread, and verified CONNECTIVITY_INTERNAL
546 // permission above.
547
548 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
549 if (reason == CHANGE_REASON_REMOVED) {
550 final WifiConfiguration config = intent.getParcelableExtra(
551 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700552 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800553 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700554 synchronized (mRulesLock) {
555 if (mNetworkPolicy.containsKey(template)) {
556 mNetworkPolicy.remove(template);
557 writePolicyLocked();
558 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700559 }
560 }
561 }
562 }
563 };
564
565 /**
566 * Receiver that watches {@link WifiInfo} state changes to infer metered
567 * state. Ignores hints when policy is user-defined.
568 */
569 private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
570 @Override
571 public void onReceive(Context context, Intent intent) {
572 // on background handler thread, and verified CONNECTIVITY_INTERNAL
573 // permission above.
574
575 // ignore when not connected
576 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
577 if (!netInfo.isConnected()) return;
578
579 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
580 final boolean meteredHint = info.getMeteredHint();
581
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800582 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700583 synchronized (mRulesLock) {
584 NetworkPolicy policy = mNetworkPolicy.get(template);
585 if (policy == null && meteredHint) {
586 // policy doesn't exist, and AP is hinting that it's
587 // metered: create an inferred policy.
588 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
589 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
590 meteredHint, true);
591 addNetworkPolicyLocked(policy);
592
593 } else if (policy != null && policy.inferred) {
594 // policy exists, and was inferred: update its current
595 // metered state.
596 policy.metered = meteredHint;
597
598 // since this is inferred for each wifi session, just update
599 // rules without persisting.
600 updateNetworkRulesLocked();
601 }
602 }
603 }
604 };
605
606 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700607 * Observer that watches for {@link INetworkManagementService} alerts.
608 */
Jeff Sharkey216c1812012-08-05 14:29:23 -0700609 private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700610 @Override
611 public void limitReached(String limitName, String iface) {
612 // only someone like NMS should be calling us
613 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
614
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800615 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
616 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700617 }
618 }
619 };
620
621 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700622 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
623 * to show visible notifications as needed.
624 */
625 private void updateNotificationsLocked() {
626 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
627
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700628 // keep track of previously active notifications
629 final HashSet<String> beforeNotifs = Sets.newHashSet();
630 beforeNotifs.addAll(mActiveNotifs);
631 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700632
633 // TODO: when switching to kernel notifications, compute next future
634 // cycle boundary to recompute notifications.
635
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700636 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800637 final long currentTime = currentTimeMillis();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700638 for (NetworkPolicy policy : mNetworkPolicy.values()) {
639 // ignore policies that aren't relevant to user
640 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700641 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700642
Jeff Sharkey497e4432011-06-14 17:27:29 -0700643 final long start = computeLastCycleBoundary(currentTime, policy);
644 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700645 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700646
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700647 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800648 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700649 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
650 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700651 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
652 notifyOverLimitLocked(policy.template);
653 }
654
Jeff Sharkey497e4432011-06-14 17:27:29 -0700655 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700656 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700657
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800658 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700659 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700660 }
661 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700662 }
663
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700664 // ongoing notification when restricting background data
665 if (mRestrictBackground) {
666 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700667 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700668
669 // cancel stale notifications that we didn't renew above
670 for (String tag : beforeNotifs) {
671 if (!mActiveNotifs.contains(tag)) {
672 cancelNotification(tag);
673 }
674 }
675 }
676
677 /**
678 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700679 * current device state, such as when
680 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
681 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700682 */
683 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700684 final TelephonyManager tele = TelephonyManager.from(mContext);
685
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700686 switch (template.getMatchRule()) {
687 case MATCH_MOBILE_3G_LOWER:
688 case MATCH_MOBILE_4G:
689 case MATCH_MOBILE_ALL:
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700690 // mobile templates are relevant when SIM is ready and
691 // subscriberId matches.
692 if (tele.getSimState() == SIM_STATE_READY) {
693 return Objects.equal(tele.getSubscriberId(), template.getSubscriberId());
694 } else {
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700695 return false;
696 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700697 }
698 return true;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700699 }
700
701 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700702 * Notify that given {@link NetworkTemplate} is over
703 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
704 */
705 private void notifyOverLimitLocked(NetworkTemplate template) {
706 if (!mOverLimitNotified.contains(template)) {
707 mContext.startActivity(buildNetworkOverLimitIntent(template));
708 mOverLimitNotified.add(template);
709 }
710 }
711
712 private void notifyUnderLimitLocked(NetworkTemplate template) {
713 mOverLimitNotified.remove(template);
714 }
715
716 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700717 * Build unique tag that identifies an active {@link NetworkPolicy}
718 * notification of a specific type, like {@link #TYPE_LIMIT}.
719 */
720 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700721 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700722 }
723
724 /**
725 * Show notification for combined {@link NetworkPolicy} and specific type,
726 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
727 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700728 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700729 final String tag = buildNotificationTag(policy, type);
730 final Notification.Builder builder = new Notification.Builder(mContext);
731 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800732 builder.setWhen(0L);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700733
734 final Resources res = mContext.getResources();
735 switch (type) {
736 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700737 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700738 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700739
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700740 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700741 builder.setTicker(title);
742 builder.setContentTitle(title);
743 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700744
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800745 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
746 builder.setDeleteIntent(PendingIntent.getBroadcast(
747 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
748
749 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700750 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800751 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
752
Jeff Sharkey497e4432011-06-14 17:27:29 -0700753 break;
754 }
755 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700756 final CharSequence body = res.getText(R.string.data_usage_limit_body);
757
758 final CharSequence title;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700759 switch (policy.template.getMatchRule()) {
760 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700761 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700762 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700763 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700764 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700765 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700766 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700767 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700768 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700769 case MATCH_WIFI:
770 title = res.getText(R.string.data_usage_wifi_limit_title);
771 break;
772 default:
773 title = null;
774 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700775 }
776
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800777 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700778 builder.setSmallIcon(R.drawable.stat_notify_disabled);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700779 builder.setTicker(title);
780 builder.setContentTitle(title);
781 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700782
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700783 final Intent intent = buildNetworkOverLimitIntent(policy.template);
784 builder.setContentIntent(PendingIntent.getActivity(
785 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
786 break;
787 }
788 case TYPE_LIMIT_SNOOZED: {
789 final long overBytes = totalBytes - policy.limitBytes;
790 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
791 Formatter.formatFileSize(mContext, overBytes));
792
793 final CharSequence title;
794 switch (policy.template.getMatchRule()) {
795 case MATCH_MOBILE_3G_LOWER:
796 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
797 break;
798 case MATCH_MOBILE_4G:
799 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
800 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700801 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700802 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
803 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700804 case MATCH_WIFI:
805 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
806 break;
807 default:
808 title = null;
809 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700810 }
811
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800812 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700813 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700814 builder.setTicker(title);
815 builder.setContentTitle(title);
816 builder.setContentText(body);
817
818 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700819 builder.setContentIntent(PendingIntent.getActivity(
820 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700821 break;
822 }
823 }
824
825 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700826 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700827 try {
828 final String packageName = mContext.getPackageName();
829 final int[] idReceived = new int[1];
830 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800831 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Dianne Hackborn41203752012-08-31 14:05:51 -0700832 UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700833 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700834 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700835 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700836 }
837 }
838
839 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700840 * Show ongoing notification to reflect that {@link #mRestrictBackground}
841 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700842 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700843 private void enqueueRestrictedNotification(String tag) {
844 final Resources res = mContext.getResources();
845 final Notification.Builder builder = new Notification.Builder(mContext);
846
847 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
848 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
849
850 builder.setOnlyAlertOnce(true);
851 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700852 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700853 builder.setTicker(title);
854 builder.setContentTitle(title);
855 builder.setContentText(body);
856
857 final Intent intent = buildAllowBackgroundDataIntent();
858 builder.setContentIntent(
859 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700860
861 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700862 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700863 try {
864 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700865 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800866 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Dianne Hackborn41203752012-08-31 14:05:51 -0700867 0x0, builder.getNotification(), idReceived, UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700868 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700869 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700870 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700871 }
872 }
873
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700874 private void cancelNotification(String tag) {
875 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700876 // XXX what to do about multi-user?
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700877 try {
878 final String packageName = mContext.getPackageName();
879 mNotifManager.cancelNotificationWithTag(
Dianne Hackborn41203752012-08-31 14:05:51 -0700880 packageName, tag, 0x0, UserHandle.USER_OWNER);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700881 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700882 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700883 }
884 }
885
886 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700887 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700888 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700889 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700890 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700891 @Override
892 public void onReceive(Context context, Intent intent) {
893 // on background handler thread, and verified CONNECTIVITY_INTERNAL
894 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800895
896 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700897 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700898 ensureActiveMobilePolicyLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700899 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700900 updateNetworkRulesLocked();
901 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700902 }
903 }
904 };
905
906 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700907 * Proactively control network data connections when they exceed
908 * {@link NetworkPolicy#limitBytes}.
909 */
910 private void updateNetworkEnabledLocked() {
911 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
912
913 // TODO: reset any policy-disabled networks when any policy is removed
914 // completely, which is currently rare case.
915
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800916 final long currentTime = currentTimeMillis();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700917 for (NetworkPolicy policy : mNetworkPolicy.values()) {
918 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700919 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700920 setNetworkTemplateEnabled(policy.template, true);
921 continue;
922 }
923
924 final long start = computeLastCycleBoundary(currentTime, policy);
925 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700926 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700927
928 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800929 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
930 && policy.lastLimitSnooze < start;
931 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700932
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800933 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700934 }
935 }
936
937 /**
938 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}
939 * for the given {@link NetworkTemplate}.
940 */
941 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700942 final TelephonyManager tele = TelephonyManager.from(mContext);
943
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700944 switch (template.getMatchRule()) {
945 case MATCH_MOBILE_3G_LOWER:
946 case MATCH_MOBILE_4G:
947 case MATCH_MOBILE_ALL:
948 // TODO: offer more granular control over radio states once
949 // 4965893 is available.
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700950 if (tele.getSimState() == SIM_STATE_READY
951 && Objects.equal(tele.getSubscriberId(), template.getSubscriberId())) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700952 setPolicyDataEnable(TYPE_MOBILE, enabled);
953 setPolicyDataEnable(TYPE_WIMAX, enabled);
954 }
955 break;
956 case MATCH_WIFI:
957 setPolicyDataEnable(TYPE_WIFI, enabled);
958 break;
959 case MATCH_ETHERNET:
960 setPolicyDataEnable(TYPE_ETHERNET, enabled);
961 break;
962 default:
963 throw new IllegalArgumentException("unexpected template");
964 }
965 }
966
967 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700968 * Examine all connected {@link NetworkState}, looking for
969 * {@link NetworkPolicy} that need to be enforced. When matches found, set
970 * remaining quota based on usage cycle and historical stats.
971 */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700972 private void updateNetworkRulesLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700973 if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700974
975 final NetworkState[] states;
976 try {
977 states = mConnManager.getAllNetworkState();
978 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700979 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700980 return;
981 }
982
983 // first, derive identity for all connected networks, which can be used
984 // to match against templates.
985 final HashMap<NetworkIdentity, String> networks = Maps.newHashMap();
986 for (NetworkState state : states) {
987 // stash identity and iface away for later use
988 if (state.networkInfo.isConnected()) {
989 final String iface = state.linkProperties.getInterfaceName();
990 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
991 networks.put(ident, iface);
992 }
993 }
994
995 // build list of rules and ifaces to enforce them against
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700996 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700997 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700998 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700999
1000 // collect all active ifaces that match this template
1001 ifaceList.clear();
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001002 for (Map.Entry<NetworkIdentity, String> entry : networks.entrySet()) {
1003 final NetworkIdentity ident = entry.getKey();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001004 if (policy.template.matches(ident)) {
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001005 final String iface = entry.getValue();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001006 ifaceList.add(iface);
1007 }
1008 }
1009
1010 if (ifaceList.size() > 0) {
1011 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001012 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001013 }
1014 }
1015
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001016 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001017 final HashSet<String> newMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001018
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001019 // apply each policy that we found ifaces for; compute remaining data
1020 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001021 final long currentTime = currentTimeMillis();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001022 for (NetworkPolicy policy : mNetworkRules.keySet()) {
1023 final String[] ifaces = mNetworkRules.get(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001024
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001025 final long start;
1026 final long totalBytes;
1027 if (policy.hasCycle()) {
1028 start = computeLastCycleBoundary(currentTime, policy);
1029 totalBytes = getTotalBytes(policy.template, start, currentTime);
1030 } else {
1031 start = Long.MAX_VALUE;
1032 totalBytes = 0;
1033 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001034
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001035 if (LOGD) {
1036 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001037 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001038 }
1039
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001040 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001041 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001042 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001043 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001044 if (!hasLimit) {
1045 // metered network, but no policy limit; we still need to
1046 // restrict apps, so push really high quota.
1047 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001048 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001049 // snoozing past quota, but we still need to restrict apps,
1050 // so push really high quota.
1051 quotaBytes = Long.MAX_VALUE;
1052 } else {
1053 // remaining "quota" bytes are based on total usage in
1054 // current cycle. kernel doesn't like 0-byte rules, so we
1055 // set 1-byte quota and disable the radio later.
1056 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1057 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001058
1059 if (ifaces.length > 1) {
1060 // TODO: switch to shared quota once NMS supports
1061 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001062 }
1063
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001064 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001065 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001066 setInterfaceQuota(iface, quotaBytes);
1067 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001068 }
1069 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001070
1071 // keep track of lowest warning or limit of active policies
1072 if (hasWarning && policy.warningBytes < lowestRule) {
1073 lowestRule = policy.warningBytes;
1074 }
1075 if (hasLimit && policy.limitBytes < lowestRule) {
1076 lowestRule = policy.limitBytes;
1077 }
1078 }
1079
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001080 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001081
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001082 // remove quota on any trailing interfaces
1083 for (String iface : mMeteredIfaces) {
1084 if (!newMeteredIfaces.contains(iface)) {
1085 removeInterfaceQuota(iface);
1086 }
1087 }
1088 mMeteredIfaces = newMeteredIfaces;
1089
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001090 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001091 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001092 }
1093
1094 /**
1095 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1096 * have at least a default mobile policy defined.
1097 */
1098 private void ensureActiveMobilePolicyLocked() {
1099 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001100 if (mSuppressDefaultPolicy) return;
1101
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001102 final TelephonyManager tele = TelephonyManager.from(mContext);
1103
1104 // avoid creating policy when SIM isn't ready
1105 if (tele.getSimState() != SIM_STATE_READY) return;
1106
1107 final String subscriberId = tele.getSubscriberId();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001108 final NetworkIdentity probeIdent = new NetworkIdentity(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001109 TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001110
1111 // examine to see if any policy is defined for active mobile
1112 boolean mobileDefined = false;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001113 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001114 if (policy.template.matches(probeIdent)) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001115 mobileDefined = true;
1116 }
1117 }
1118
1119 if (!mobileDefined) {
1120 Slog.i(TAG, "no policy for active mobile network; generating default policy");
1121
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001122 // build default mobile policy, and assume usage cycle starts today
1123 final long warningBytes = mContext.getResources().getInteger(
1124 com.android.internal.R.integer.config_networkPolicyDefaultWarning)
1125 * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001126
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001127 final Time time = new Time();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001128 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001129
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001130 final int cycleDay = time.monthDay;
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001131 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001132
Jeff Sharkey4e814c32011-07-14 20:37:37 -07001133 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001134 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1135 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1136 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001137 }
1138 }
1139
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001140 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001141 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001142
1143 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001144 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001145 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001146
1147 FileInputStream fis = null;
1148 try {
1149 fis = mPolicyFile.openRead();
1150 final XmlPullParser in = Xml.newPullParser();
1151 in.setInput(fis, null);
1152
1153 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001154 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001155 while ((type = in.next()) != END_DOCUMENT) {
1156 final String tag = in.getName();
1157 if (type == START_TAG) {
1158 if (TAG_POLICY_LIST.equals(tag)) {
1159 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001160 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1161 mRestrictBackground = readBooleanAttribute(
1162 in, ATTR_RESTRICT_BACKGROUND);
1163 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001164 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001165 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001166
1167 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1168 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1169 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001170 final String networkId;
1171 if (version >= VERSION_ADDED_NETWORK_ID) {
1172 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1173 } else {
1174 networkId = null;
1175 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001176 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001177 final String cycleTimezone;
1178 if (version >= VERSION_ADDED_TIMEZONE) {
1179 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1180 } else {
1181 cycleTimezone = Time.TIMEZONE_UTC;
1182 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001183 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1184 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001185 final long lastLimitSnooze;
1186 if (version >= VERSION_SPLIT_SNOOZE) {
1187 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1188 } else if (version >= VERSION_ADDED_SNOOZE) {
1189 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001190 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001191 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001192 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001193 final boolean metered;
1194 if (version >= VERSION_ADDED_METERED) {
1195 metered = readBooleanAttribute(in, ATTR_METERED);
1196 } else {
1197 switch (networkTemplate) {
1198 case MATCH_MOBILE_3G_LOWER:
1199 case MATCH_MOBILE_4G:
1200 case MATCH_MOBILE_ALL:
1201 metered = true;
1202 break;
1203 default:
1204 metered = false;
1205 }
1206 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001207 final long lastWarningSnooze;
1208 if (version >= VERSION_SPLIT_SNOOZE) {
1209 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1210 } else {
1211 lastWarningSnooze = SNOOZE_NEVER;
1212 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001213 final boolean inferred;
1214 if (version >= VERSION_ADDED_INFERRED) {
1215 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1216 } else {
1217 inferred = false;
1218 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001219
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001220 final NetworkTemplate template = new NetworkTemplate(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001221 networkTemplate, subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001222 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001223 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001224 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001225
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001226 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001227 final int uid = readIntAttribute(in, ATTR_UID);
1228 final int policy = readIntAttribute(in, ATTR_POLICY);
1229
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001230 if (UserHandle.isApp(uid)) {
1231 setUidPolicyUnchecked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001232 } else {
1233 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1234 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001235 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001236 final int appId = readIntAttribute(in, ATTR_APP_ID);
1237 final int policy = readIntAttribute(in, ATTR_POLICY);
1238
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001239 // TODO: set for other users during upgrade
1240 final int uid = UserHandle.getUid(UserHandle.USER_OWNER, appId);
1241 if (UserHandle.isApp(uid)) {
1242 setUidPolicyUnchecked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001243 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001244 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001245 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001246 }
1247 }
1248 }
1249
1250 } catch (FileNotFoundException e) {
1251 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001252 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001253 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001254 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001255 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001256 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001257 } finally {
1258 IoUtils.closeQuietly(fis);
1259 }
1260 }
1261
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001262 /**
1263 * Upgrade legacy background data flags, notifying listeners of one last
1264 * change to always-true.
1265 */
1266 private void upgradeLegacyBackgroundData() {
1267 mRestrictBackground = Settings.Secure.getInt(
1268 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1269
1270 // kick off one last broadcast if restricted
1271 if (mRestrictBackground) {
1272 final Intent broadcast = new Intent(
1273 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001274 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001275 }
1276 }
1277
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001278 private void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001279 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001280
1281 FileOutputStream fos = null;
1282 try {
1283 fos = mPolicyFile.startWrite();
1284
1285 XmlSerializer out = new FastXmlSerializer();
1286 out.setOutput(fos, "utf-8");
1287 out.startDocument(null, true);
1288
1289 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001290 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001291 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001292
1293 // write all known network policies
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001294 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001295 final NetworkTemplate template = policy.template;
1296
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001297 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001298 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1299 final String subscriberId = template.getSubscriberId();
1300 if (subscriberId != null) {
1301 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001302 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001303 final String networkId = template.getNetworkId();
1304 if (networkId != null) {
1305 out.attribute(null, ATTR_NETWORK_ID, networkId);
1306 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001307 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001308 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001309 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1310 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001311 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1312 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001313 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001314 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001315 out.endTag(null, TAG_NETWORK_POLICY);
1316 }
1317
1318 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001319 for (int i = 0; i < mUidPolicy.size(); i++) {
1320 final int uid = mUidPolicy.keyAt(i);
1321 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001322
Jeff Sharkey497e4432011-06-14 17:27:29 -07001323 // skip writing empty policies
1324 if (policy == POLICY_NONE) continue;
1325
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001326 out.startTag(null, TAG_UID_POLICY);
1327 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001328 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001329 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001330 }
1331
1332 out.endTag(null, TAG_POLICY_LIST);
1333 out.endDocument();
1334
1335 mPolicyFile.finishWrite(fos);
1336 } catch (IOException e) {
1337 if (fos != null) {
1338 mPolicyFile.failWrite(fos);
1339 }
1340 }
1341 }
1342
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001343 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001344 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001345 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001346
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001347 if (!UserHandle.isApp(uid)) {
1348 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001349 }
1350
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001351 setUidPolicyUnchecked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001352 }
1353
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001354 private void setUidPolicyUnchecked(int uid, int policy, boolean persist) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001355 final int oldPolicy;
Jeff Sharkeya4620792011-05-20 15:29:23 -07001356 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001357 oldPolicy = getUidPolicy(uid);
1358 mUidPolicy.put(uid, policy);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001359
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001360 // uid policy changed, recompute rules and persist policy.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001361 updateRulesForUidLocked(uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001362 if (persist) {
1363 writePolicyLocked();
1364 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001365 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001366 }
1367
1368 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001369 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001370 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1371
Jeff Sharkeya4620792011-05-20 15:29:23 -07001372 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001373 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001374 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001375 }
1376
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001377 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001378 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001379 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1380
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001381 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001382 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001383 for (int i = 0; i < mUidPolicy.size(); i++) {
1384 final int uid = mUidPolicy.keyAt(i);
1385 final int uidPolicy = mUidPolicy.valueAt(i);
1386 if (uidPolicy == policy) {
1387 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001388 }
1389 }
1390 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001391 return uids;
1392 }
1393
1394 /**
1395 * Remove any policies associated with given {@link UserHandle}, persisting
1396 * if any changes are made.
1397 */
1398 private void removePoliciesForUserLocked(int userId) {
1399 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1400
1401 int[] uids = new int[0];
1402 for (int i = 0; i < mUidPolicy.size(); i++) {
1403 final int uid = mUidPolicy.keyAt(i);
1404 if (UserHandle.getUserId(uid) == userId) {
1405 uids = appendInt(uids, uid);
1406 }
1407 }
1408
1409 if (uids.length > 0) {
1410 for (int uid : uids) {
1411 mUidPolicy.delete(uid);
1412 updateRulesForUidLocked(uid);
1413 }
1414 writePolicyLocked();
1415 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001416 }
1417
1418 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001419 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001420 // TODO: create permission for observing network policy
1421 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1422
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001423 mListeners.register(listener);
1424
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001425 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001426 }
1427
1428 @Override
1429 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001430 // TODO: create permission for observing network policy
1431 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1432
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001433 mListeners.unregister(listener);
1434 }
1435
Jeff Sharkey1b861272011-05-22 00:34:52 -07001436 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001437 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001438 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1439
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001440 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001441 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001442 mNetworkPolicy.clear();
1443 for (NetworkPolicy policy : policies) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001444 mNetworkPolicy.put(policy.template, policy);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001445 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001446
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001447 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001448 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001449 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001450 writePolicyLocked();
1451 }
1452 }
1453
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001454 private void addNetworkPolicyLocked(NetworkPolicy policy) {
1455 mNetworkPolicy.put(policy.template, policy);
1456
1457 updateNetworkEnabledLocked();
1458 updateNetworkRulesLocked();
1459 updateNotificationsLocked();
1460 writePolicyLocked();
1461 }
1462
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001463 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001464 public NetworkPolicy[] getNetworkPolicies() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001465 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001466 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001467
1468 synchronized (mRulesLock) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001469 return mNetworkPolicy.values().toArray(new NetworkPolicy[mNetworkPolicy.size()]);
1470 }
1471 }
1472
1473 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001474 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001475 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001476
1477 final long token = Binder.clearCallingIdentity();
1478 try {
1479 performSnooze(template, TYPE_LIMIT);
1480 } finally {
1481 Binder.restoreCallingIdentity(token);
1482 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001483 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001484
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001485 private void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001486 maybeRefreshTrustedTime();
1487 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001488 synchronized (mRulesLock) {
1489 // find and snooze local policy that matches
1490 final NetworkPolicy policy = mNetworkPolicy.get(template);
1491 if (policy == null) {
1492 throw new IllegalArgumentException("unable to find policy for " + template);
1493 }
1494
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001495 switch (type) {
1496 case TYPE_WARNING:
1497 policy.lastWarningSnooze = currentTime;
1498 break;
1499 case TYPE_LIMIT:
1500 policy.lastLimitSnooze = currentTime;
1501 break;
1502 default:
1503 throw new IllegalArgumentException("unexpected type");
1504 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001505
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001506 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001507 updateNetworkRulesLocked();
1508 updateNotificationsLocked();
1509 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001510 }
1511 }
1512
1513 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001514 public void setRestrictBackground(boolean restrictBackground) {
1515 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1516
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001517 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001518 synchronized (mRulesLock) {
1519 mRestrictBackground = restrictBackground;
1520 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001521 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001522 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001523 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001524
1525 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1526 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001527 }
1528
1529 @Override
1530 public boolean getRestrictBackground() {
1531 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1532
1533 synchronized (mRulesLock) {
1534 return mRestrictBackground;
1535 }
1536 }
1537
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001538 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
1539 for (NetworkPolicy policy : mNetworkPolicy.values()) {
1540 if (policy.template.matches(ident)) {
1541 return policy;
1542 }
1543 }
1544 return null;
1545 }
1546
1547 @Override
1548 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1549 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1550
1551 // only returns usage summary, so we don't require caller to have
1552 // READ_NETWORK_USAGE_HISTORY.
1553 final long token = Binder.clearCallingIdentity();
1554 try {
1555 return getNetworkQuotaInfoUnchecked(state);
1556 } finally {
1557 Binder.restoreCallingIdentity(token);
1558 }
1559 }
1560
1561 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1562 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1563
1564 final NetworkPolicy policy;
1565 synchronized (mRulesLock) {
1566 policy = findPolicyForNetworkLocked(ident);
1567 }
1568
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001569 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001570 // missing policy means we can't derive useful quota info
1571 return null;
1572 }
1573
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001574 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001575
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001576 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001577 final long start = computeLastCycleBoundary(currentTime, policy);
1578 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001579 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001580
1581 // report soft and hard limits under policy
1582 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1583 : NetworkQuotaInfo.NO_LIMIT;
1584 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1585 : NetworkQuotaInfo.NO_LIMIT;
1586
1587 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1588 }
1589
Jeff Sharkey46645002011-07-27 21:11:21 -07001590 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001591 public boolean isNetworkMetered(NetworkState state) {
1592 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1593
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001594 // roaming networks are always considered metered
1595 if (ident.getRoaming()) {
1596 return true;
1597 }
1598
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001599 final NetworkPolicy policy;
1600 synchronized (mRulesLock) {
1601 policy = findPolicyForNetworkLocked(ident);
1602 }
1603
1604 if (policy != null) {
1605 return policy.metered;
1606 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001607 final int type = state.networkInfo.getType();
1608 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1609 return true;
1610 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001611 return false;
1612 }
1613 }
1614
1615 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001616 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001617 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001618
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001619 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1620
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001621 final HashSet<String> argSet = new HashSet<String>();
1622 for (String arg : args) {
1623 argSet.add(arg);
1624 }
1625
Jeff Sharkey1b861272011-05-22 00:34:52 -07001626 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001627 if (argSet.contains("--unsnooze")) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001628 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001629 policy.clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001630 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001631
1632 updateNetworkEnabledLocked();
1633 updateNetworkRulesLocked();
1634 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001635 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001636
1637 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001638 return;
1639 }
1640
Jeff Sharkey46645002011-07-27 21:11:21 -07001641 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001642 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001643 fout.increaseIndent();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001644 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001645 fout.println(policy.toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001646 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001647 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001648
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001649 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001650 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001651 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001652 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001653 final int uid = mUidPolicy.keyAt(i);
1654 final int policy = mUidPolicy.valueAt(i);
1655 fout.print("UID=");
1656 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001657 fout.print(" policy=");
1658 dumpPolicy(fout, policy);
1659 fout.println();
1660 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001661 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001662
1663 final SparseBooleanArray knownUids = new SparseBooleanArray();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001664 collectKeys(mUidForeground, knownUids);
1665 collectKeys(mUidRules, knownUids);
1666
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001667 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001668 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001669 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001670 for (int i = 0; i < size; i++) {
1671 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001672 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001673 fout.print(uid);
1674
Jeff Sharkey1b861272011-05-22 00:34:52 -07001675 fout.print(" foreground=");
1676 final int foregroundIndex = mUidPidForeground.indexOfKey(uid);
1677 if (foregroundIndex < 0) {
1678 fout.print("UNKNOWN");
1679 } else {
1680 dumpSparseBooleanArray(fout, mUidPidForeground.valueAt(foregroundIndex));
1681 }
1682
1683 fout.print(" rules=");
1684 final int rulesIndex = mUidRules.indexOfKey(uid);
1685 if (rulesIndex < 0) {
1686 fout.print("UNKNOWN");
1687 } else {
1688 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1689 }
1690
1691 fout.println();
1692 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001693 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001694 }
1695 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001696
1697 @Override
1698 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001699 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1700
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001701 synchronized (mRulesLock) {
1702 // only really in foreground when screen is also on
1703 return mUidForeground.get(uid, false) && mScreenOn;
1704 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001705 }
1706
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001707 /**
1708 * Foreground for PID changed; recompute foreground at UID level. If
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001709 * changed, will trigger {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001710 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001711 private void computeUidForegroundLocked(int uid) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001712 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1713
1714 // current pid is dropping foreground; examine other pids
1715 boolean uidForeground = false;
1716 final int size = pidForeground.size();
1717 for (int i = 0; i < size; i++) {
1718 if (pidForeground.valueAt(i)) {
1719 uidForeground = true;
1720 break;
1721 }
1722 }
1723
1724 final boolean oldUidForeground = mUidForeground.get(uid, false);
1725 if (oldUidForeground != uidForeground) {
1726 // foreground changed, push updated rules
1727 mUidForeground.put(uid, uidForeground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001728 updateRulesForUidLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001729 }
1730 }
1731
Jeff Sharkeya4620792011-05-20 15:29:23 -07001732 private void updateScreenOn() {
1733 synchronized (mRulesLock) {
1734 try {
1735 mScreenOn = mPowerManager.isScreenOn();
1736 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001737 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07001738 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001739 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001740 }
1741 }
1742
1743 /**
1744 * Update rules that might be changed by {@link #mScreenOn} value.
1745 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001746 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07001747 // only update rules for anyone with foreground activities
1748 final int size = mUidForeground.size();
1749 for (int i = 0; i < size; i++) {
1750 if (mUidForeground.valueAt(i)) {
1751 final int uid = mUidForeground.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001752 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001753 }
1754 }
1755 }
1756
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001757 /**
Jeff Sharkey46645002011-07-27 21:11:21 -07001758 * Update rules that might be changed by {@link #mRestrictBackground} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001759 */
Jeff Sharkey46645002011-07-27 21:11:21 -07001760 private void updateRulesForRestrictBackgroundLocked() {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001761 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001762 final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1763
1764 // update rules for all installed applications
1765 final List<UserInfo> users = um.getUsers();
1766 final List<ApplicationInfo> apps = pm.getInstalledApplications(
1767 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
1768
1769 for (UserInfo user : users) {
1770 for (ApplicationInfo app : apps) {
1771 final int uid = UserHandle.getUid(user.id, app.uid);
1772 updateRulesForUidLocked(uid);
1773 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001774 }
1775
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001776 // limit data usage for some internal system services
1777 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
1778 updateRulesForUidLocked(android.os.Process.DRM_UID);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001779 }
1780
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001781 private static boolean isUidValidForRules(int uid) {
1782 // allow rules on specific system services, and any apps
1783 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001784 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001785 return true;
1786 }
1787
1788 return false;
1789 }
1790
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001791 private void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001792 if (!isUidValidForRules(uid)) return;
1793
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001794 final int uidPolicy = getUidPolicy(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001795 final boolean uidForeground = isUidForeground(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001796
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001797 // derive active rules based on policy and active state
1798 int uidRules = RULE_ALLOW_ALL;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001799 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001800 // uid in background, and policy says to block metered data
1801 uidRules = RULE_REJECT_METERED;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001802 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001803 if (!uidForeground && mRestrictBackground) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001804 // uid in background, and global background disabled
1805 uidRules = RULE_REJECT_METERED;
1806 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001807
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001808 // TODO: only dispatch when rules actually change
1809
Jeff Sharkey350083e2011-06-29 10:45:16 -07001810 if (uidRules == RULE_ALLOW_ALL) {
1811 mUidRules.delete(uid);
1812 } else {
1813 mUidRules.put(uid, uidRules);
1814 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001815
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001816 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001817 setUidNetworkRules(uid, rejectMetered);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001818
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001819 // dispatch changed rule to existing listeners
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001820 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001821
1822 try {
1823 // adjust stats accounting based on foreground status
1824 mNetworkStats.setUidForeground(uid, uidForeground);
1825 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001826 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001827 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001828 }
1829
1830 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001831 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001832 public boolean handleMessage(Message msg) {
1833 switch (msg.what) {
1834 case MSG_RULES_CHANGED: {
1835 final int uid = msg.arg1;
1836 final int uidRules = msg.arg2;
1837 final int length = mListeners.beginBroadcast();
1838 for (int i = 0; i < length; i++) {
1839 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1840 if (listener != null) {
1841 try {
1842 listener.onUidRulesChanged(uid, uidRules);
1843 } catch (RemoteException e) {
1844 }
1845 }
1846 }
1847 mListeners.finishBroadcast();
1848 return true;
1849 }
1850 case MSG_METERED_IFACES_CHANGED: {
1851 final String[] meteredIfaces = (String[]) msg.obj;
1852 final int length = mListeners.beginBroadcast();
1853 for (int i = 0; i < length; i++) {
1854 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1855 if (listener != null) {
1856 try {
1857 listener.onMeteredIfacesChanged(meteredIfaces);
1858 } catch (RemoteException e) {
1859 }
1860 }
1861 }
1862 mListeners.finishBroadcast();
1863 return true;
1864 }
Jeff Sharkey6f7af032011-11-01 18:25:15 -07001865 case MSG_FOREGROUND_ACTIVITIES_CHANGED: {
1866 final int pid = msg.arg1;
1867 final int uid = msg.arg2;
1868 final boolean foregroundActivities = (Boolean) msg.obj;
1869
1870 synchronized (mRulesLock) {
1871 // because a uid can have multiple pids running inside, we need to
1872 // remember all pid states and summarize foreground at uid level.
1873
1874 // record foreground for this specific pid
1875 SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1876 if (pidForeground == null) {
1877 pidForeground = new SparseBooleanArray(2);
1878 mUidPidForeground.put(uid, pidForeground);
1879 }
1880 pidForeground.put(pid, foregroundActivities);
1881 computeUidForegroundLocked(uid);
1882 }
1883 return true;
1884 }
1885 case MSG_PROCESS_DIED: {
1886 final int pid = msg.arg1;
1887 final int uid = msg.arg2;
1888
1889 synchronized (mRulesLock) {
1890 // clear records and recompute, when they exist
1891 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1892 if (pidForeground != null) {
1893 pidForeground.delete(pid);
1894 computeUidForegroundLocked(uid);
1895 }
1896 }
1897 return true;
1898 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001899 case MSG_LIMIT_REACHED: {
1900 final String iface = (String) msg.obj;
1901
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001902 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001903 synchronized (mRulesLock) {
1904 if (mMeteredIfaces.contains(iface)) {
1905 try {
1906 // force stats update to make sure we have
1907 // numbers that caused alert to trigger.
1908 mNetworkStats.forceUpdate();
1909 } catch (RemoteException e) {
1910 // ignored; service lives in system_server
1911 }
1912
1913 updateNetworkEnabledLocked();
1914 updateNotificationsLocked();
1915 }
1916 }
1917 return true;
1918 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001919 case MSG_RESTRICT_BACKGROUND_CHANGED: {
1920 final boolean restrictBackground = msg.arg1 != 0;
1921 final int length = mListeners.beginBroadcast();
1922 for (int i = 0; i < length; i++) {
1923 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1924 if (listener != null) {
1925 try {
1926 listener.onRestrictBackgroundChanged(restrictBackground);
1927 } catch (RemoteException e) {
1928 }
1929 }
1930 }
1931 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001932 return true;
1933 }
1934 case MSG_ADVISE_PERSIST_THRESHOLD: {
1935 final long lowestRule = (Long) msg.obj;
1936 try {
1937 // make sure stats are recorded frequently enough; we aim
1938 // for 2MB threshold for 2GB/month rules.
1939 final long persistThreshold = lowestRule / 1000;
1940 mNetworkStats.advisePersistThreshold(persistThreshold);
1941 } catch (RemoteException e) {
1942 // ignored; service lives in system_server
1943 }
1944 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001945 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07001946 case MSG_SCREEN_ON_CHANGED: {
1947 updateScreenOn();
1948 return true;
1949 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001950 default: {
1951 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07001952 }
1953 }
1954 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001955 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001956
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001957 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001958 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001959 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001960 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001961 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001962 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001963 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001964 }
1965 }
1966
1967 private void removeInterfaceQuota(String iface) {
1968 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001969 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001970 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001971 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001972 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001973 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001974 }
1975 }
1976
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001977 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1978 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001979 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001980 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001981 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001982 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001983 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001984 }
1985 }
1986
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001987 /**
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001988 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001989 */
1990 private void setPolicyDataEnable(int networkType, boolean enabled) {
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001991 try {
1992 mConnManager.setPolicyDataEnable(networkType, enabled);
1993 } catch (RemoteException e) {
1994 // ignored; service lives in system_server
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001995 }
1996 }
1997
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001998 private long getTotalBytes(NetworkTemplate template, long start, long end) {
1999 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002000 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002001 } catch (RuntimeException e) {
2002 Slog.w(TAG, "problem reading network stats: " + e);
2003 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002004 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002005 // ignored; service lives in system_server
2006 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002007 }
2008 }
2009
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002010 private boolean isBandwidthControlEnabled() {
2011 final long token = Binder.clearCallingIdentity();
2012 try {
2013 return mNetworkManager.isBandwidthControlEnabled();
2014 } catch (RemoteException e) {
2015 // ignored; service lives in system_server
2016 return false;
2017 } finally {
2018 Binder.restoreCallingIdentity(token);
2019 }
2020 }
2021
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002022 /**
2023 * Try refreshing {@link #mTime} when stale.
2024 */
2025 private void maybeRefreshTrustedTime() {
2026 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002027 mTime.forceRefresh();
2028 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002029 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002030
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002031 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002032 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2033 }
2034
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002035 private static Intent buildAllowBackgroundDataIntent() {
2036 return new Intent(ACTION_ALLOW_BACKGROUND);
2037 }
2038
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002039 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2040 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2041 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2042 return intent;
2043 }
2044
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002045 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2046 final Intent intent = new Intent();
2047 intent.setComponent(new ComponentName(
2048 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2049 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2050 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2051 return intent;
2052 }
2053
2054 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2055 final Intent intent = new Intent();
2056 intent.setComponent(new ComponentName(
2057 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2058 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2059 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2060 return intent;
2061 }
2062
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002063 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002064 public void addIdleHandler(IdleHandler handler) {
2065 mHandler.getLooper().getQueue().addIdleHandler(handler);
2066 }
2067
Jeff Sharkey1b861272011-05-22 00:34:52 -07002068 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2069 final int size = source.size();
2070 for (int i = 0; i < size; i++) {
2071 target.put(source.keyAt(i), true);
2072 }
2073 }
2074
2075 private static void collectKeys(SparseBooleanArray source, SparseBooleanArray target) {
2076 final int size = source.size();
2077 for (int i = 0; i < size; i++) {
2078 target.put(source.keyAt(i), true);
2079 }
2080 }
2081
2082 private static void dumpSparseBooleanArray(PrintWriter fout, SparseBooleanArray value) {
2083 fout.print("[");
2084 final int size = value.size();
2085 for (int i = 0; i < size; i++) {
2086 fout.print(value.keyAt(i) + "=" + value.valueAt(i));
2087 if (i < size - 1) fout.print(",");
2088 }
2089 fout.print("]");
2090 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002091
Jeff Sharkey46645002011-07-27 21:11:21 -07002092 public static class XmlUtils {
2093 public static int readIntAttribute(XmlPullParser in, String name) throws IOException {
2094 final String value = in.getAttributeValue(null, name);
2095 try {
2096 return Integer.parseInt(value);
2097 } catch (NumberFormatException e) {
2098 throw new ProtocolException("problem parsing " + name + "=" + value + " as int");
2099 }
2100 }
2101
2102 public static void writeIntAttribute(XmlSerializer out, String name, int value)
2103 throws IOException {
2104 out.attribute(null, name, Integer.toString(value));
2105 }
2106
2107 public static long readLongAttribute(XmlPullParser in, String name) throws IOException {
2108 final String value = in.getAttributeValue(null, name);
2109 try {
2110 return Long.parseLong(value);
2111 } catch (NumberFormatException e) {
2112 throw new ProtocolException("problem parsing " + name + "=" + value + " as long");
2113 }
2114 }
2115
2116 public static void writeLongAttribute(XmlSerializer out, String name, long value)
2117 throws IOException {
2118 out.attribute(null, name, Long.toString(value));
2119 }
2120
2121 public static boolean readBooleanAttribute(XmlPullParser in, String name) {
2122 final String value = in.getAttributeValue(null, name);
2123 return Boolean.parseBoolean(value);
2124 }
2125
2126 public static void writeBooleanAttribute(XmlSerializer out, String name, boolean value)
2127 throws IOException {
2128 out.attribute(null, name, Boolean.toString(value));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002129 }
2130 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002131}