blob: d568b11c70a17f2aa63294cf73cd4f079a4570de [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey1b861272011-05-22 00:34:52 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070022import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070025import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070026import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070027import static android.content.Intent.ACTION_USER_ADDED;
28import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070029import static android.content.Intent.EXTRA_UID;
Jeff Sharkey961e3042011-08-29 16:02:57 -070030import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070031import static android.net.ConnectivityManager.TYPE_ETHERNET;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070032import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070033import static android.net.ConnectivityManager.TYPE_WIFI;
34import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070035import static android.net.ConnectivityManager.isNetworkTypeMobile;
36import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070037import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070038import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070039import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070040import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070041import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070042import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070043import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070044import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070045import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Jeff Sharkey1b861272011-05-22 00:34:52 -070046import static android.net.NetworkPolicyManager.dumpPolicy;
47import static android.net.NetworkPolicyManager.dumpRules;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070048import static android.net.NetworkTemplate.MATCH_ETHERNET;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070049import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
50import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070051import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
52import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070053import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080054import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070055import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
56import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
57import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
58import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
59import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
60import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
61import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -070062import static android.telephony.TelephonyManager.SIM_STATE_READY;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070063import static android.text.format.DateUtils.DAY_IN_MILLIS;
Jeff Sharkey854b2b12012-04-13 16:03:40 -070064import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070065import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070066import static com.android.internal.util.XmlUtils.readBooleanAttribute;
67import static com.android.internal.util.XmlUtils.readIntAttribute;
68import static com.android.internal.util.XmlUtils.readLongAttribute;
69import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
70import static com.android.internal.util.XmlUtils.writeIntAttribute;
71import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070072import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070073import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070074import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
75import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070076
Jeff Sharkeya4620792011-05-20 15:29:23 -070077import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070078import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070079import android.app.IProcessObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070080import android.app.Notification;
81import android.app.PendingIntent;
Jeff Sharkeya4620792011-05-20 15:29:23 -070082import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070083import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070084import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070085import android.content.Intent;
86import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070087import android.content.pm.ApplicationInfo;
88import android.content.pm.PackageManager;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -070089import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -070090import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070091import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070092import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070093import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070094import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070095import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -070096import android.net.INetworkStatsService;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070097import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070098import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070099import android.net.NetworkPolicy;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700100import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700101import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700102import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700103import android.net.wifi.WifiConfiguration;
104import android.net.wifi.WifiInfo;
105import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700106import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700107import android.os.Environment;
108import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700109import android.os.HandlerThread;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700110import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700111import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700112import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700113import android.os.MessageQueue.IdleHandler;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700114import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700115import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700116import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700117import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700118import android.provider.Settings;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700119import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700120import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700121import android.text.format.Time;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700122import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700123import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700124import android.util.NtpTrustedTime;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700125import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700126import android.util.SparseArray;
127import android.util.SparseBooleanArray;
128import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700129import android.util.TrustedTime;
130import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700131
Jeff Sharkey497e4432011-06-14 17:27:29 -0700132import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800133import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700134import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700135import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700136import com.android.internal.util.Objects;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700137import com.google.android.collect.Lists;
138import com.google.android.collect.Maps;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700139import com.google.android.collect.Sets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700140
141import org.xmlpull.v1.XmlPullParser;
142import org.xmlpull.v1.XmlPullParserException;
143import org.xmlpull.v1.XmlSerializer;
144
145import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700146import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700147import java.io.FileInputStream;
148import java.io.FileNotFoundException;
149import java.io.FileOutputStream;
150import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700151import java.io.PrintWriter;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700152import java.util.ArrayList;
153import java.util.Arrays;
154import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700155import java.util.HashSet;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700156import java.util.List;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700157import java.util.Map;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700158
159import libcore.io.IoUtils;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700160
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700161/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700162 * Service that maintains low-level network policy rules, using
163 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700164 * <p>
165 * Derives active rules by combining a given policy with other system status,
166 * and delivers to listeners, such as {@link ConnectivityManager}, for
167 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700168 */
169public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
170 private static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700171 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700172 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700173
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700174 private static final int VERSION_INIT = 1;
175 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700176 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800177 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800178 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800179 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700180 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700181 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700182 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700183 private static final int VERSION_SWITCH_UID = 10;
184 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700185
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800186 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700187 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800188 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700189 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800190 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700191 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700192
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700193 private static final String TAG_POLICY_LIST = "policy-list";
194 private static final String TAG_NETWORK_POLICY = "network-policy";
195 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700196 private static final String TAG_APP_POLICY = "app-policy";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700197
198 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700199 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700200 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
201 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700202 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700203 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800204 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700205 private static final String ATTR_WARNING_BYTES = "warningBytes";
206 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700207 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800208 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
209 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800210 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700211 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700212 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700213 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700214 private static final String ATTR_POLICY = "policy";
215
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700216 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
217
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800218 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800219 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800220 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800221 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700222
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700223 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
224
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700225 private static final int MSG_RULES_CHANGED = 1;
226 private static final int MSG_METERED_IFACES_CHANGED = 2;
227 private static final int MSG_FOREGROUND_ACTIVITIES_CHANGED = 3;
228 private static final int MSG_PROCESS_DIED = 4;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800229 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800230 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700231 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700232 private static final int MSG_SCREEN_ON_CHANGED = 8;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700233
Jeff Sharkey75279902011-05-24 18:39:45 -0700234 private final Context mContext;
235 private final IActivityManager mActivityManager;
236 private final IPowerManager mPowerManager;
237 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700238 private final INetworkManagementService mNetworkManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700239 private final TrustedTime mTime;
240
241 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700242 private INotificationManager mNotifManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700243
Jeff Sharkey75279902011-05-24 18:39:45 -0700244 private final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700245
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700246 private volatile boolean mScreenOn;
247 private volatile boolean mRestrictBackground;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700248
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700249 private final boolean mSuppressDefaultPolicy;
250
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700251 /** Defined network policies. */
252 private HashMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = Maps.newHashMap();
253 /** Currently active network rules for ifaces. */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700254 private HashMap<NetworkPolicy, String[]> mNetworkRules = Maps.newHashMap();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700255
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700256 /** Defined UID policies. */
257 private SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700258 /** Currently derived rules for each UID. */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700259 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700260
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700261 /** Set of ifaces that are metered. */
262 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700263 /** Set of over-limit templates that have been notified. */
264 private HashSet<NetworkTemplate> mOverLimitNotified = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700265
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700266 /** Set of currently active {@link Notification} tags. */
267 private HashSet<String> mActiveNotifs = Sets.newHashSet();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700268
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700269 /** Foreground at both UID and PID granularity. */
Jeff Sharkeya4620792011-05-20 15:29:23 -0700270 private SparseBooleanArray mUidForeground = new SparseBooleanArray();
271 private SparseArray<SparseBooleanArray> mUidPidForeground = new SparseArray<
272 SparseBooleanArray>();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700273
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700274 private final RemoteCallbackList<INetworkPolicyListener> mListeners = new RemoteCallbackList<
275 INetworkPolicyListener>();
276
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700277 private final Handler mHandler;
278
279 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700280
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700281 // TODO: keep whitelist of system-critical services that should never have
282 // rules enforced, such as system, phone, and radio UIDs.
283
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700284 // TODO: migrate notifications to SystemUI
285
Jeff Sharkey75279902011-05-24 18:39:45 -0700286 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700287 IPowerManager powerManager, INetworkStatsService networkStats,
288 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700289 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700290 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700291 }
292
293 private static File getSystemDir() {
294 return new File(Environment.getDataDirectory(), "system");
295 }
296
297 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700298 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700299 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
300 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700301 mContext = checkNotNull(context, "missing context");
302 mActivityManager = checkNotNull(activityManager, "missing activityManager");
303 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700304 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700305 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700306 mTime = checkNotNull(time, "missing TrustedTime");
307
Amith Yamasani450a16b2013-09-18 16:28:50 -0700308 HandlerThread thread = new HandlerThread(TAG);
309 thread.start();
310 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700311
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700312 mSuppressDefaultPolicy = suppressDefaultPolicy;
313
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700314 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
315 }
316
317 public void bindConnectivityManager(IConnectivityManager connManager) {
318 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700319 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700320
Jeff Sharkey497e4432011-06-14 17:27:29 -0700321 public void bindNotificationManager(INotificationManager notifManager) {
322 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
323 }
324
Jeff Sharkeya4620792011-05-20 15:29:23 -0700325 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700326 if (!isBandwidthControlEnabled()) {
327 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
328 return;
329 }
330
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700331 synchronized (mRulesLock) {
332 // read policy from disk
333 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700334
335 if (mRestrictBackground) {
336 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700337 updateNotificationsLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700338 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700339 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700340
Jeff Sharkeya4620792011-05-20 15:29:23 -0700341 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700342
Jeff Sharkeya4620792011-05-20 15:29:23 -0700343 try {
344 mActivityManager.registerProcessObserver(mProcessObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700345 mNetworkManager.registerObserver(mAlertObserver);
346 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700347 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700348 }
349
Jeff Sharkeya4620792011-05-20 15:29:23 -0700350 // TODO: traverse existing processes to know foreground state, or have
351 // activitymanager dispatch current state when new observer attached.
352
353 final IntentFilter screenFilter = new IntentFilter();
354 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
355 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700356 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700357
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700358 // watch for network interfaces to be claimed
Jeff Sharkey961e3042011-08-29 16:02:57 -0700359 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION_IMMEDIATE);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700360 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
361
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700362 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700363 final IntentFilter packageFilter = new IntentFilter();
364 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700365 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700366 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700367
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700368 // listen for UID changes to update policy
369 mContext.registerReceiver(
370 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
371
372 // listen for user changes to update policy
373 final IntentFilter userFilter = new IntentFilter();
374 userFilter.addAction(ACTION_USER_ADDED);
375 userFilter.addAction(ACTION_USER_REMOVED);
376 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
377
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700378 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700379 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
380 mContext.registerReceiver(
381 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
382
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700383 // listen for restrict background changes from notifications
384 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
385 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
386
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800387 // listen for snooze warning from notifications
388 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
389 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
390 MANAGE_NETWORK_POLICY, mHandler);
391
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700392 // listen for configured wifi networks to be removed
393 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
394 mContext.registerReceiver(
395 mWifiConfigReceiver, wifiConfigFilter, CONNECTIVITY_INTERNAL, mHandler);
396
397 // listen for wifi state changes to catch metered hint
398 final IntentFilter wifiStateFilter = new IntentFilter(
399 WifiManager.NETWORK_STATE_CHANGED_ACTION);
400 mContext.registerReceiver(
401 mWifiStateReceiver, wifiStateFilter, CONNECTIVITY_INTERNAL, mHandler);
402
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700403 }
404
Jeff Sharkeya4620792011-05-20 15:29:23 -0700405 private IProcessObserver mProcessObserver = new IProcessObserver.Stub() {
406 @Override
407 public void onForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700408 mHandler.obtainMessage(MSG_FOREGROUND_ACTIVITIES_CHANGED,
409 pid, uid, foregroundActivities).sendToTarget();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700410 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700411
412 @Override
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700413 public void onImportanceChanged(int pid, int uid, int importance) {
414 }
415
416 @Override
Jeff Sharkeya4620792011-05-20 15:29:23 -0700417 public void onProcessDied(int pid, int uid) {
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700418 mHandler.obtainMessage(MSG_PROCESS_DIED, pid, uid).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700419 }
420 };
421
422 private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
423 @Override
424 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800425 // screen-related broadcasts are protected by system, no need
426 // for permissions check.
427 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700428 }
429 };
430
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700431 private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700432 @Override
433 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700434 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700435
436 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700437 final int uid = intent.getIntExtra(EXTRA_UID, -1);
438 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700439
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700440 if (ACTION_PACKAGE_ADDED.equals(action)) {
441 // update rules for UID, since it might be subject to
442 // global background data policy
443 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
444 synchronized (mRulesLock) {
445 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700446 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700447 }
448 }
449 };
450
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700451 private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
452 @Override
453 public void onReceive(Context context, Intent intent) {
454 // on background handler thread, and UID_REMOVED is protected
455
456 final int uid = intent.getIntExtra(EXTRA_UID, -1);
457 if (uid == -1) return;
458
459 // remove any policy and update rules to clean up
460 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
461 synchronized (mRulesLock) {
462 mUidPolicy.delete(uid);
463 updateRulesForUidLocked(uid);
464 writePolicyLocked();
465 }
466 }
467 };
468
469 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
470 @Override
471 public void onReceive(Context context, Intent intent) {
472 // on background handler thread, and USER_ADDED and USER_REMOVED
473 // broadcasts are protected
474
475 final String action = intent.getAction();
476 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
477 if (userId == -1) return;
478
479 // Remove any policies for given user; both cleaning up after a
480 // USER_REMOVED, and one last sanity check during USER_ADDED
481 removePoliciesForUserLocked(userId);
482
483 // Update global restrict for new user
484 synchronized (mRulesLock) {
485 updateRulesForRestrictBackgroundLocked();
486 }
487 }
488 };
489
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700490 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700491 * Receiver that watches for {@link INetworkStatsService} updates, which we
492 * use to check against {@link NetworkPolicy#warningBytes}.
493 */
494 private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
495 @Override
496 public void onReceive(Context context, Intent intent) {
497 // on background handler thread, and verified
498 // READ_NETWORK_USAGE_HISTORY permission above.
499
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800500 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700501 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700502 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700503 updateNotificationsLocked();
504 }
505 }
506 };
507
508 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700509 * Receiver that watches for {@link Notification} control of
510 * {@link #mRestrictBackground}.
511 */
512 private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
513 @Override
514 public void onReceive(Context context, Intent intent) {
515 // on background handler thread, and verified MANAGE_NETWORK_POLICY
516 // permission above.
517
518 setRestrictBackground(false);
519 }
520 };
521
522 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800523 * Receiver that watches for {@link Notification} control of
524 * {@link NetworkPolicy#lastWarningSnooze}.
525 */
526 private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
527 @Override
528 public void onReceive(Context context, Intent intent) {
529 // on background handler thread, and verified MANAGE_NETWORK_POLICY
530 // permission above.
531
532 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
533 performSnooze(template, TYPE_WARNING);
534 }
535 };
536
537 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700538 * Receiver that watches for {@link WifiConfiguration} to be changed.
539 */
540 private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
541 @Override
542 public void onReceive(Context context, Intent intent) {
543 // on background handler thread, and verified CONNECTIVITY_INTERNAL
544 // permission above.
545
546 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
547 if (reason == CHANGE_REASON_REMOVED) {
548 final WifiConfiguration config = intent.getParcelableExtra(
549 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700550 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800551 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700552 synchronized (mRulesLock) {
553 if (mNetworkPolicy.containsKey(template)) {
554 mNetworkPolicy.remove(template);
555 writePolicyLocked();
556 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700557 }
558 }
559 }
560 }
561 };
562
563 /**
564 * Receiver that watches {@link WifiInfo} state changes to infer metered
565 * state. Ignores hints when policy is user-defined.
566 */
567 private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
568 @Override
569 public void onReceive(Context context, Intent intent) {
570 // on background handler thread, and verified CONNECTIVITY_INTERNAL
571 // permission above.
572
573 // ignore when not connected
574 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
575 if (!netInfo.isConnected()) return;
576
577 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
578 final boolean meteredHint = info.getMeteredHint();
579
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800580 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700581 synchronized (mRulesLock) {
582 NetworkPolicy policy = mNetworkPolicy.get(template);
583 if (policy == null && meteredHint) {
584 // policy doesn't exist, and AP is hinting that it's
585 // metered: create an inferred policy.
586 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
587 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
588 meteredHint, true);
589 addNetworkPolicyLocked(policy);
590
591 } else if (policy != null && policy.inferred) {
592 // policy exists, and was inferred: update its current
593 // metered state.
594 policy.metered = meteredHint;
595
596 // since this is inferred for each wifi session, just update
597 // rules without persisting.
598 updateNetworkRulesLocked();
599 }
600 }
601 }
602 };
603
604 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700605 * Observer that watches for {@link INetworkManagementService} alerts.
606 */
Jeff Sharkey216c1812012-08-05 14:29:23 -0700607 private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700608 @Override
609 public void limitReached(String limitName, String iface) {
610 // only someone like NMS should be calling us
611 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
612
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800613 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
614 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700615 }
616 }
617 };
618
619 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700620 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
621 * to show visible notifications as needed.
622 */
623 private void updateNotificationsLocked() {
624 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
625
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700626 // keep track of previously active notifications
627 final HashSet<String> beforeNotifs = Sets.newHashSet();
628 beforeNotifs.addAll(mActiveNotifs);
629 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700630
631 // TODO: when switching to kernel notifications, compute next future
632 // cycle boundary to recompute notifications.
633
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700634 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800635 final long currentTime = currentTimeMillis();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700636 for (NetworkPolicy policy : mNetworkPolicy.values()) {
637 // ignore policies that aren't relevant to user
638 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700639 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700640
Jeff Sharkey497e4432011-06-14 17:27:29 -0700641 final long start = computeLastCycleBoundary(currentTime, policy);
642 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700643 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700644
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700645 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800646 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700647 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
648 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700649 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
650 notifyOverLimitLocked(policy.template);
651 }
652
Jeff Sharkey497e4432011-06-14 17:27:29 -0700653 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700654 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700655
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800656 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700657 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700658 }
659 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700660 }
661
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700662 // ongoing notification when restricting background data
663 if (mRestrictBackground) {
664 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700665 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700666
667 // cancel stale notifications that we didn't renew above
668 for (String tag : beforeNotifs) {
669 if (!mActiveNotifs.contains(tag)) {
670 cancelNotification(tag);
671 }
672 }
673 }
674
675 /**
676 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700677 * current device state, such as when
678 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
679 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700680 */
681 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700682 final TelephonyManager tele = TelephonyManager.from(mContext);
683
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700684 switch (template.getMatchRule()) {
685 case MATCH_MOBILE_3G_LOWER:
686 case MATCH_MOBILE_4G:
687 case MATCH_MOBILE_ALL:
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700688 // mobile templates are relevant when SIM is ready and
689 // subscriberId matches.
690 if (tele.getSimState() == SIM_STATE_READY) {
691 return Objects.equal(tele.getSubscriberId(), template.getSubscriberId());
692 } else {
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700693 return false;
694 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700695 }
696 return true;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700697 }
698
699 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700700 * Notify that given {@link NetworkTemplate} is over
701 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
702 */
703 private void notifyOverLimitLocked(NetworkTemplate template) {
704 if (!mOverLimitNotified.contains(template)) {
705 mContext.startActivity(buildNetworkOverLimitIntent(template));
706 mOverLimitNotified.add(template);
707 }
708 }
709
710 private void notifyUnderLimitLocked(NetworkTemplate template) {
711 mOverLimitNotified.remove(template);
712 }
713
714 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700715 * Build unique tag that identifies an active {@link NetworkPolicy}
716 * notification of a specific type, like {@link #TYPE_LIMIT}.
717 */
718 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700719 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700720 }
721
722 /**
723 * Show notification for combined {@link NetworkPolicy} and specific type,
724 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
725 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700726 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700727 final String tag = buildNotificationTag(policy, type);
728 final Notification.Builder builder = new Notification.Builder(mContext);
729 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800730 builder.setWhen(0L);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700731
732 final Resources res = mContext.getResources();
733 switch (type) {
734 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700735 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700736 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700737
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700738 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700739 builder.setTicker(title);
740 builder.setContentTitle(title);
741 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700742
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800743 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
744 builder.setDeleteIntent(PendingIntent.getBroadcast(
745 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
746
747 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700748 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800749 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
750
Jeff Sharkey497e4432011-06-14 17:27:29 -0700751 break;
752 }
753 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700754 final CharSequence body = res.getText(R.string.data_usage_limit_body);
755
756 final CharSequence title;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700757 switch (policy.template.getMatchRule()) {
758 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700759 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700760 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700761 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700762 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700763 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700764 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700765 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700766 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700767 case MATCH_WIFI:
768 title = res.getText(R.string.data_usage_wifi_limit_title);
769 break;
770 default:
771 title = null;
772 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700773 }
774
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800775 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700776 builder.setSmallIcon(R.drawable.stat_notify_disabled);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700777 builder.setTicker(title);
778 builder.setContentTitle(title);
779 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700780
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700781 final Intent intent = buildNetworkOverLimitIntent(policy.template);
782 builder.setContentIntent(PendingIntent.getActivity(
783 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
784 break;
785 }
786 case TYPE_LIMIT_SNOOZED: {
787 final long overBytes = totalBytes - policy.limitBytes;
788 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
789 Formatter.formatFileSize(mContext, overBytes));
790
791 final CharSequence title;
792 switch (policy.template.getMatchRule()) {
793 case MATCH_MOBILE_3G_LOWER:
794 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
795 break;
796 case MATCH_MOBILE_4G:
797 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
798 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700799 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700800 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
801 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700802 case MATCH_WIFI:
803 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
804 break;
805 default:
806 title = null;
807 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700808 }
809
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800810 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700811 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700812 builder.setTicker(title);
813 builder.setContentTitle(title);
814 builder.setContentText(body);
815
816 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700817 builder.setContentIntent(PendingIntent.getActivity(
818 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700819 break;
820 }
821 }
822
823 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700824 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700825 try {
826 final String packageName = mContext.getPackageName();
827 final int[] idReceived = new int[1];
828 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800829 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Dianne Hackborn41203752012-08-31 14:05:51 -0700830 UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700831 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700832 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700833 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700834 }
835 }
836
837 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700838 * Show ongoing notification to reflect that {@link #mRestrictBackground}
839 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700840 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700841 private void enqueueRestrictedNotification(String tag) {
842 final Resources res = mContext.getResources();
843 final Notification.Builder builder = new Notification.Builder(mContext);
844
845 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
846 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
847
848 builder.setOnlyAlertOnce(true);
849 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700850 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700851 builder.setTicker(title);
852 builder.setContentTitle(title);
853 builder.setContentText(body);
854
855 final Intent intent = buildAllowBackgroundDataIntent();
856 builder.setContentIntent(
857 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700858
859 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700860 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700861 try {
862 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700863 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800864 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Dianne Hackborn41203752012-08-31 14:05:51 -0700865 0x0, builder.getNotification(), idReceived, UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700866 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700867 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700868 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700869 }
870 }
871
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700872 private void cancelNotification(String tag) {
873 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700874 // XXX what to do about multi-user?
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700875 try {
876 final String packageName = mContext.getPackageName();
877 mNotifManager.cancelNotificationWithTag(
Dianne Hackborn41203752012-08-31 14:05:51 -0700878 packageName, tag, 0x0, UserHandle.USER_OWNER);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700879 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700880 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700881 }
882 }
883
884 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700885 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700886 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700887 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700888 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700889 @Override
890 public void onReceive(Context context, Intent intent) {
891 // on background handler thread, and verified CONNECTIVITY_INTERNAL
892 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800893
894 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700895 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700896 ensureActiveMobilePolicyLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700897 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700898 updateNetworkRulesLocked();
899 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700900 }
901 }
902 };
903
904 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700905 * Proactively control network data connections when they exceed
906 * {@link NetworkPolicy#limitBytes}.
907 */
908 private void updateNetworkEnabledLocked() {
909 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
910
911 // TODO: reset any policy-disabled networks when any policy is removed
912 // completely, which is currently rare case.
913
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800914 final long currentTime = currentTimeMillis();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700915 for (NetworkPolicy policy : mNetworkPolicy.values()) {
916 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700917 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700918 setNetworkTemplateEnabled(policy.template, true);
919 continue;
920 }
921
922 final long start = computeLastCycleBoundary(currentTime, policy);
923 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700924 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700925
926 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800927 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
928 && policy.lastLimitSnooze < start;
929 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700930
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800931 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700932 }
933 }
934
935 /**
936 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}
937 * for the given {@link NetworkTemplate}.
938 */
939 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700940 final TelephonyManager tele = TelephonyManager.from(mContext);
941
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700942 switch (template.getMatchRule()) {
943 case MATCH_MOBILE_3G_LOWER:
944 case MATCH_MOBILE_4G:
945 case MATCH_MOBILE_ALL:
946 // TODO: offer more granular control over radio states once
947 // 4965893 is available.
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700948 if (tele.getSimState() == SIM_STATE_READY
949 && Objects.equal(tele.getSubscriberId(), template.getSubscriberId())) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700950 setPolicyDataEnable(TYPE_MOBILE, enabled);
951 setPolicyDataEnable(TYPE_WIMAX, enabled);
952 }
953 break;
954 case MATCH_WIFI:
955 setPolicyDataEnable(TYPE_WIFI, enabled);
956 break;
957 case MATCH_ETHERNET:
958 setPolicyDataEnable(TYPE_ETHERNET, enabled);
959 break;
960 default:
961 throw new IllegalArgumentException("unexpected template");
962 }
963 }
964
965 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700966 * Examine all connected {@link NetworkState}, looking for
967 * {@link NetworkPolicy} that need to be enforced. When matches found, set
968 * remaining quota based on usage cycle and historical stats.
969 */
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700970 private void updateNetworkRulesLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700971 if (LOGV) Slog.v(TAG, "updateIfacesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700972
973 final NetworkState[] states;
974 try {
975 states = mConnManager.getAllNetworkState();
976 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700977 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700978 return;
979 }
980
981 // first, derive identity for all connected networks, which can be used
982 // to match against templates.
983 final HashMap<NetworkIdentity, String> networks = Maps.newHashMap();
984 for (NetworkState state : states) {
985 // stash identity and iface away for later use
986 if (state.networkInfo.isConnected()) {
987 final String iface = state.linkProperties.getInterfaceName();
988 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
989 networks.put(ident, iface);
990 }
991 }
992
993 // build list of rules and ifaces to enforce them against
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700994 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700995 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700996 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700997
998 // collect all active ifaces that match this template
999 ifaceList.clear();
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001000 for (Map.Entry<NetworkIdentity, String> entry : networks.entrySet()) {
1001 final NetworkIdentity ident = entry.getKey();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001002 if (policy.template.matches(ident)) {
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001003 final String iface = entry.getValue();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001004 ifaceList.add(iface);
1005 }
1006 }
1007
1008 if (ifaceList.size() > 0) {
1009 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001010 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001011 }
1012 }
1013
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001014 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001015 final HashSet<String> newMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001016
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001017 // apply each policy that we found ifaces for; compute remaining data
1018 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001019 final long currentTime = currentTimeMillis();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001020 for (NetworkPolicy policy : mNetworkRules.keySet()) {
1021 final String[] ifaces = mNetworkRules.get(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001022
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001023 final long start;
1024 final long totalBytes;
1025 if (policy.hasCycle()) {
1026 start = computeLastCycleBoundary(currentTime, policy);
1027 totalBytes = getTotalBytes(policy.template, start, currentTime);
1028 } else {
1029 start = Long.MAX_VALUE;
1030 totalBytes = 0;
1031 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001032
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001033 if (LOGD) {
1034 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001035 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001036 }
1037
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001038 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001039 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001040 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001041 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001042 if (!hasLimit) {
1043 // metered network, but no policy limit; we still need to
1044 // restrict apps, so push really high quota.
1045 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001046 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001047 // snoozing past quota, but we still need to restrict apps,
1048 // so push really high quota.
1049 quotaBytes = Long.MAX_VALUE;
1050 } else {
1051 // remaining "quota" bytes are based on total usage in
1052 // current cycle. kernel doesn't like 0-byte rules, so we
1053 // set 1-byte quota and disable the radio later.
1054 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1055 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001056
1057 if (ifaces.length > 1) {
1058 // TODO: switch to shared quota once NMS supports
1059 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001060 }
1061
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001062 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001063 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001064 setInterfaceQuota(iface, quotaBytes);
1065 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001066 }
1067 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001068
1069 // keep track of lowest warning or limit of active policies
1070 if (hasWarning && policy.warningBytes < lowestRule) {
1071 lowestRule = policy.warningBytes;
1072 }
1073 if (hasLimit && policy.limitBytes < lowestRule) {
1074 lowestRule = policy.limitBytes;
1075 }
1076 }
1077
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001078 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001079
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001080 // remove quota on any trailing interfaces
1081 for (String iface : mMeteredIfaces) {
1082 if (!newMeteredIfaces.contains(iface)) {
1083 removeInterfaceQuota(iface);
1084 }
1085 }
1086 mMeteredIfaces = newMeteredIfaces;
1087
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001088 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001089 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001090 }
1091
1092 /**
1093 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1094 * have at least a default mobile policy defined.
1095 */
1096 private void ensureActiveMobilePolicyLocked() {
1097 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001098 if (mSuppressDefaultPolicy) return;
1099
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001100 final TelephonyManager tele = TelephonyManager.from(mContext);
1101
1102 // avoid creating policy when SIM isn't ready
1103 if (tele.getSimState() != SIM_STATE_READY) return;
1104
1105 final String subscriberId = tele.getSubscriberId();
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001106 final NetworkIdentity probeIdent = new NetworkIdentity(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001107 TYPE_MOBILE, TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001108
1109 // examine to see if any policy is defined for active mobile
1110 boolean mobileDefined = false;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001111 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001112 if (policy.template.matches(probeIdent)) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001113 mobileDefined = true;
1114 }
1115 }
1116
1117 if (!mobileDefined) {
1118 Slog.i(TAG, "no policy for active mobile network; generating default policy");
1119
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001120 // build default mobile policy, and assume usage cycle starts today
1121 final long warningBytes = mContext.getResources().getInteger(
1122 com.android.internal.R.integer.config_networkPolicyDefaultWarning)
1123 * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001124
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001125 final Time time = new Time();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001126 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001127
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001128 final int cycleDay = time.monthDay;
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001129 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001130
Jeff Sharkey4e814c32011-07-14 20:37:37 -07001131 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001132 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1133 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1134 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001135 }
1136 }
1137
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001138 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001139 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001140
1141 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001142 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001143 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001144
1145 FileInputStream fis = null;
1146 try {
1147 fis = mPolicyFile.openRead();
1148 final XmlPullParser in = Xml.newPullParser();
1149 in.setInput(fis, null);
1150
1151 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001152 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001153 while ((type = in.next()) != END_DOCUMENT) {
1154 final String tag = in.getName();
1155 if (type == START_TAG) {
1156 if (TAG_POLICY_LIST.equals(tag)) {
1157 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001158 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1159 mRestrictBackground = readBooleanAttribute(
1160 in, ATTR_RESTRICT_BACKGROUND);
1161 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001162 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001163 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001164
1165 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1166 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1167 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001168 final String networkId;
1169 if (version >= VERSION_ADDED_NETWORK_ID) {
1170 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1171 } else {
1172 networkId = null;
1173 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001174 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001175 final String cycleTimezone;
1176 if (version >= VERSION_ADDED_TIMEZONE) {
1177 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1178 } else {
1179 cycleTimezone = Time.TIMEZONE_UTC;
1180 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001181 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1182 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001183 final long lastLimitSnooze;
1184 if (version >= VERSION_SPLIT_SNOOZE) {
1185 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1186 } else if (version >= VERSION_ADDED_SNOOZE) {
1187 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001188 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001189 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001190 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001191 final boolean metered;
1192 if (version >= VERSION_ADDED_METERED) {
1193 metered = readBooleanAttribute(in, ATTR_METERED);
1194 } else {
1195 switch (networkTemplate) {
1196 case MATCH_MOBILE_3G_LOWER:
1197 case MATCH_MOBILE_4G:
1198 case MATCH_MOBILE_ALL:
1199 metered = true;
1200 break;
1201 default:
1202 metered = false;
1203 }
1204 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001205 final long lastWarningSnooze;
1206 if (version >= VERSION_SPLIT_SNOOZE) {
1207 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1208 } else {
1209 lastWarningSnooze = SNOOZE_NEVER;
1210 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001211 final boolean inferred;
1212 if (version >= VERSION_ADDED_INFERRED) {
1213 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1214 } else {
1215 inferred = false;
1216 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001217
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001218 final NetworkTemplate template = new NetworkTemplate(
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001219 networkTemplate, subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001220 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001221 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001222 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001223
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001224 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001225 final int uid = readIntAttribute(in, ATTR_UID);
1226 final int policy = readIntAttribute(in, ATTR_POLICY);
1227
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001228 if (UserHandle.isApp(uid)) {
1229 setUidPolicyUnchecked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001230 } else {
1231 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1232 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001233 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001234 final int appId = readIntAttribute(in, ATTR_APP_ID);
1235 final int policy = readIntAttribute(in, ATTR_POLICY);
1236
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001237 // TODO: set for other users during upgrade
1238 final int uid = UserHandle.getUid(UserHandle.USER_OWNER, appId);
1239 if (UserHandle.isApp(uid)) {
1240 setUidPolicyUnchecked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001241 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001242 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001243 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001244 }
1245 }
1246 }
1247
1248 } catch (FileNotFoundException e) {
1249 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001250 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001251 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001252 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001253 } catch (XmlPullParserException 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 } finally {
1256 IoUtils.closeQuietly(fis);
1257 }
1258 }
1259
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001260 /**
1261 * Upgrade legacy background data flags, notifying listeners of one last
1262 * change to always-true.
1263 */
1264 private void upgradeLegacyBackgroundData() {
1265 mRestrictBackground = Settings.Secure.getInt(
1266 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1267
1268 // kick off one last broadcast if restricted
1269 if (mRestrictBackground) {
1270 final Intent broadcast = new Intent(
1271 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001272 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001273 }
1274 }
1275
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001276 private void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001277 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001278
1279 FileOutputStream fos = null;
1280 try {
1281 fos = mPolicyFile.startWrite();
1282
1283 XmlSerializer out = new FastXmlSerializer();
1284 out.setOutput(fos, "utf-8");
1285 out.startDocument(null, true);
1286
1287 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001288 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001289 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001290
1291 // write all known network policies
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001292 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001293 final NetworkTemplate template = policy.template;
1294
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001295 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001296 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1297 final String subscriberId = template.getSubscriberId();
1298 if (subscriberId != null) {
1299 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001300 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001301 final String networkId = template.getNetworkId();
1302 if (networkId != null) {
1303 out.attribute(null, ATTR_NETWORK_ID, networkId);
1304 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001305 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001306 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001307 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1308 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001309 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1310 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001311 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001312 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001313 out.endTag(null, TAG_NETWORK_POLICY);
1314 }
1315
1316 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001317 for (int i = 0; i < mUidPolicy.size(); i++) {
1318 final int uid = mUidPolicy.keyAt(i);
1319 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001320
Jeff Sharkey497e4432011-06-14 17:27:29 -07001321 // skip writing empty policies
1322 if (policy == POLICY_NONE) continue;
1323
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001324 out.startTag(null, TAG_UID_POLICY);
1325 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001326 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001327 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001328 }
1329
1330 out.endTag(null, TAG_POLICY_LIST);
1331 out.endDocument();
1332
1333 mPolicyFile.finishWrite(fos);
1334 } catch (IOException e) {
1335 if (fos != null) {
1336 mPolicyFile.failWrite(fos);
1337 }
1338 }
1339 }
1340
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001341 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001342 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001343 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001344
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001345 if (!UserHandle.isApp(uid)) {
1346 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001347 }
1348
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001349 setUidPolicyUnchecked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001350 }
1351
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001352 private void setUidPolicyUnchecked(int uid, int policy, boolean persist) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001353 final int oldPolicy;
Jeff Sharkeya4620792011-05-20 15:29:23 -07001354 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001355 oldPolicy = getUidPolicy(uid);
1356 mUidPolicy.put(uid, policy);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001357
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001358 // uid policy changed, recompute rules and persist policy.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001359 updateRulesForUidLocked(uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001360 if (persist) {
1361 writePolicyLocked();
1362 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001363 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001364 }
1365
1366 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001367 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001368 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1369
Jeff Sharkeya4620792011-05-20 15:29:23 -07001370 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001371 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001372 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001373 }
1374
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001375 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001376 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001377 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1378
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001379 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001380 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001381 for (int i = 0; i < mUidPolicy.size(); i++) {
1382 final int uid = mUidPolicy.keyAt(i);
1383 final int uidPolicy = mUidPolicy.valueAt(i);
1384 if (uidPolicy == policy) {
1385 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001386 }
1387 }
1388 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001389 return uids;
1390 }
1391
1392 /**
1393 * Remove any policies associated with given {@link UserHandle}, persisting
1394 * if any changes are made.
1395 */
1396 private void removePoliciesForUserLocked(int userId) {
1397 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1398
1399 int[] uids = new int[0];
1400 for (int i = 0; i < mUidPolicy.size(); i++) {
1401 final int uid = mUidPolicy.keyAt(i);
1402 if (UserHandle.getUserId(uid) == userId) {
1403 uids = appendInt(uids, uid);
1404 }
1405 }
1406
1407 if (uids.length > 0) {
1408 for (int uid : uids) {
1409 mUidPolicy.delete(uid);
1410 updateRulesForUidLocked(uid);
1411 }
1412 writePolicyLocked();
1413 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001414 }
1415
1416 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001417 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001418 // TODO: create permission for observing network policy
1419 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1420
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001421 mListeners.register(listener);
1422
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001423 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001424 }
1425
1426 @Override
1427 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001428 // TODO: create permission for observing network policy
1429 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1430
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001431 mListeners.unregister(listener);
1432 }
1433
Jeff Sharkey1b861272011-05-22 00:34:52 -07001434 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001435 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001436 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1437
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001438 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001439 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001440 mNetworkPolicy.clear();
1441 for (NetworkPolicy policy : policies) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001442 mNetworkPolicy.put(policy.template, policy);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001443 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001444
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001445 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001446 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001447 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001448 writePolicyLocked();
1449 }
1450 }
1451
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001452 private void addNetworkPolicyLocked(NetworkPolicy policy) {
1453 mNetworkPolicy.put(policy.template, policy);
1454
1455 updateNetworkEnabledLocked();
1456 updateNetworkRulesLocked();
1457 updateNotificationsLocked();
1458 writePolicyLocked();
1459 }
1460
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001461 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001462 public NetworkPolicy[] getNetworkPolicies() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001463 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001464 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001465
1466 synchronized (mRulesLock) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001467 return mNetworkPolicy.values().toArray(new NetworkPolicy[mNetworkPolicy.size()]);
1468 }
1469 }
1470
1471 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001472 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001473 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001474
1475 final long token = Binder.clearCallingIdentity();
1476 try {
1477 performSnooze(template, TYPE_LIMIT);
1478 } finally {
1479 Binder.restoreCallingIdentity(token);
1480 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001481 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001482
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001483 private void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001484 maybeRefreshTrustedTime();
1485 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001486 synchronized (mRulesLock) {
1487 // find and snooze local policy that matches
1488 final NetworkPolicy policy = mNetworkPolicy.get(template);
1489 if (policy == null) {
1490 throw new IllegalArgumentException("unable to find policy for " + template);
1491 }
1492
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001493 switch (type) {
1494 case TYPE_WARNING:
1495 policy.lastWarningSnooze = currentTime;
1496 break;
1497 case TYPE_LIMIT:
1498 policy.lastLimitSnooze = currentTime;
1499 break;
1500 default:
1501 throw new IllegalArgumentException("unexpected type");
1502 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001503
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001504 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001505 updateNetworkRulesLocked();
1506 updateNotificationsLocked();
1507 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001508 }
1509 }
1510
1511 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001512 public void setRestrictBackground(boolean restrictBackground) {
1513 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1514
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001515 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001516 synchronized (mRulesLock) {
1517 mRestrictBackground = restrictBackground;
1518 updateRulesForRestrictBackgroundLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001519 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001520 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001521 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001522
1523 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1524 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001525 }
1526
1527 @Override
1528 public boolean getRestrictBackground() {
1529 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1530
1531 synchronized (mRulesLock) {
1532 return mRestrictBackground;
1533 }
1534 }
1535
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001536 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
1537 for (NetworkPolicy policy : mNetworkPolicy.values()) {
1538 if (policy.template.matches(ident)) {
1539 return policy;
1540 }
1541 }
1542 return null;
1543 }
1544
1545 @Override
1546 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1547 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1548
1549 // only returns usage summary, so we don't require caller to have
1550 // READ_NETWORK_USAGE_HISTORY.
1551 final long token = Binder.clearCallingIdentity();
1552 try {
1553 return getNetworkQuotaInfoUnchecked(state);
1554 } finally {
1555 Binder.restoreCallingIdentity(token);
1556 }
1557 }
1558
1559 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1560 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1561
1562 final NetworkPolicy policy;
1563 synchronized (mRulesLock) {
1564 policy = findPolicyForNetworkLocked(ident);
1565 }
1566
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001567 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001568 // missing policy means we can't derive useful quota info
1569 return null;
1570 }
1571
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001572 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001573
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001574 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001575 final long start = computeLastCycleBoundary(currentTime, policy);
1576 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001577 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001578
1579 // report soft and hard limits under policy
1580 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1581 : NetworkQuotaInfo.NO_LIMIT;
1582 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1583 : NetworkQuotaInfo.NO_LIMIT;
1584
1585 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1586 }
1587
Jeff Sharkey46645002011-07-27 21:11:21 -07001588 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001589 public boolean isNetworkMetered(NetworkState state) {
1590 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1591
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001592 // roaming networks are always considered metered
1593 if (ident.getRoaming()) {
1594 return true;
1595 }
1596
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001597 final NetworkPolicy policy;
1598 synchronized (mRulesLock) {
1599 policy = findPolicyForNetworkLocked(ident);
1600 }
1601
1602 if (policy != null) {
1603 return policy.metered;
1604 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001605 final int type = state.networkInfo.getType();
1606 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1607 return true;
1608 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001609 return false;
1610 }
1611 }
1612
1613 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001614 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001615 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001616
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001617 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1618
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001619 final HashSet<String> argSet = new HashSet<String>();
1620 for (String arg : args) {
1621 argSet.add(arg);
1622 }
1623
Jeff Sharkey1b861272011-05-22 00:34:52 -07001624 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001625 if (argSet.contains("--unsnooze")) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001626 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001627 policy.clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001628 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001629
1630 updateNetworkEnabledLocked();
1631 updateNetworkRulesLocked();
1632 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001633 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001634
1635 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001636 return;
1637 }
1638
Jeff Sharkey46645002011-07-27 21:11:21 -07001639 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001640 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001641 fout.increaseIndent();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001642 for (NetworkPolicy policy : mNetworkPolicy.values()) {
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001643 fout.println(policy.toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001644 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001645 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001646
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001647 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001648 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001649 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001650 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001651 final int uid = mUidPolicy.keyAt(i);
1652 final int policy = mUidPolicy.valueAt(i);
1653 fout.print("UID=");
1654 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001655 fout.print(" policy=");
1656 dumpPolicy(fout, policy);
1657 fout.println();
1658 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001659 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001660
1661 final SparseBooleanArray knownUids = new SparseBooleanArray();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001662 collectKeys(mUidForeground, knownUids);
1663 collectKeys(mUidRules, knownUids);
1664
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001665 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001666 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001667 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001668 for (int i = 0; i < size; i++) {
1669 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001670 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001671 fout.print(uid);
1672
Jeff Sharkey1b861272011-05-22 00:34:52 -07001673 fout.print(" foreground=");
1674 final int foregroundIndex = mUidPidForeground.indexOfKey(uid);
1675 if (foregroundIndex < 0) {
1676 fout.print("UNKNOWN");
1677 } else {
1678 dumpSparseBooleanArray(fout, mUidPidForeground.valueAt(foregroundIndex));
1679 }
1680
1681 fout.print(" rules=");
1682 final int rulesIndex = mUidRules.indexOfKey(uid);
1683 if (rulesIndex < 0) {
1684 fout.print("UNKNOWN");
1685 } else {
1686 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1687 }
1688
1689 fout.println();
1690 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001691 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001692 }
1693 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001694
1695 @Override
1696 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001697 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1698
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001699 synchronized (mRulesLock) {
1700 // only really in foreground when screen is also on
1701 return mUidForeground.get(uid, false) && mScreenOn;
1702 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001703 }
1704
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001705 /**
1706 * Foreground for PID changed; recompute foreground at UID level. If
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001707 * changed, will trigger {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001708 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001709 private void computeUidForegroundLocked(int uid) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001710 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1711
1712 // current pid is dropping foreground; examine other pids
1713 boolean uidForeground = false;
1714 final int size = pidForeground.size();
1715 for (int i = 0; i < size; i++) {
1716 if (pidForeground.valueAt(i)) {
1717 uidForeground = true;
1718 break;
1719 }
1720 }
1721
1722 final boolean oldUidForeground = mUidForeground.get(uid, false);
1723 if (oldUidForeground != uidForeground) {
1724 // foreground changed, push updated rules
1725 mUidForeground.put(uid, uidForeground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001726 updateRulesForUidLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001727 }
1728 }
1729
Jeff Sharkeya4620792011-05-20 15:29:23 -07001730 private void updateScreenOn() {
1731 synchronized (mRulesLock) {
1732 try {
1733 mScreenOn = mPowerManager.isScreenOn();
1734 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001735 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07001736 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001737 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001738 }
1739 }
1740
1741 /**
1742 * Update rules that might be changed by {@link #mScreenOn} value.
1743 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001744 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07001745 // only update rules for anyone with foreground activities
1746 final int size = mUidForeground.size();
1747 for (int i = 0; i < size; i++) {
1748 if (mUidForeground.valueAt(i)) {
1749 final int uid = mUidForeground.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001750 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001751 }
1752 }
1753 }
1754
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001755 /**
Jeff Sharkey46645002011-07-27 21:11:21 -07001756 * Update rules that might be changed by {@link #mRestrictBackground} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001757 */
Jeff Sharkey46645002011-07-27 21:11:21 -07001758 private void updateRulesForRestrictBackgroundLocked() {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001759 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001760 final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1761
1762 // update rules for all installed applications
1763 final List<UserInfo> users = um.getUsers();
1764 final List<ApplicationInfo> apps = pm.getInstalledApplications(
1765 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
1766
1767 for (UserInfo user : users) {
1768 for (ApplicationInfo app : apps) {
1769 final int uid = UserHandle.getUid(user.id, app.uid);
1770 updateRulesForUidLocked(uid);
1771 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001772 }
1773
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001774 // limit data usage for some internal system services
1775 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
1776 updateRulesForUidLocked(android.os.Process.DRM_UID);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001777 }
1778
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001779 private static boolean isUidValidForRules(int uid) {
1780 // allow rules on specific system services, and any apps
1781 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001782 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001783 return true;
1784 }
1785
1786 return false;
1787 }
1788
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001789 private void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001790 if (!isUidValidForRules(uid)) return;
1791
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001792 final int uidPolicy = getUidPolicy(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001793 final boolean uidForeground = isUidForeground(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001794
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001795 // derive active rules based on policy and active state
1796 int uidRules = RULE_ALLOW_ALL;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001797 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001798 // uid in background, and policy says to block metered data
1799 uidRules = RULE_REJECT_METERED;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001800 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001801 if (!uidForeground && mRestrictBackground) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001802 // uid in background, and global background disabled
1803 uidRules = RULE_REJECT_METERED;
1804 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001805
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001806 // TODO: only dispatch when rules actually change
1807
Jeff Sharkey350083e2011-06-29 10:45:16 -07001808 if (uidRules == RULE_ALLOW_ALL) {
1809 mUidRules.delete(uid);
1810 } else {
1811 mUidRules.put(uid, uidRules);
1812 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001813
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001814 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001815 setUidNetworkRules(uid, rejectMetered);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001816
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001817 // dispatch changed rule to existing listeners
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001818 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001819
1820 try {
1821 // adjust stats accounting based on foreground status
1822 mNetworkStats.setUidForeground(uid, uidForeground);
1823 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001824 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07001825 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001826 }
1827
1828 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07001829 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001830 public boolean handleMessage(Message msg) {
1831 switch (msg.what) {
1832 case MSG_RULES_CHANGED: {
1833 final int uid = msg.arg1;
1834 final int uidRules = msg.arg2;
1835 final int length = mListeners.beginBroadcast();
1836 for (int i = 0; i < length; i++) {
1837 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1838 if (listener != null) {
1839 try {
1840 listener.onUidRulesChanged(uid, uidRules);
1841 } catch (RemoteException e) {
1842 }
1843 }
1844 }
1845 mListeners.finishBroadcast();
1846 return true;
1847 }
1848 case MSG_METERED_IFACES_CHANGED: {
1849 final String[] meteredIfaces = (String[]) msg.obj;
1850 final int length = mListeners.beginBroadcast();
1851 for (int i = 0; i < length; i++) {
1852 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1853 if (listener != null) {
1854 try {
1855 listener.onMeteredIfacesChanged(meteredIfaces);
1856 } catch (RemoteException e) {
1857 }
1858 }
1859 }
1860 mListeners.finishBroadcast();
1861 return true;
1862 }
Jeff Sharkey6f7af032011-11-01 18:25:15 -07001863 case MSG_FOREGROUND_ACTIVITIES_CHANGED: {
1864 final int pid = msg.arg1;
1865 final int uid = msg.arg2;
1866 final boolean foregroundActivities = (Boolean) msg.obj;
1867
1868 synchronized (mRulesLock) {
1869 // because a uid can have multiple pids running inside, we need to
1870 // remember all pid states and summarize foreground at uid level.
1871
1872 // record foreground for this specific pid
1873 SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1874 if (pidForeground == null) {
1875 pidForeground = new SparseBooleanArray(2);
1876 mUidPidForeground.put(uid, pidForeground);
1877 }
1878 pidForeground.put(pid, foregroundActivities);
1879 computeUidForegroundLocked(uid);
1880 }
1881 return true;
1882 }
1883 case MSG_PROCESS_DIED: {
1884 final int pid = msg.arg1;
1885 final int uid = msg.arg2;
1886
1887 synchronized (mRulesLock) {
1888 // clear records and recompute, when they exist
1889 final SparseBooleanArray pidForeground = mUidPidForeground.get(uid);
1890 if (pidForeground != null) {
1891 pidForeground.delete(pid);
1892 computeUidForegroundLocked(uid);
1893 }
1894 }
1895 return true;
1896 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001897 case MSG_LIMIT_REACHED: {
1898 final String iface = (String) msg.obj;
1899
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001900 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001901 synchronized (mRulesLock) {
1902 if (mMeteredIfaces.contains(iface)) {
1903 try {
1904 // force stats update to make sure we have
1905 // numbers that caused alert to trigger.
1906 mNetworkStats.forceUpdate();
1907 } catch (RemoteException e) {
1908 // ignored; service lives in system_server
1909 }
1910
1911 updateNetworkEnabledLocked();
1912 updateNotificationsLocked();
1913 }
1914 }
1915 return true;
1916 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001917 case MSG_RESTRICT_BACKGROUND_CHANGED: {
1918 final boolean restrictBackground = msg.arg1 != 0;
1919 final int length = mListeners.beginBroadcast();
1920 for (int i = 0; i < length; i++) {
1921 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
1922 if (listener != null) {
1923 try {
1924 listener.onRestrictBackgroundChanged(restrictBackground);
1925 } catch (RemoteException e) {
1926 }
1927 }
1928 }
1929 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001930 return true;
1931 }
1932 case MSG_ADVISE_PERSIST_THRESHOLD: {
1933 final long lowestRule = (Long) msg.obj;
1934 try {
1935 // make sure stats are recorded frequently enough; we aim
1936 // for 2MB threshold for 2GB/month rules.
1937 final long persistThreshold = lowestRule / 1000;
1938 mNetworkStats.advisePersistThreshold(persistThreshold);
1939 } catch (RemoteException e) {
1940 // ignored; service lives in system_server
1941 }
1942 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001943 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07001944 case MSG_SCREEN_ON_CHANGED: {
1945 updateScreenOn();
1946 return true;
1947 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001948 default: {
1949 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07001950 }
1951 }
1952 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001953 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001954
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001955 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001956 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001957 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001958 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001959 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001960 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001961 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001962 }
1963 }
1964
1965 private void removeInterfaceQuota(String iface) {
1966 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001967 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001968 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001969 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001970 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001971 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001972 }
1973 }
1974
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001975 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
1976 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001977 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001978 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001979 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001980 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001981 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001982 }
1983 }
1984
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001985 /**
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001986 * Control {@link IConnectivityManager#setPolicyDataEnable(int, boolean)}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001987 */
1988 private void setPolicyDataEnable(int networkType, boolean enabled) {
Jeff Sharkey3f3115b2011-11-08 16:30:37 -08001989 try {
1990 mConnManager.setPolicyDataEnable(networkType, enabled);
1991 } catch (RemoteException e) {
1992 // ignored; service lives in system_server
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001993 }
1994 }
1995
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001996 private long getTotalBytes(NetworkTemplate template, long start, long end) {
1997 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07001998 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08001999 } catch (RuntimeException e) {
2000 Slog.w(TAG, "problem reading network stats: " + e);
2001 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002002 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002003 // ignored; service lives in system_server
2004 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002005 }
2006 }
2007
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002008 private boolean isBandwidthControlEnabled() {
2009 final long token = Binder.clearCallingIdentity();
2010 try {
2011 return mNetworkManager.isBandwidthControlEnabled();
2012 } catch (RemoteException e) {
2013 // ignored; service lives in system_server
2014 return false;
2015 } finally {
2016 Binder.restoreCallingIdentity(token);
2017 }
2018 }
2019
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002020 /**
2021 * Try refreshing {@link #mTime} when stale.
2022 */
2023 private void maybeRefreshTrustedTime() {
2024 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002025 mTime.forceRefresh();
2026 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002027 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002028
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002029 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002030 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2031 }
2032
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002033 private static Intent buildAllowBackgroundDataIntent() {
2034 return new Intent(ACTION_ALLOW_BACKGROUND);
2035 }
2036
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002037 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2038 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2039 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2040 return intent;
2041 }
2042
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002043 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2044 final Intent intent = new Intent();
2045 intent.setComponent(new ComponentName(
2046 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2047 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2048 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2049 return intent;
2050 }
2051
2052 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2053 final Intent intent = new Intent();
2054 intent.setComponent(new ComponentName(
2055 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2056 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2057 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2058 return intent;
2059 }
2060
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002061 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002062 public void addIdleHandler(IdleHandler handler) {
2063 mHandler.getLooper().getQueue().addIdleHandler(handler);
2064 }
2065
Jeff Sharkey1b861272011-05-22 00:34:52 -07002066 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2067 final int size = source.size();
2068 for (int i = 0; i < size; i++) {
2069 target.put(source.keyAt(i), true);
2070 }
2071 }
2072
2073 private static void collectKeys(SparseBooleanArray source, SparseBooleanArray target) {
2074 final int size = source.size();
2075 for (int i = 0; i < size; i++) {
2076 target.put(source.keyAt(i), true);
2077 }
2078 }
2079
2080 private static void dumpSparseBooleanArray(PrintWriter fout, SparseBooleanArray value) {
2081 fout.print("[");
2082 final int size = value.size();
2083 for (int i = 0; i < size; i++) {
2084 fout.print(value.keyAt(i) + "=" + value.valueAt(i));
2085 if (i < size - 1) fout.print(",");
2086 }
2087 fout.print("]");
2088 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002089}