blob: cc0fcf575760cbf3ca7906594934002aa571aa4e [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 Sharkey1b5a2a92011-06-18 18:34:16 -070031import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070032import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070033import static android.net.ConnectivityManager.isNetworkTypeMobile;
34import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070035import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070036import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070037import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070038import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -070039import static android.net.NetworkPolicyManager.POLICY_ALLOW_BACKGROUND_BATTERY_SAVE;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070040import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070041import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070042import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070043import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070044import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Jeff Sharkey1b861272011-05-22 00:34:52 -070045import static android.net.NetworkPolicyManager.dumpPolicy;
46import static android.net.NetworkPolicyManager.dumpRules;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070047import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
48import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070049import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
50import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070051import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080052import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070053import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
54import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
55import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
56import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
57import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
58import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
59import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070060import static android.text.format.DateUtils.DAY_IN_MILLIS;
Jeff Sharkey854b2b12012-04-13 16:03:40 -070061import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070062import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070063import static com.android.internal.util.XmlUtils.readBooleanAttribute;
64import static com.android.internal.util.XmlUtils.readIntAttribute;
65import static com.android.internal.util.XmlUtils.readLongAttribute;
66import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
67import static com.android.internal.util.XmlUtils.writeIntAttribute;
68import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070069import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070070import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070071import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
72import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070073
Dianne Hackborn497175b2014-07-01 12:56:08 -070074import android.app.ActivityManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070075import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070076import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070077import android.app.IProcessObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070078import android.app.Notification;
79import android.app.PendingIntent;
Jeff Sharkeya4620792011-05-20 15:29:23 -070080import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070081import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070082import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070083import android.content.Intent;
84import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070085import android.content.pm.ApplicationInfo;
86import android.content.pm.PackageManager;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -070087import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -070088import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070089import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070090import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070091import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070092import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070093import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -070094import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070095import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070096import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070097import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070098import android.net.NetworkPolicy;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070099import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700100import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700101import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700102import android.net.wifi.WifiConfiguration;
103import android.net.wifi.WifiInfo;
104import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700105import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700106import android.os.Environment;
107import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700108import android.os.HandlerThread;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700109import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700110import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700111import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700112import android.os.MessageQueue.IdleHandler;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700113import android.os.PowerManagerInternal;
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 Sharkey32566012014-12-02 18:30:14 -0800119import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700120import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700121import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700122import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700123import android.util.ArrayMap;
124import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700125import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700126import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700127import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700128import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700129import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700130import android.util.SparseArray;
131import android.util.SparseBooleanArray;
132import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700133import android.util.TrustedTime;
134import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700135
Jeff Sharkey32566012014-12-02 18:30:14 -0800136import libcore.io.IoUtils;
137
Jeff Sharkey497e4432011-06-14 17:27:29 -0700138import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800139import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey32566012014-12-02 18:30:14 -0800140import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700141import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700142import com.android.internal.util.IndentingPrintWriter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700143import com.android.server.LocalServices;
144import com.android.server.SystemConfig;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700145import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700146
147import org.xmlpull.v1.XmlPullParser;
148import org.xmlpull.v1.XmlPullParserException;
149import org.xmlpull.v1.XmlSerializer;
150
151import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700152import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700153import java.io.FileInputStream;
154import java.io.FileNotFoundException;
155import java.io.FileOutputStream;
156import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700157import java.io.PrintWriter;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700158import java.util.ArrayList;
159import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700160import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700161
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700162/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700163 * Service that maintains low-level network policy rules, using
164 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700165 * <p>
166 * Derives active rules by combining a given policy with other system status,
167 * and delivers to listeners, such as {@link ConnectivityManager}, for
168 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700169 */
170public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
171 private static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700172 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700173 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700174
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700175 private static final int VERSION_INIT = 1;
176 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700177 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800178 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800179 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800180 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700181 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700182 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700183 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700184 private static final int VERSION_SWITCH_UID = 10;
185 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700186
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800187 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700188 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800189 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700190 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800191 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700192 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700193
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700194 private static final String TAG_POLICY_LIST = "policy-list";
195 private static final String TAG_NETWORK_POLICY = "network-policy";
196 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700197 private static final String TAG_APP_POLICY = "app-policy";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700198
199 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700200 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700201 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
202 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700203 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700204 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800205 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700206 private static final String ATTR_WARNING_BYTES = "warningBytes";
207 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700208 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800209 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
210 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800211 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700212 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700213 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700214 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700215 private static final String ATTR_POLICY = "policy";
216
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700217 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
218
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800219 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800220 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800221 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800222 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700223
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700224 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
225
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700226 private static final int MSG_RULES_CHANGED = 1;
227 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800228 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800229 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700230 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700231 private static final int MSG_SCREEN_ON_CHANGED = 8;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700232
Jeff Sharkey75279902011-05-24 18:39:45 -0700233 private final Context mContext;
234 private final IActivityManager mActivityManager;
235 private final IPowerManager mPowerManager;
236 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700237 private final INetworkManagementService mNetworkManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700238 private final TrustedTime mTime;
239
240 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700241 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700242 private PowerManagerInternal mPowerManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700243
Dianne Hackborn497175b2014-07-01 12:56:08 -0700244 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700245
Dianne Hackborn497175b2014-07-01 12:56:08 -0700246 volatile boolean mScreenOn;
247 volatile boolean mRestrictBackground;
248 volatile boolean mRestrictPower;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700249
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700250 private final boolean mSuppressDefaultPolicy;
251
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700252 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800253 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700254 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800255 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700256
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700257 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700258 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700259 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800260 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700261
Jeff Sharkey32566012014-12-02 18:30:14 -0800262 /**
263 * UIDs that have been white-listed to always be able to have network access
264 * in power save mode.
265 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700266 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700267
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700268 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800269 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700270 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800271 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700272
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700273 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700274 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700275
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700276 /** Foreground at both UID and PID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800277 final SparseIntArray mUidState = new SparseIntArray();
278 final SparseArray<SparseIntArray> mUidPidState = new SparseArray<>();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700279
280 /** The current maximum process state that we are considering to be foreground. */
281 private int mCurForegroundState = ActivityManager.PROCESS_STATE_TOP;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700282
Jeff Sharkey32566012014-12-02 18:30:14 -0800283 private final RemoteCallbackList<INetworkPolicyListener>
284 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700285
Dianne Hackborn497175b2014-07-01 12:56:08 -0700286 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700287
288 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700289
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700290 // TODO: keep whitelist of system-critical services that should never have
291 // rules enforced, such as system, phone, and radio UIDs.
292
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700293 // TODO: migrate notifications to SystemUI
294
Jeff Sharkey75279902011-05-24 18:39:45 -0700295 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700296 IPowerManager powerManager, INetworkStatsService networkStats,
297 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700298 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700299 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700300 }
301
302 private static File getSystemDir() {
303 return new File(Environment.getDataDirectory(), "system");
304 }
305
306 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700307 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700308 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
309 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700310 mContext = checkNotNull(context, "missing context");
311 mActivityManager = checkNotNull(activityManager, "missing activityManager");
312 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700313 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700314 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700315 mTime = checkNotNull(time, "missing TrustedTime");
316
Amith Yamasani450a16b2013-09-18 16:28:50 -0700317 HandlerThread thread = new HandlerThread(TAG);
318 thread.start();
319 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700320
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700321 mSuppressDefaultPolicy = suppressDefaultPolicy;
322
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700323 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
324 }
325
326 public void bindConnectivityManager(IConnectivityManager connManager) {
327 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700328 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700329
Jeff Sharkey497e4432011-06-14 17:27:29 -0700330 public void bindNotificationManager(INotificationManager notifManager) {
331 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
332 }
333
Jeff Sharkeya4620792011-05-20 15:29:23 -0700334 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700335 if (!isBandwidthControlEnabled()) {
336 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
337 return;
338 }
339
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700340 final PackageManager pm = mContext.getPackageManager();
341
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700342 synchronized (mRulesLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700343 SystemConfig sysConfig = SystemConfig.getInstance();
344 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
345 for (int i=0; i<allowPower.size(); i++) {
346 String pkg = allowPower.valueAt(i);
347 try {
348 ApplicationInfo ai = pm.getApplicationInfo(pkg, 0);
349 if ((ai.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
350 mPowerSaveWhitelistAppIds.put(UserHandle.getAppId(ai.uid), true);
351 }
352 } catch (PackageManager.NameNotFoundException e) {
353 }
354 }
355
356 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
357 mPowerManagerInternal.registerLowPowerModeObserver(
358 new PowerManagerInternal.LowPowerModeListener() {
359 @Override
360 public void onLowPowerModeChanged(boolean enabled) {
361 synchronized (mRulesLock) {
362 if (mRestrictPower != enabled) {
363 mRestrictPower = enabled;
364 updateRulesForGlobalChangeLocked(true);
365 }
366 }
367 }
368 });
369 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
370
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700371 // read policy from disk
372 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700373
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700374 if (mRestrictBackground || mRestrictPower) {
375 updateRulesForGlobalChangeLocked(true);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700376 updateNotificationsLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700377 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700378 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700379
Jeff Sharkeya4620792011-05-20 15:29:23 -0700380 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700381
Jeff Sharkeya4620792011-05-20 15:29:23 -0700382 try {
383 mActivityManager.registerProcessObserver(mProcessObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700384 mNetworkManager.registerObserver(mAlertObserver);
385 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700386 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700387 }
388
Jeff Sharkeya4620792011-05-20 15:29:23 -0700389 // TODO: traverse existing processes to know foreground state, or have
390 // activitymanager dispatch current state when new observer attached.
391
392 final IntentFilter screenFilter = new IntentFilter();
393 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
394 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700395 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700396
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700397 // watch for network interfaces to be claimed
Jeff Sharkey961e3042011-08-29 16:02:57 -0700398 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION_IMMEDIATE);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700399 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
400
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700401 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700402 final IntentFilter packageFilter = new IntentFilter();
403 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700404 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700405 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700406
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700407 // listen for UID changes to update policy
408 mContext.registerReceiver(
409 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
410
411 // listen for user changes to update policy
412 final IntentFilter userFilter = new IntentFilter();
413 userFilter.addAction(ACTION_USER_ADDED);
414 userFilter.addAction(ACTION_USER_REMOVED);
415 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
416
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700417 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700418 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
419 mContext.registerReceiver(
420 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
421
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700422 // listen for restrict background changes from notifications
423 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
424 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
425
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800426 // listen for snooze warning from notifications
427 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
428 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
429 MANAGE_NETWORK_POLICY, mHandler);
430
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700431 // listen for configured wifi networks to be removed
432 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700433 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700434
435 // listen for wifi state changes to catch metered hint
436 final IntentFilter wifiStateFilter = new IntentFilter(
437 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700438 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700439
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700440 }
441
Jeff Sharkeya4620792011-05-20 15:29:23 -0700442 private IProcessObserver mProcessObserver = new IProcessObserver.Stub() {
443 @Override
444 public void onForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700445 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700446
447 @Override
Dianne Hackborn684bf342014-04-29 17:56:57 -0700448 public void onProcessStateChanged(int pid, int uid, int procState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700449 synchronized (mRulesLock) {
450 // because a uid can have multiple pids running inside, we need to
451 // remember all pid states and summarize foreground at uid level.
452
453 // record foreground for this specific pid
454 SparseIntArray pidState = mUidPidState.get(uid);
455 if (pidState == null) {
456 pidState = new SparseIntArray(2);
457 mUidPidState.put(uid, pidState);
458 }
459 pidState.put(pid, procState);
460 computeUidStateLocked(uid);
461 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700462 }
463
464 @Override
Jeff Sharkeya4620792011-05-20 15:29:23 -0700465 public void onProcessDied(int pid, int uid) {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700466 synchronized (mRulesLock) {
467 // clear records and recompute, when they exist
468 final SparseIntArray pidState = mUidPidState.get(uid);
469 if (pidState != null) {
470 pidState.delete(pid);
471 if (pidState.size() <= 0) {
472 mUidPidState.remove(uid);
473 }
474 computeUidStateLocked(uid);
475 }
476 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700477 }
478 };
479
480 private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
481 @Override
482 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800483 // screen-related broadcasts are protected by system, no need
484 // for permissions check.
485 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700486 }
487 };
488
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700489 private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700490 @Override
491 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700492 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700493
494 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700495 final int uid = intent.getIntExtra(EXTRA_UID, -1);
496 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700497
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700498 if (ACTION_PACKAGE_ADDED.equals(action)) {
499 // update rules for UID, since it might be subject to
500 // global background data policy
501 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
502 synchronized (mRulesLock) {
503 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700504 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700505 }
506 }
507 };
508
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700509 private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
510 @Override
511 public void onReceive(Context context, Intent intent) {
512 // on background handler thread, and UID_REMOVED is protected
513
514 final int uid = intent.getIntExtra(EXTRA_UID, -1);
515 if (uid == -1) return;
516
517 // remove any policy and update rules to clean up
518 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
519 synchronized (mRulesLock) {
520 mUidPolicy.delete(uid);
521 updateRulesForUidLocked(uid);
522 writePolicyLocked();
523 }
524 }
525 };
526
527 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
528 @Override
529 public void onReceive(Context context, Intent intent) {
530 // on background handler thread, and USER_ADDED and USER_REMOVED
531 // broadcasts are protected
532
533 final String action = intent.getAction();
534 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
535 if (userId == -1) return;
536
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700537 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700538 // Remove any policies for given user; both cleaning up after a
539 // USER_REMOVED, and one last sanity check during USER_ADDED
540 removePoliciesForUserLocked(userId);
541 // Update global restrict for new user
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700542 updateRulesForGlobalChangeLocked(true);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700543 }
544 }
545 };
546
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700547 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700548 * Receiver that watches for {@link INetworkStatsService} updates, which we
549 * use to check against {@link NetworkPolicy#warningBytes}.
550 */
551 private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
552 @Override
553 public void onReceive(Context context, Intent intent) {
554 // on background handler thread, and verified
555 // READ_NETWORK_USAGE_HISTORY permission above.
556
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800557 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700558 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700559 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700560 updateNotificationsLocked();
561 }
562 }
563 };
564
565 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700566 * Receiver that watches for {@link Notification} control of
567 * {@link #mRestrictBackground}.
568 */
569 private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
570 @Override
571 public void onReceive(Context context, Intent intent) {
572 // on background handler thread, and verified MANAGE_NETWORK_POLICY
573 // permission above.
574
575 setRestrictBackground(false);
576 }
577 };
578
579 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800580 * Receiver that watches for {@link Notification} control of
581 * {@link NetworkPolicy#lastWarningSnooze}.
582 */
583 private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
584 @Override
585 public void onReceive(Context context, Intent intent) {
586 // on background handler thread, and verified MANAGE_NETWORK_POLICY
587 // permission above.
588
589 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
590 performSnooze(template, TYPE_WARNING);
591 }
592 };
593
594 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700595 * Receiver that watches for {@link WifiConfiguration} to be changed.
596 */
597 private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
598 @Override
599 public void onReceive(Context context, Intent intent) {
600 // on background handler thread, and verified CONNECTIVITY_INTERNAL
601 // permission above.
602
603 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
604 if (reason == CHANGE_REASON_REMOVED) {
605 final WifiConfiguration config = intent.getParcelableExtra(
606 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700607 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800608 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700609 synchronized (mRulesLock) {
610 if (mNetworkPolicy.containsKey(template)) {
611 mNetworkPolicy.remove(template);
612 writePolicyLocked();
613 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700614 }
615 }
616 }
617 }
618 };
619
620 /**
621 * Receiver that watches {@link WifiInfo} state changes to infer metered
622 * state. Ignores hints when policy is user-defined.
623 */
624 private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
625 @Override
626 public void onReceive(Context context, Intent intent) {
627 // on background handler thread, and verified CONNECTIVITY_INTERNAL
628 // permission above.
629
630 // ignore when not connected
631 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
632 if (!netInfo.isConnected()) return;
633
634 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
635 final boolean meteredHint = info.getMeteredHint();
636
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800637 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700638 synchronized (mRulesLock) {
639 NetworkPolicy policy = mNetworkPolicy.get(template);
640 if (policy == null && meteredHint) {
641 // policy doesn't exist, and AP is hinting that it's
642 // metered: create an inferred policy.
643 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
644 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
645 meteredHint, true);
646 addNetworkPolicyLocked(policy);
647
648 } else if (policy != null && policy.inferred) {
649 // policy exists, and was inferred: update its current
650 // metered state.
651 policy.metered = meteredHint;
652
653 // since this is inferred for each wifi session, just update
654 // rules without persisting.
655 updateNetworkRulesLocked();
656 }
657 }
658 }
659 };
660
661 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700662 * Observer that watches for {@link INetworkManagementService} alerts.
663 */
Jeff Sharkey216c1812012-08-05 14:29:23 -0700664 private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700665 @Override
666 public void limitReached(String limitName, String iface) {
667 // only someone like NMS should be calling us
668 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
669
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800670 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
671 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700672 }
673 }
674 };
675
676 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700677 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
678 * to show visible notifications as needed.
679 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700680 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700681 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
682
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700683 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700684 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700685 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700686
687 // TODO: when switching to kernel notifications, compute next future
688 // cycle boundary to recompute notifications.
689
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700690 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800691 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700692 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
693 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700694 // ignore policies that aren't relevant to user
695 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700696 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700697
Jeff Sharkey497e4432011-06-14 17:27:29 -0700698 final long start = computeLastCycleBoundary(currentTime, policy);
699 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700700 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700701
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700702 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800703 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700704 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
705 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700706 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
707 notifyOverLimitLocked(policy.template);
708 }
709
Jeff Sharkey497e4432011-06-14 17:27:29 -0700710 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700711 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700712
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800713 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700714 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700715 }
716 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700717 }
718
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700719 // ongoing notification when restricting background data
720 if (mRestrictBackground) {
721 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700722 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700723
724 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700725 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
726 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700727 if (!mActiveNotifs.contains(tag)) {
728 cancelNotification(tag);
729 }
730 }
731 }
732
733 /**
734 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700735 * current device state, such as when
736 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
737 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700738 */
739 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800740 if (template.isMatchRuleMobile()) {
741 final TelephonyManager tele = TelephonyManager.from(mContext);
742 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700743
Jeff Sharkey32566012014-12-02 18:30:14 -0800744 // Mobile template is relevant when any active subscriber matches
745 final int[] subIds = sub.getActiveSubscriptionIdList();
746 for (int subId : subIds) {
747 final String subscriberId = tele.getSubscriberId(subId);
748 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
749 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
750 if (template.matches(probeIdent)) {
751 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700752 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800753 }
754 return false;
755 } else {
756 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700757 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700758 }
759
760 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700761 * Notify that given {@link NetworkTemplate} is over
762 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
763 */
764 private void notifyOverLimitLocked(NetworkTemplate template) {
765 if (!mOverLimitNotified.contains(template)) {
766 mContext.startActivity(buildNetworkOverLimitIntent(template));
767 mOverLimitNotified.add(template);
768 }
769 }
770
771 private void notifyUnderLimitLocked(NetworkTemplate template) {
772 mOverLimitNotified.remove(template);
773 }
774
775 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700776 * Build unique tag that identifies an active {@link NetworkPolicy}
777 * notification of a specific type, like {@link #TYPE_LIMIT}.
778 */
779 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700780 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700781 }
782
783 /**
784 * Show notification for combined {@link NetworkPolicy} and specific type,
785 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
786 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700787 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700788 final String tag = buildNotificationTag(policy, type);
789 final Notification.Builder builder = new Notification.Builder(mContext);
790 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800791 builder.setWhen(0L);
Selim Cinek255dd042014-08-19 22:29:02 +0200792 builder.setColor(mContext.getResources().getColor(
793 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700794
795 final Resources res = mContext.getResources();
796 switch (type) {
797 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700798 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700799 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700800
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700801 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700802 builder.setTicker(title);
803 builder.setContentTitle(title);
804 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700805
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800806 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
807 builder.setDeleteIntent(PendingIntent.getBroadcast(
808 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
809
810 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700811 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800812 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
813
Jeff Sharkey497e4432011-06-14 17:27:29 -0700814 break;
815 }
816 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700817 final CharSequence body = res.getText(R.string.data_usage_limit_body);
818
819 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -0400820 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700821 switch (policy.template.getMatchRule()) {
822 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700823 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700824 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700825 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700826 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700827 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700828 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700829 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700830 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700831 case MATCH_WIFI:
832 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -0400833 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700834 break;
835 default:
836 title = null;
837 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700838 }
839
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800840 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -0400841 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700842 builder.setTicker(title);
843 builder.setContentTitle(title);
844 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700845
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700846 final Intent intent = buildNetworkOverLimitIntent(policy.template);
847 builder.setContentIntent(PendingIntent.getActivity(
848 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
849 break;
850 }
851 case TYPE_LIMIT_SNOOZED: {
852 final long overBytes = totalBytes - policy.limitBytes;
853 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
854 Formatter.formatFileSize(mContext, overBytes));
855
856 final CharSequence title;
857 switch (policy.template.getMatchRule()) {
858 case MATCH_MOBILE_3G_LOWER:
859 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
860 break;
861 case MATCH_MOBILE_4G:
862 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
863 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700864 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700865 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
866 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700867 case MATCH_WIFI:
868 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
869 break;
870 default:
871 title = null;
872 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700873 }
874
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800875 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700876 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700877 builder.setTicker(title);
878 builder.setContentTitle(title);
879 builder.setContentText(body);
880
881 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700882 builder.setContentIntent(PendingIntent.getActivity(
883 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700884 break;
885 }
886 }
887
888 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700889 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700890 try {
891 final String packageName = mContext.getPackageName();
892 final int[] idReceived = new int[1];
893 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800894 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Dianne Hackborn41203752012-08-31 14:05:51 -0700895 UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700896 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700897 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700898 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700899 }
900 }
901
902 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700903 * Show ongoing notification to reflect that {@link #mRestrictBackground}
904 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700905 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700906 private void enqueueRestrictedNotification(String tag) {
907 final Resources res = mContext.getResources();
908 final Notification.Builder builder = new Notification.Builder(mContext);
909
910 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
911 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
912
913 builder.setOnlyAlertOnce(true);
914 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700915 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700916 builder.setTicker(title);
917 builder.setContentTitle(title);
918 builder.setContentText(body);
Selim Cinek255dd042014-08-19 22:29:02 +0200919 builder.setColor(mContext.getResources().getColor(
920 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700921
922 final Intent intent = buildAllowBackgroundDataIntent();
923 builder.setContentIntent(
924 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700925
926 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700927 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700928 try {
929 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700930 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800931 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Dianne Hackborn41203752012-08-31 14:05:51 -0700932 0x0, builder.getNotification(), idReceived, UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700933 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700934 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700935 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700936 }
937 }
938
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700939 private void cancelNotification(String tag) {
940 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700941 // XXX what to do about multi-user?
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700942 try {
943 final String packageName = mContext.getPackageName();
944 mNotifManager.cancelNotificationWithTag(
Dianne Hackborn41203752012-08-31 14:05:51 -0700945 packageName, tag, 0x0, UserHandle.USER_OWNER);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700946 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700947 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700948 }
949 }
950
951 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700952 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700953 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700954 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700955 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700956 @Override
957 public void onReceive(Context context, Intent intent) {
958 // on background handler thread, and verified CONNECTIVITY_INTERNAL
959 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800960
961 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700962 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700963 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -0800964 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700965 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700966 updateNetworkRulesLocked();
967 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700968 }
969 }
970 };
971
972 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700973 * Proactively control network data connections when they exceed
974 * {@link NetworkPolicy#limitBytes}.
975 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700976 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700977 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
978
979 // TODO: reset any policy-disabled networks when any policy is removed
980 // completely, which is currently rare case.
981
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800982 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700983 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
984 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700985 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700986 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700987 setNetworkTemplateEnabled(policy.template, true);
988 continue;
989 }
990
991 final long start = computeLastCycleBoundary(currentTime, policy);
992 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700993 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700994
995 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800996 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
997 && policy.lastLimitSnooze < start;
998 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700999
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001000 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001001 }
1002 }
1003
1004 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001005 * Proactively disable networks that match the given
1006 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001007 */
1008 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001009 // TODO: reach into ConnectivityManager to proactively disable bringing
1010 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001011 }
1012
1013 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001014 * Examine all connected {@link NetworkState}, looking for
1015 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1016 * remaining quota based on usage cycle and historical stats.
1017 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001018 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001019 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001020
1021 final NetworkState[] states;
1022 try {
1023 states = mConnManager.getAllNetworkState();
1024 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001025 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001026 return;
1027 }
1028
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001029 // If we are in restrict power mode, we want to treat all interfaces
1030 // as metered, to restrict access to the network by uid. However, we
1031 // will not have a bandwidth limit. Also only do this if restrict
1032 // background data use is *not* enabled, since that takes precendence
1033 // use over those networks can have a cost associated with it).
1034 final boolean powerSave = mRestrictPower && !mRestrictBackground;
1035
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001036 // First, generate identities of all connected networks so we can
1037 // quickly compare them against all defined policies below.
1038 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001039 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001040 for (NetworkState state : states) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001041 if (state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001042 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001043
1044 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001045 if (baseIface != null) {
1046 connIdents.add(Pair.create(baseIface, ident));
1047 if (powerSave) {
1048 connIfaces.add(baseIface);
1049 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001050 }
1051
1052 // Stacked interfaces are considered to have same identity as
1053 // their parent network.
1054 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1055 for (LinkProperties stackedLink : stackedLinks) {
1056 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001057 if (stackedIface != null) {
1058 connIdents.add(Pair.create(stackedIface, ident));
1059 if (powerSave) {
1060 connIfaces.add(stackedIface);
1061 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001062 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001063 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001064 }
1065 }
1066
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001067 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001068 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001069 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001070 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001071 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001072
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001073 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001074 for (int j = connIdents.size() - 1; j >= 0; j--) {
1075 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1076 if (policy.template.matches(ident.second)) {
1077 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001078 }
1079 }
1080
1081 if (ifaceList.size() > 0) {
1082 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001083 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001084 }
1085 }
1086
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001087 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001088 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001089
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001090 // apply each policy that we found ifaces for; compute remaining data
1091 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001092 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001093 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1094 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1095 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001096
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001097 final long start;
1098 final long totalBytes;
1099 if (policy.hasCycle()) {
1100 start = computeLastCycleBoundary(currentTime, policy);
1101 totalBytes = getTotalBytes(policy.template, start, currentTime);
1102 } else {
1103 start = Long.MAX_VALUE;
1104 totalBytes = 0;
1105 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001106
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001107 if (LOGD) {
1108 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001109 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001110 }
1111
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001112 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001113 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001114 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001115 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001116 if (!hasLimit) {
1117 // metered network, but no policy limit; we still need to
1118 // restrict apps, so push really high quota.
1119 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001120 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001121 // snoozing past quota, but we still need to restrict apps,
1122 // so push really high quota.
1123 quotaBytes = Long.MAX_VALUE;
1124 } else {
1125 // remaining "quota" bytes are based on total usage in
1126 // current cycle. kernel doesn't like 0-byte rules, so we
1127 // set 1-byte quota and disable the radio later.
1128 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1129 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001130
1131 if (ifaces.length > 1) {
1132 // TODO: switch to shared quota once NMS supports
1133 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001134 }
1135
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001136 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001137 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001138 setInterfaceQuota(iface, quotaBytes);
1139 newMeteredIfaces.add(iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001140 if (powerSave) {
1141 connIfaces.remove(iface);
1142 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001143 }
1144 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001145
1146 // keep track of lowest warning or limit of active policies
1147 if (hasWarning && policy.warningBytes < lowestRule) {
1148 lowestRule = policy.warningBytes;
1149 }
1150 if (hasLimit && policy.limitBytes < lowestRule) {
1151 lowestRule = policy.limitBytes;
1152 }
1153 }
1154
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001155 for (int i = connIfaces.size()-1; i >= 0; i--) {
1156 String iface = connIfaces.valueAt(i);
1157 removeInterfaceQuota(iface);
1158 setInterfaceQuota(iface, Long.MAX_VALUE);
1159 newMeteredIfaces.add(iface);
1160 }
1161
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001162 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001163
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001164 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001165 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1166 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001167 if (!newMeteredIfaces.contains(iface)) {
1168 removeInterfaceQuota(iface);
1169 }
1170 }
1171 mMeteredIfaces = newMeteredIfaces;
1172
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001173 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001174 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001175 }
1176
1177 /**
1178 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1179 * have at least a default mobile policy defined.
1180 */
1181 private void ensureActiveMobilePolicyLocked() {
1182 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001183 if (mSuppressDefaultPolicy) return;
1184
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001185 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001186 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001187
Jeff Sharkey32566012014-12-02 18:30:14 -08001188 final int[] subIds = sub.getActiveSubscriptionIdList();
1189 for (int subId : subIds) {
1190 final String subscriberId = tele.getSubscriberId(subId);
1191 ensureActiveMobilePolicyLocked(subscriberId);
1192 }
1193 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001194
Jeff Sharkey32566012014-12-02 18:30:14 -08001195 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1196 // Poke around to see if we already have a policy
1197 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1198 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1199 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1200 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1201 if (template.matches(probeIdent)) {
1202 if (LOGD) {
1203 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1204 + NetworkIdentity.scrubSubscriberId(subscriberId));
1205 }
1206 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001207 }
1208 }
1209
Jeff Sharkey32566012014-12-02 18:30:14 -08001210 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1211 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001212
Jeff Sharkey32566012014-12-02 18:30:14 -08001213 // Build default mobile policy, and assume usage cycle starts today
1214 final long warningBytes = mContext.getResources().getInteger(
1215 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001216
Jeff Sharkey32566012014-12-02 18:30:14 -08001217 final Time time = new Time();
1218 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001219
Jeff Sharkey32566012014-12-02 18:30:14 -08001220 final int cycleDay = time.monthDay;
1221 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001222
Jeff Sharkey32566012014-12-02 18:30:14 -08001223 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1224 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1225 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1226 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001227 }
1228
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001229 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001230 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001231
1232 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001233 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001234 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001235
1236 FileInputStream fis = null;
1237 try {
1238 fis = mPolicyFile.openRead();
1239 final XmlPullParser in = Xml.newPullParser();
1240 in.setInput(fis, null);
1241
1242 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001243 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001244 while ((type = in.next()) != END_DOCUMENT) {
1245 final String tag = in.getName();
1246 if (type == START_TAG) {
1247 if (TAG_POLICY_LIST.equals(tag)) {
1248 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001249 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1250 mRestrictBackground = readBooleanAttribute(
1251 in, ATTR_RESTRICT_BACKGROUND);
1252 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001253 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001254 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001255
1256 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1257 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1258 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001259 final String networkId;
1260 if (version >= VERSION_ADDED_NETWORK_ID) {
1261 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1262 } else {
1263 networkId = null;
1264 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001265 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001266 final String cycleTimezone;
1267 if (version >= VERSION_ADDED_TIMEZONE) {
1268 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1269 } else {
1270 cycleTimezone = Time.TIMEZONE_UTC;
1271 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001272 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1273 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001274 final long lastLimitSnooze;
1275 if (version >= VERSION_SPLIT_SNOOZE) {
1276 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1277 } else if (version >= VERSION_ADDED_SNOOZE) {
1278 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001279 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001280 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001281 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001282 final boolean metered;
1283 if (version >= VERSION_ADDED_METERED) {
1284 metered = readBooleanAttribute(in, ATTR_METERED);
1285 } else {
1286 switch (networkTemplate) {
1287 case MATCH_MOBILE_3G_LOWER:
1288 case MATCH_MOBILE_4G:
1289 case MATCH_MOBILE_ALL:
1290 metered = true;
1291 break;
1292 default:
1293 metered = false;
1294 }
1295 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001296 final long lastWarningSnooze;
1297 if (version >= VERSION_SPLIT_SNOOZE) {
1298 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1299 } else {
1300 lastWarningSnooze = SNOOZE_NEVER;
1301 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001302 final boolean inferred;
1303 if (version >= VERSION_ADDED_INFERRED) {
1304 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1305 } else {
1306 inferred = false;
1307 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001308
Jeff Sharkey32566012014-12-02 18:30:14 -08001309 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1310 subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001311 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001312 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001313 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001314
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001315 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001316 final int uid = readIntAttribute(in, ATTR_UID);
1317 final int policy = readIntAttribute(in, ATTR_POLICY);
1318
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001319 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001320 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001321 } else {
1322 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1323 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001324 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001325 final int appId = readIntAttribute(in, ATTR_APP_ID);
1326 final int policy = readIntAttribute(in, ATTR_POLICY);
1327
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001328 // TODO: set for other users during upgrade
1329 final int uid = UserHandle.getUid(UserHandle.USER_OWNER, appId);
1330 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001331 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001332 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001333 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001334 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001335 }
1336 }
1337 }
1338
1339 } catch (FileNotFoundException e) {
1340 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001341 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001342 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001343 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001344 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001345 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001346 } finally {
1347 IoUtils.closeQuietly(fis);
1348 }
1349 }
1350
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001351 /**
1352 * Upgrade legacy background data flags, notifying listeners of one last
1353 * change to always-true.
1354 */
1355 private void upgradeLegacyBackgroundData() {
1356 mRestrictBackground = Settings.Secure.getInt(
1357 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1358
1359 // kick off one last broadcast if restricted
1360 if (mRestrictBackground) {
1361 final Intent broadcast = new Intent(
1362 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001363 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001364 }
1365 }
1366
Dianne Hackborn497175b2014-07-01 12:56:08 -07001367 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001368 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001369
1370 FileOutputStream fos = null;
1371 try {
1372 fos = mPolicyFile.startWrite();
1373
1374 XmlSerializer out = new FastXmlSerializer();
1375 out.setOutput(fos, "utf-8");
1376 out.startDocument(null, true);
1377
1378 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001379 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001380 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001381
1382 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001383 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1384 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001385 final NetworkTemplate template = policy.template;
1386
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001387 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001388 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1389 final String subscriberId = template.getSubscriberId();
1390 if (subscriberId != null) {
1391 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001392 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001393 final String networkId = template.getNetworkId();
1394 if (networkId != null) {
1395 out.attribute(null, ATTR_NETWORK_ID, networkId);
1396 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001397 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001398 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001399 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1400 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001401 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1402 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001403 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001404 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001405 out.endTag(null, TAG_NETWORK_POLICY);
1406 }
1407
1408 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001409 for (int i = 0; i < mUidPolicy.size(); i++) {
1410 final int uid = mUidPolicy.keyAt(i);
1411 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001412
Jeff Sharkey497e4432011-06-14 17:27:29 -07001413 // skip writing empty policies
1414 if (policy == POLICY_NONE) continue;
1415
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001416 out.startTag(null, TAG_UID_POLICY);
1417 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001418 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001419 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001420 }
1421
1422 out.endTag(null, TAG_POLICY_LIST);
1423 out.endDocument();
1424
1425 mPolicyFile.finishWrite(fos);
1426 } catch (IOException e) {
1427 if (fos != null) {
1428 mPolicyFile.failWrite(fos);
1429 }
1430 }
1431 }
1432
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001433 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001434 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001435 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001436
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001437 if (!UserHandle.isApp(uid)) {
1438 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001439 }
1440
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001441 synchronized (mRulesLock) {
1442 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1443 if (oldPolicy != policy) {
1444 setUidPolicyUncheckedLocked(uid, policy, true);
1445 }
1446 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001447 }
1448
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001449 @Override
1450 public void addUidPolicy(int uid, int policy) {
1451 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001452
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001453 if (!UserHandle.isApp(uid)) {
1454 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1455 }
1456
1457 synchronized (mRulesLock) {
1458 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1459 policy |= oldPolicy;
1460 if (oldPolicy != policy) {
1461 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001462 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001463 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001464 }
1465
1466 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001467 public void removeUidPolicy(int uid, int policy) {
1468 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1469
1470 if (!UserHandle.isApp(uid)) {
1471 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1472 }
1473
1474 synchronized (mRulesLock) {
1475 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1476 policy = oldPolicy & ~policy;
1477 if (oldPolicy != policy) {
1478 setUidPolicyUncheckedLocked(uid, policy, true);
1479 }
1480 }
1481 }
1482
1483 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1484 mUidPolicy.put(uid, policy);
1485
1486 // uid policy changed, recompute rules and persist policy.
1487 updateRulesForUidLocked(uid);
1488 if (persist) {
1489 writePolicyLocked();
1490 }
1491 }
1492
1493 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001494 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001495 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1496
Jeff Sharkeya4620792011-05-20 15:29:23 -07001497 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001498 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001499 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001500 }
1501
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001502 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001503 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001504 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1505
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001506 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001507 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001508 for (int i = 0; i < mUidPolicy.size(); i++) {
1509 final int uid = mUidPolicy.keyAt(i);
1510 final int uidPolicy = mUidPolicy.valueAt(i);
1511 if (uidPolicy == policy) {
1512 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001513 }
1514 }
1515 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001516 return uids;
1517 }
1518
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001519 @Override
1520 public int[] getPowerSaveAppIdWhitelist() {
1521 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1522
1523 synchronized (mRulesLock) {
1524 int size = mPowerSaveWhitelistAppIds.size();
1525 int[] appids = new int[size];
1526 for (int i = 0; i < size; i++) {
1527 appids[i] = mPowerSaveWhitelistAppIds.keyAt(i);
1528 }
1529 return appids;
1530 }
1531 }
1532
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001533 /**
1534 * Remove any policies associated with given {@link UserHandle}, persisting
1535 * if any changes are made.
1536 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001537 void removePoliciesForUserLocked(int userId) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001538 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1539
1540 int[] uids = new int[0];
1541 for (int i = 0; i < mUidPolicy.size(); i++) {
1542 final int uid = mUidPolicy.keyAt(i);
1543 if (UserHandle.getUserId(uid) == userId) {
1544 uids = appendInt(uids, uid);
1545 }
1546 }
1547
1548 if (uids.length > 0) {
1549 for (int uid : uids) {
1550 mUidPolicy.delete(uid);
1551 updateRulesForUidLocked(uid);
1552 }
1553 writePolicyLocked();
1554 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001555 }
1556
1557 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001558 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001559 // TODO: create permission for observing network policy
1560 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1561
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001562 mListeners.register(listener);
1563
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001564 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001565 }
1566
1567 @Override
1568 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001569 // TODO: create permission for observing network policy
1570 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1571
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001572 mListeners.unregister(listener);
1573 }
1574
Jeff Sharkey1b861272011-05-22 00:34:52 -07001575 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001576 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001577 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1578
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001579 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001580 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001581 normalizePoliciesLocked(policies);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001582 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001583 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001584 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001585 writePolicyLocked();
1586 }
1587 }
1588
Dianne Hackborn497175b2014-07-01 12:56:08 -07001589 void addNetworkPolicyLocked(NetworkPolicy policy) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001590 NetworkPolicy[] policies = getNetworkPolicies();
1591 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1592 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001593 }
1594
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001595 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001596 public NetworkPolicy[] getNetworkPolicies() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001597 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001598 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001599
1600 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001601 final int size = mNetworkPolicy.size();
1602 final NetworkPolicy[] policies = new NetworkPolicy[size];
1603 for (int i = 0; i < size; i++) {
1604 policies[i] = mNetworkPolicy.valueAt(i);
1605 }
1606 return policies;
1607 }
1608 }
1609
1610 private void normalizePoliciesLocked() {
1611 normalizePoliciesLocked(getNetworkPolicies());
1612 }
1613
1614 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1615 final TelephonyManager tele = TelephonyManager.from(mContext);
1616 final String[] merged = tele.getMergedSubscriberIds();
1617
1618 mNetworkPolicy.clear();
1619 for (NetworkPolicy policy : policies) {
1620 // When two normalized templates conflict, prefer the most
1621 // restrictive policy
1622 policy.template = NetworkTemplate.normalize(policy.template, merged);
1623 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1624 if (existing == null || existing.compareTo(policy) > 0) {
1625 if (existing != null) {
1626 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1627 }
1628 mNetworkPolicy.put(policy.template, policy);
1629 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001630 }
1631 }
1632
1633 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001634 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001635 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001636
1637 final long token = Binder.clearCallingIdentity();
1638 try {
1639 performSnooze(template, TYPE_LIMIT);
1640 } finally {
1641 Binder.restoreCallingIdentity(token);
1642 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001643 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001644
Dianne Hackborn497175b2014-07-01 12:56:08 -07001645 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001646 maybeRefreshTrustedTime();
1647 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001648 synchronized (mRulesLock) {
1649 // find and snooze local policy that matches
1650 final NetworkPolicy policy = mNetworkPolicy.get(template);
1651 if (policy == null) {
1652 throw new IllegalArgumentException("unable to find policy for " + template);
1653 }
1654
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001655 switch (type) {
1656 case TYPE_WARNING:
1657 policy.lastWarningSnooze = currentTime;
1658 break;
1659 case TYPE_LIMIT:
1660 policy.lastLimitSnooze = currentTime;
1661 break;
1662 default:
1663 throw new IllegalArgumentException("unexpected type");
1664 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001665
Jeff Sharkey32566012014-12-02 18:30:14 -08001666 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001667 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001668 updateNetworkRulesLocked();
1669 updateNotificationsLocked();
1670 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001671 }
1672 }
1673
1674 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001675 public void setRestrictBackground(boolean restrictBackground) {
1676 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1677
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001678 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001679 synchronized (mRulesLock) {
1680 mRestrictBackground = restrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001681 updateRulesForGlobalChangeLocked(false);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001682 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001683 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001684 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001685
1686 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1687 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001688 }
1689
1690 @Override
1691 public boolean getRestrictBackground() {
1692 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1693
1694 synchronized (mRulesLock) {
1695 return mRestrictBackground;
1696 }
1697 }
1698
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001699 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001700 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1701 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001702 if (policy.template.matches(ident)) {
1703 return policy;
1704 }
1705 }
1706 return null;
1707 }
1708
1709 @Override
1710 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1711 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1712
1713 // only returns usage summary, so we don't require caller to have
1714 // READ_NETWORK_USAGE_HISTORY.
1715 final long token = Binder.clearCallingIdentity();
1716 try {
1717 return getNetworkQuotaInfoUnchecked(state);
1718 } finally {
1719 Binder.restoreCallingIdentity(token);
1720 }
1721 }
1722
1723 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1724 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1725
1726 final NetworkPolicy policy;
1727 synchronized (mRulesLock) {
1728 policy = findPolicyForNetworkLocked(ident);
1729 }
1730
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001731 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001732 // missing policy means we can't derive useful quota info
1733 return null;
1734 }
1735
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001736 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001737
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001738 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001739 final long start = computeLastCycleBoundary(currentTime, policy);
1740 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001741 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001742
1743 // report soft and hard limits under policy
1744 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1745 : NetworkQuotaInfo.NO_LIMIT;
1746 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1747 : NetworkQuotaInfo.NO_LIMIT;
1748
1749 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1750 }
1751
Jeff Sharkey46645002011-07-27 21:11:21 -07001752 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001753 public boolean isNetworkMetered(NetworkState state) {
1754 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1755
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001756 // roaming networks are always considered metered
1757 if (ident.getRoaming()) {
1758 return true;
1759 }
1760
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001761 final NetworkPolicy policy;
1762 synchronized (mRulesLock) {
1763 policy = findPolicyForNetworkLocked(ident);
1764 }
1765
1766 if (policy != null) {
1767 return policy.metered;
1768 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001769 final int type = state.networkInfo.getType();
1770 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1771 return true;
1772 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001773 return false;
1774 }
1775 }
1776
1777 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001778 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001779 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001780
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001781 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1782
Dianne Hackborn497175b2014-07-01 12:56:08 -07001783 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001784 for (String arg : args) {
1785 argSet.add(arg);
1786 }
1787
Jeff Sharkey1b861272011-05-22 00:34:52 -07001788 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001789 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001790 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1791 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001792 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001793
Jeff Sharkey32566012014-12-02 18:30:14 -08001794 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001795 updateNetworkEnabledLocked();
1796 updateNetworkRulesLocked();
1797 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001798 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001799
1800 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001801 return;
1802 }
1803
Jeff Sharkey46645002011-07-27 21:11:21 -07001804 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001805 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001806 fout.print("Current foreground state: "); fout.println(mCurForegroundState);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001807 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001808 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001809 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1810 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001811 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001812 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001813
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001814 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
1815
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001816 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001817 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001818 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001819 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001820 final int uid = mUidPolicy.keyAt(i);
1821 final int policy = mUidPolicy.valueAt(i);
1822 fout.print("UID=");
1823 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001824 fout.print(" policy=");
1825 dumpPolicy(fout, policy);
1826 fout.println();
1827 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001828 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001829
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001830 size = mPowerSaveWhitelistAppIds.size();
1831 if (size > 0) {
1832 fout.println("Power save whitelist app ids:");
1833 fout.increaseIndent();
1834 for (int i = 0; i < size; i++) {
1835 fout.print("UID=");
1836 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
1837 fout.print(": ");
1838 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
1839 fout.println();
1840 }
1841 fout.decreaseIndent();
1842 }
1843
Jeff Sharkey1b861272011-05-22 00:34:52 -07001844 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07001845 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001846 collectKeys(mUidRules, knownUids);
1847
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001848 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001849 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001850 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001851 for (int i = 0; i < size; i++) {
1852 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001853 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001854 fout.print(uid);
1855
Dianne Hackborn497175b2014-07-01 12:56:08 -07001856 int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1857 fout.print(" state=");
1858 fout.print(state);
1859 fout.print(state <= mCurForegroundState ? " (fg)" : " (bg)");
1860
1861 fout.print(" pids=");
1862 final int foregroundIndex = mUidPidState.indexOfKey(uid);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001863 if (foregroundIndex < 0) {
1864 fout.print("UNKNOWN");
1865 } else {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001866 dumpSparseIntArray(fout, mUidPidState.valueAt(foregroundIndex));
Jeff Sharkey1b861272011-05-22 00:34:52 -07001867 }
1868
1869 fout.print(" rules=");
1870 final int rulesIndex = mUidRules.indexOfKey(uid);
1871 if (rulesIndex < 0) {
1872 fout.print("UNKNOWN");
1873 } else {
1874 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1875 }
1876
1877 fout.println();
1878 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001879 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001880 }
1881 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001882
1883 @Override
1884 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001885 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1886
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001887 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001888 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001889 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001890 }
1891
Dianne Hackborn497175b2014-07-01 12:56:08 -07001892 boolean isUidForegroundLocked(int uid) {
1893 // only really in foreground when screen is also on
1894 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
1895 <= mCurForegroundState;
1896 }
1897
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001898 /**
Dianne Hackborn497175b2014-07-01 12:56:08 -07001899 * Process state of PID changed; recompute state at UID level. If
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001900 * changed, will trigger {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001901 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001902 void computeUidStateLocked(int uid) {
1903 final SparseIntArray pidState = mUidPidState.get(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001904
1905 // current pid is dropping foreground; examine other pids
Dianne Hackborn497175b2014-07-01 12:56:08 -07001906 int uidState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
1907 if (pidState != null) {
1908 final int size = pidState.size();
1909 for (int i = 0; i < size; i++) {
1910 final int state = pidState.valueAt(i);
1911 if (state < uidState) {
1912 uidState = state;
1913 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001914 }
1915 }
1916
Dianne Hackborn497175b2014-07-01 12:56:08 -07001917 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1918 if (oldUidState != uidState) {
1919 // state changed, push updated rules
1920 mUidState.put(uid, uidState);
1921 final boolean oldForeground = oldUidState <= mCurForegroundState;
1922 final boolean newForeground = uidState <= mCurForegroundState;
1923 if (oldForeground != newForeground) {
1924 updateRulesForUidLocked(uid);
1925 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001926 }
1927 }
1928
Jeff Sharkeya4620792011-05-20 15:29:23 -07001929 private void updateScreenOn() {
1930 synchronized (mRulesLock) {
1931 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07001932 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001933 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001934 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07001935 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001936 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001937 }
1938 }
1939
1940 /**
1941 * Update rules that might be changed by {@link #mScreenOn} value.
1942 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001943 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07001944 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07001945 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001946 for (int i = 0; i < size; i++) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001947 if (mUidState.valueAt(i) <= mCurForegroundState) {
1948 final int uid = mUidState.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001949 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001950 }
1951 }
1952 }
1953
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001954 /**
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001955 * Update rules that might be changed by {@link #mRestrictBackground}
1956 * or {@link #mRestrictPower} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001957 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001958 void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001959 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001960 final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1961
Dianne Hackborn497175b2014-07-01 12:56:08 -07001962 // If we are in restrict power mode, we allow all important apps
1963 // to have data access. Otherwise, we restrict data access to only
1964 // the top apps.
1965 mCurForegroundState = (!mRestrictBackground && mRestrictPower)
1966 ? ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
1967 : ActivityManager.PROCESS_STATE_TOP;
1968
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001969 // update rules for all installed applications
1970 final List<UserInfo> users = um.getUsers();
1971 final List<ApplicationInfo> apps = pm.getInstalledApplications(
1972 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
1973
1974 for (UserInfo user : users) {
1975 for (ApplicationInfo app : apps) {
1976 final int uid = UserHandle.getUid(user.id, app.uid);
1977 updateRulesForUidLocked(uid);
1978 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001979 }
1980
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001981 // limit data usage for some internal system services
1982 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
1983 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001984
1985 // If the set of restricted networks may have changed, re-evaluate those.
1986 if (restrictedNetworksChanged) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001987 normalizePoliciesLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001988 updateNetworkRulesLocked();
1989 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001990 }
1991
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001992 private static boolean isUidValidForRules(int uid) {
1993 // allow rules on specific system services, and any apps
1994 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07001995 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07001996 return true;
1997 }
1998
1999 return false;
2000 }
2001
Dianne Hackborn497175b2014-07-01 12:56:08 -07002002 void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002003 if (!isUidValidForRules(uid)) return;
2004
Dianne Hackborn497175b2014-07-01 12:56:08 -07002005 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2006 final boolean uidForeground = isUidForegroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002007
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002008 // derive active rules based on policy and active state
2009 int uidRules = RULE_ALLOW_ALL;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002010 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002011 // uid in background, and policy says to block metered data
2012 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002013 } else if (mRestrictBackground) {
2014 if (!uidForeground) {
2015 // uid in background, and global background disabled
2016 uidRules = RULE_REJECT_METERED;
2017 }
2018 } else if (mRestrictPower) {
2019 final boolean whitelisted = mPowerSaveWhitelistAppIds.get(UserHandle.getAppId(uid));
2020 if (!whitelisted && !uidForeground
2021 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
2022 // uid is in background, restrict power use mode is on (so we want to
2023 // restrict all background network access), and this uid is not on the
2024 // white list of those allowed background access.
2025 uidRules = RULE_REJECT_METERED;
2026 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002027 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002028
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002029 // TODO: only dispatch when rules actually change
2030
Jeff Sharkey350083e2011-06-29 10:45:16 -07002031 if (uidRules == RULE_ALLOW_ALL) {
2032 mUidRules.delete(uid);
2033 } else {
2034 mUidRules.put(uid, uidRules);
2035 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002036
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002037 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Ashish Sharma50fd36d2011-06-15 19:34:53 -07002038 setUidNetworkRules(uid, rejectMetered);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002039
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002040 // dispatch changed rule to existing listeners
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002041 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002042
2043 try {
2044 // adjust stats accounting based on foreground status
2045 mNetworkStats.setUidForeground(uid, uidForeground);
2046 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002047 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002048 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002049 }
2050
2051 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002052 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002053 public boolean handleMessage(Message msg) {
2054 switch (msg.what) {
2055 case MSG_RULES_CHANGED: {
2056 final int uid = msg.arg1;
2057 final int uidRules = msg.arg2;
2058 final int length = mListeners.beginBroadcast();
2059 for (int i = 0; i < length; i++) {
2060 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2061 if (listener != null) {
2062 try {
2063 listener.onUidRulesChanged(uid, uidRules);
2064 } catch (RemoteException e) {
2065 }
2066 }
2067 }
2068 mListeners.finishBroadcast();
2069 return true;
2070 }
2071 case MSG_METERED_IFACES_CHANGED: {
2072 final String[] meteredIfaces = (String[]) msg.obj;
2073 final int length = mListeners.beginBroadcast();
2074 for (int i = 0; i < length; i++) {
2075 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2076 if (listener != null) {
2077 try {
2078 listener.onMeteredIfacesChanged(meteredIfaces);
2079 } catch (RemoteException e) {
2080 }
2081 }
2082 }
2083 mListeners.finishBroadcast();
2084 return true;
2085 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002086 case MSG_LIMIT_REACHED: {
2087 final String iface = (String) msg.obj;
2088
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002089 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002090 synchronized (mRulesLock) {
2091 if (mMeteredIfaces.contains(iface)) {
2092 try {
2093 // force stats update to make sure we have
2094 // numbers that caused alert to trigger.
2095 mNetworkStats.forceUpdate();
2096 } catch (RemoteException e) {
2097 // ignored; service lives in system_server
2098 }
2099
2100 updateNetworkEnabledLocked();
2101 updateNotificationsLocked();
2102 }
2103 }
2104 return true;
2105 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002106 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2107 final boolean restrictBackground = msg.arg1 != 0;
2108 final int length = mListeners.beginBroadcast();
2109 for (int i = 0; i < length; i++) {
2110 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2111 if (listener != null) {
2112 try {
2113 listener.onRestrictBackgroundChanged(restrictBackground);
2114 } catch (RemoteException e) {
2115 }
2116 }
2117 }
2118 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002119 return true;
2120 }
2121 case MSG_ADVISE_PERSIST_THRESHOLD: {
2122 final long lowestRule = (Long) msg.obj;
2123 try {
2124 // make sure stats are recorded frequently enough; we aim
2125 // for 2MB threshold for 2GB/month rules.
2126 final long persistThreshold = lowestRule / 1000;
2127 mNetworkStats.advisePersistThreshold(persistThreshold);
2128 } catch (RemoteException e) {
2129 // ignored; service lives in system_server
2130 }
2131 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002132 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002133 case MSG_SCREEN_ON_CHANGED: {
2134 updateScreenOn();
2135 return true;
2136 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002137 default: {
2138 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002139 }
2140 }
2141 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002142 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002143
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002144 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002145 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002146 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002147 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002148 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002149 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002150 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002151 }
2152 }
2153
2154 private void removeInterfaceQuota(String iface) {
2155 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002156 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002157 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002158 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002159 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002160 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002161 }
2162 }
2163
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002164 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2165 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002166 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002167 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002168 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002169 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002170 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002171 }
2172 }
2173
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002174 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2175 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002176 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002177 } catch (RuntimeException e) {
2178 Slog.w(TAG, "problem reading network stats: " + e);
2179 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002180 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002181 // ignored; service lives in system_server
2182 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002183 }
2184 }
2185
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002186 private boolean isBandwidthControlEnabled() {
2187 final long token = Binder.clearCallingIdentity();
2188 try {
2189 return mNetworkManager.isBandwidthControlEnabled();
2190 } catch (RemoteException e) {
2191 // ignored; service lives in system_server
2192 return false;
2193 } finally {
2194 Binder.restoreCallingIdentity(token);
2195 }
2196 }
2197
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002198 /**
2199 * Try refreshing {@link #mTime} when stale.
2200 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002201 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002202 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002203 mTime.forceRefresh();
2204 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002205 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002206
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002207 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002208 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2209 }
2210
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002211 private static Intent buildAllowBackgroundDataIntent() {
2212 return new Intent(ACTION_ALLOW_BACKGROUND);
2213 }
2214
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002215 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2216 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2217 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2218 return intent;
2219 }
2220
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002221 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2222 final Intent intent = new Intent();
2223 intent.setComponent(new ComponentName(
2224 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2225 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2226 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2227 return intent;
2228 }
2229
2230 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2231 final Intent intent = new Intent();
2232 intent.setComponent(new ComponentName(
2233 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2234 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2235 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2236 return intent;
2237 }
2238
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002239 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002240 public void addIdleHandler(IdleHandler handler) {
2241 mHandler.getLooper().getQueue().addIdleHandler(handler);
2242 }
2243
Jeff Sharkey1b861272011-05-22 00:34:52 -07002244 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2245 final int size = source.size();
2246 for (int i = 0; i < size; i++) {
2247 target.put(source.keyAt(i), true);
2248 }
2249 }
2250
Dianne Hackborn497175b2014-07-01 12:56:08 -07002251 private static void dumpSparseIntArray(PrintWriter fout, SparseIntArray value) {
Jeff Sharkey1b861272011-05-22 00:34:52 -07002252 fout.print("[");
2253 final int size = value.size();
2254 for (int i = 0; i < size; i++) {
2255 fout.print(value.keyAt(i) + "=" + value.valueAt(i));
2256 if (i < size - 1) fout.print(",");
2257 }
2258 fout.print("]");
2259 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002260}