blob: 5de7d422ee807fd03a1072abc006b0384eb0dd55 [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 Hackborn88e98df2015-03-23 13:29:14 -070074import android.Manifest;
Dianne Hackborn497175b2014-07-01 12:56:08 -070075import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070076import android.app.AppGlobals;
Jeff Sharkeya4620792011-05-20 15:29:23 -070077import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070078import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070079import android.app.IProcessObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070080import android.app.Notification;
81import android.app.PendingIntent;
Jeff Sharkeya4620792011-05-20 15:29:23 -070082import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070083import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070084import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070085import android.content.Intent;
86import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070087import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070088import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070089import android.content.pm.PackageManager;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -070090import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -070091import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070092import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070093import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070094import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070095import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070096import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -070097import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070098import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070099import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700100import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700101import android.net.NetworkPolicy;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700102import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700103import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700104import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700105import android.net.wifi.WifiConfiguration;
106import android.net.wifi.WifiInfo;
107import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700108import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700109import android.os.Environment;
110import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700111import android.os.HandlerThread;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700112import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700113import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700114import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700115import android.os.MessageQueue.IdleHandler;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700116import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700117import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700118import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700119import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700120import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700121import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800122import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700123import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700124import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700125import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700126import android.util.ArrayMap;
127import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700128import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700129import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700130import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700131import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700132import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700133import android.util.SparseArray;
134import android.util.SparseBooleanArray;
135import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700136import android.util.TrustedTime;
137import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700138
Jeff Sharkey32566012014-12-02 18:30:14 -0800139import libcore.io.IoUtils;
140
Jeff Sharkey497e4432011-06-14 17:27:29 -0700141import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800142import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey32566012014-12-02 18:30:14 -0800143import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700144import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700145import com.android.internal.util.IndentingPrintWriter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700146import com.android.server.LocalServices;
147import com.android.server.SystemConfig;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700148import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700149
150import org.xmlpull.v1.XmlPullParser;
151import org.xmlpull.v1.XmlPullParserException;
152import org.xmlpull.v1.XmlSerializer;
153
154import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700155import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700156import java.io.FileInputStream;
157import java.io.FileNotFoundException;
158import java.io.FileOutputStream;
159import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700160import java.io.PrintWriter;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700161import java.util.ArrayList;
162import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700163import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700164
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700165/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700166 * Service that maintains low-level network policy rules, using
167 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700168 * <p>
169 * Derives active rules by combining a given policy with other system status,
170 * and delivers to listeners, such as {@link ConnectivityManager}, for
171 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700172 */
173public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
174 private static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700175 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700176 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700177
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700178 private static final int VERSION_INIT = 1;
179 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700180 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800181 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800182 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800183 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700184 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700185 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700186 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700187 private static final int VERSION_SWITCH_UID = 10;
188 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700189
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800190 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700191 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800192 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700193 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800194 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700195 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700196
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700197 private static final String TAG_POLICY_LIST = "policy-list";
198 private static final String TAG_NETWORK_POLICY = "network-policy";
199 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700200 private static final String TAG_APP_POLICY = "app-policy";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700201
202 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700203 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700204 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
205 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700206 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700207 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800208 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700209 private static final String ATTR_WARNING_BYTES = "warningBytes";
210 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700211 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800212 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
213 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800214 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700215 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700216 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700217 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700218 private static final String ATTR_POLICY = "policy";
219
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700220 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
221
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800222 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800223 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800224 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800225 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700226
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700227 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
228
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700229 private static final int MSG_RULES_CHANGED = 1;
230 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800231 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800232 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700233 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700234 private static final int MSG_SCREEN_ON_CHANGED = 8;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700235
Jeff Sharkey75279902011-05-24 18:39:45 -0700236 private final Context mContext;
237 private final IActivityManager mActivityManager;
238 private final IPowerManager mPowerManager;
239 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700240 private final INetworkManagementService mNetworkManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700241 private final TrustedTime mTime;
242
243 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700244 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700245 private PowerManagerInternal mPowerManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700246
Dianne Hackborn497175b2014-07-01 12:56:08 -0700247 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700248
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700249 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700250 volatile boolean mScreenOn;
251 volatile boolean mRestrictBackground;
252 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700253 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700254
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700255 private final boolean mSuppressDefaultPolicy;
256
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700257 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800258 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700259 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800260 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700261
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700262 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700263 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700264 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800265 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700266
Jeff Sharkey32566012014-12-02 18:30:14 -0800267 /**
268 * UIDs that have been white-listed to always be able to have network access
269 * in power save mode.
270 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700271 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700272
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700273 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800274 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700275 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800276 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700277
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700278 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700279 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700280
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700281 /** Foreground at both UID and PID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800282 final SparseIntArray mUidState = new SparseIntArray();
283 final SparseArray<SparseIntArray> mUidPidState = new SparseArray<>();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700284
285 /** The current maximum process state that we are considering to be foreground. */
286 private int mCurForegroundState = ActivityManager.PROCESS_STATE_TOP;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700287
Jeff Sharkey32566012014-12-02 18:30:14 -0800288 private final RemoteCallbackList<INetworkPolicyListener>
289 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700290
Dianne Hackborn497175b2014-07-01 12:56:08 -0700291 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700292
293 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700294
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700295 // TODO: keep whitelist of system-critical services that should never have
296 // rules enforced, such as system, phone, and radio UIDs.
297
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700298 // TODO: migrate notifications to SystemUI
299
Jeff Sharkey75279902011-05-24 18:39:45 -0700300 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700301 IPowerManager powerManager, INetworkStatsService networkStats,
302 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700303 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700304 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700305 }
306
307 private static File getSystemDir() {
308 return new File(Environment.getDataDirectory(), "system");
309 }
310
311 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700312 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700313 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
314 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700315 mContext = checkNotNull(context, "missing context");
316 mActivityManager = checkNotNull(activityManager, "missing activityManager");
317 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700318 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700319 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700320 mTime = checkNotNull(time, "missing TrustedTime");
321
Amith Yamasani450a16b2013-09-18 16:28:50 -0700322 HandlerThread thread = new HandlerThread(TAG);
323 thread.start();
324 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700325
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700326 mSuppressDefaultPolicy = suppressDefaultPolicy;
327
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700328 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
329 }
330
331 public void bindConnectivityManager(IConnectivityManager connManager) {
332 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700333 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700334
Jeff Sharkey497e4432011-06-14 17:27:29 -0700335 public void bindNotificationManager(INotificationManager notifManager) {
336 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
337 }
338
Jeff Sharkeya4620792011-05-20 15:29:23 -0700339 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700340 if (!isBandwidthControlEnabled()) {
341 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
342 return;
343 }
344
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700345 final PackageManager pm = mContext.getPackageManager();
346
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700347 synchronized (mRulesLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700348 SystemConfig sysConfig = SystemConfig.getInstance();
349 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
350 for (int i=0; i<allowPower.size(); i++) {
351 String pkg = allowPower.valueAt(i);
352 try {
353 ApplicationInfo ai = pm.getApplicationInfo(pkg, 0);
354 if ((ai.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
355 mPowerSaveWhitelistAppIds.put(UserHandle.getAppId(ai.uid), true);
356 }
357 } catch (PackageManager.NameNotFoundException e) {
358 }
359 }
360
361 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
362 mPowerManagerInternal.registerLowPowerModeObserver(
363 new PowerManagerInternal.LowPowerModeListener() {
364 @Override
365 public void onLowPowerModeChanged(boolean enabled) {
366 synchronized (mRulesLock) {
367 if (mRestrictPower != enabled) {
368 mRestrictPower = enabled;
369 updateRulesForGlobalChangeLocked(true);
370 }
371 }
372 }
373 });
374 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700375 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700376
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700377 // read policy from disk
378 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700379
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700380 if (mRestrictBackground || mRestrictPower || mDeviceIdleMode) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700381 updateRulesForGlobalChangeLocked(true);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700382 updateNotificationsLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700383 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700384 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700385
Jeff Sharkeya4620792011-05-20 15:29:23 -0700386 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700387
Jeff Sharkeya4620792011-05-20 15:29:23 -0700388 try {
389 mActivityManager.registerProcessObserver(mProcessObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700390 mNetworkManager.registerObserver(mAlertObserver);
391 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700392 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700393 }
394
Jeff Sharkeya4620792011-05-20 15:29:23 -0700395 // TODO: traverse existing processes to know foreground state, or have
396 // activitymanager dispatch current state when new observer attached.
397
398 final IntentFilter screenFilter = new IntentFilter();
399 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
400 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700401 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700402
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700403 // watch for network interfaces to be claimed
Jeff Sharkey961e3042011-08-29 16:02:57 -0700404 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION_IMMEDIATE);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700405 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
406
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700407 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700408 final IntentFilter packageFilter = new IntentFilter();
409 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700410 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700411 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700412
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700413 // listen for UID changes to update policy
414 mContext.registerReceiver(
415 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
416
417 // listen for user changes to update policy
418 final IntentFilter userFilter = new IntentFilter();
419 userFilter.addAction(ACTION_USER_ADDED);
420 userFilter.addAction(ACTION_USER_REMOVED);
421 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
422
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700423 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700424 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
425 mContext.registerReceiver(
426 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
427
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700428 // listen for restrict background changes from notifications
429 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
430 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
431
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800432 // listen for snooze warning from notifications
433 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
434 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
435 MANAGE_NETWORK_POLICY, mHandler);
436
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700437 // listen for configured wifi networks to be removed
438 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700439 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700440
441 // listen for wifi state changes to catch metered hint
442 final IntentFilter wifiStateFilter = new IntentFilter(
443 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700444 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700445
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700446 }
447
Jeff Sharkeya4620792011-05-20 15:29:23 -0700448 private IProcessObserver mProcessObserver = new IProcessObserver.Stub() {
449 @Override
450 public void onForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700451 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700452
453 @Override
Dianne Hackborn684bf342014-04-29 17:56:57 -0700454 public void onProcessStateChanged(int pid, int uid, int procState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700455 synchronized (mRulesLock) {
456 // because a uid can have multiple pids running inside, we need to
457 // remember all pid states and summarize foreground at uid level.
458
459 // record foreground for this specific pid
460 SparseIntArray pidState = mUidPidState.get(uid);
461 if (pidState == null) {
462 pidState = new SparseIntArray(2);
463 mUidPidState.put(uid, pidState);
464 }
465 pidState.put(pid, procState);
466 computeUidStateLocked(uid);
467 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700468 }
469
470 @Override
Jeff Sharkeya4620792011-05-20 15:29:23 -0700471 public void onProcessDied(int pid, int uid) {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700472 synchronized (mRulesLock) {
473 // clear records and recompute, when they exist
474 final SparseIntArray pidState = mUidPidState.get(uid);
475 if (pidState != null) {
476 pidState.delete(pid);
477 if (pidState.size() <= 0) {
478 mUidPidState.remove(uid);
479 }
480 computeUidStateLocked(uid);
481 }
482 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700483 }
484 };
485
486 private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
487 @Override
488 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800489 // screen-related broadcasts are protected by system, no need
490 // for permissions check.
491 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700492 }
493 };
494
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700495 private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700496 @Override
497 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700498 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700499
500 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700501 final int uid = intent.getIntExtra(EXTRA_UID, -1);
502 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700503
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700504 if (ACTION_PACKAGE_ADDED.equals(action)) {
505 // update rules for UID, since it might be subject to
506 // global background data policy
507 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
508 synchronized (mRulesLock) {
509 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700510 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700511 }
512 }
513 };
514
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700515 private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
516 @Override
517 public void onReceive(Context context, Intent intent) {
518 // on background handler thread, and UID_REMOVED is protected
519
520 final int uid = intent.getIntExtra(EXTRA_UID, -1);
521 if (uid == -1) return;
522
523 // remove any policy and update rules to clean up
524 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
525 synchronized (mRulesLock) {
526 mUidPolicy.delete(uid);
527 updateRulesForUidLocked(uid);
528 writePolicyLocked();
529 }
530 }
531 };
532
533 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
534 @Override
535 public void onReceive(Context context, Intent intent) {
536 // on background handler thread, and USER_ADDED and USER_REMOVED
537 // broadcasts are protected
538
539 final String action = intent.getAction();
540 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
541 if (userId == -1) return;
542
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700543 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700544 // Remove any policies for given user; both cleaning up after a
545 // USER_REMOVED, and one last sanity check during USER_ADDED
546 removePoliciesForUserLocked(userId);
547 // Update global restrict for new user
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700548 updateRulesForGlobalChangeLocked(true);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700549 }
550 }
551 };
552
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700553 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700554 * Receiver that watches for {@link INetworkStatsService} updates, which we
555 * use to check against {@link NetworkPolicy#warningBytes}.
556 */
557 private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
558 @Override
559 public void onReceive(Context context, Intent intent) {
560 // on background handler thread, and verified
561 // READ_NETWORK_USAGE_HISTORY permission above.
562
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800563 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700564 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700565 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700566 updateNotificationsLocked();
567 }
568 }
569 };
570
571 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700572 * Receiver that watches for {@link Notification} control of
573 * {@link #mRestrictBackground}.
574 */
575 private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
576 @Override
577 public void onReceive(Context context, Intent intent) {
578 // on background handler thread, and verified MANAGE_NETWORK_POLICY
579 // permission above.
580
581 setRestrictBackground(false);
582 }
583 };
584
585 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800586 * Receiver that watches for {@link Notification} control of
587 * {@link NetworkPolicy#lastWarningSnooze}.
588 */
589 private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
590 @Override
591 public void onReceive(Context context, Intent intent) {
592 // on background handler thread, and verified MANAGE_NETWORK_POLICY
593 // permission above.
594
595 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
596 performSnooze(template, TYPE_WARNING);
597 }
598 };
599
600 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700601 * Receiver that watches for {@link WifiConfiguration} to be changed.
602 */
603 private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
604 @Override
605 public void onReceive(Context context, Intent intent) {
606 // on background handler thread, and verified CONNECTIVITY_INTERNAL
607 // permission above.
608
609 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
610 if (reason == CHANGE_REASON_REMOVED) {
611 final WifiConfiguration config = intent.getParcelableExtra(
612 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700613 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800614 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700615 synchronized (mRulesLock) {
616 if (mNetworkPolicy.containsKey(template)) {
617 mNetworkPolicy.remove(template);
618 writePolicyLocked();
619 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700620 }
621 }
622 }
623 }
624 };
625
626 /**
627 * Receiver that watches {@link WifiInfo} state changes to infer metered
628 * state. Ignores hints when policy is user-defined.
629 */
630 private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
631 @Override
632 public void onReceive(Context context, Intent intent) {
633 // on background handler thread, and verified CONNECTIVITY_INTERNAL
634 // permission above.
635
636 // ignore when not connected
637 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
638 if (!netInfo.isConnected()) return;
639
640 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
641 final boolean meteredHint = info.getMeteredHint();
642
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800643 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700644 synchronized (mRulesLock) {
645 NetworkPolicy policy = mNetworkPolicy.get(template);
646 if (policy == null && meteredHint) {
647 // policy doesn't exist, and AP is hinting that it's
648 // metered: create an inferred policy.
649 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
650 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
651 meteredHint, true);
652 addNetworkPolicyLocked(policy);
653
654 } else if (policy != null && policy.inferred) {
655 // policy exists, and was inferred: update its current
656 // metered state.
657 policy.metered = meteredHint;
658
659 // since this is inferred for each wifi session, just update
660 // rules without persisting.
661 updateNetworkRulesLocked();
662 }
663 }
664 }
665 };
666
667 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700668 * Observer that watches for {@link INetworkManagementService} alerts.
669 */
Jeff Sharkey216c1812012-08-05 14:29:23 -0700670 private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700671 @Override
672 public void limitReached(String limitName, String iface) {
673 // only someone like NMS should be calling us
674 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
675
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800676 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
677 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700678 }
679 }
680 };
681
682 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700683 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
684 * to show visible notifications as needed.
685 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700686 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700687 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
688
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700689 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700690 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700691 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700692
693 // TODO: when switching to kernel notifications, compute next future
694 // cycle boundary to recompute notifications.
695
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700696 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800697 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700698 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
699 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700700 // ignore policies that aren't relevant to user
701 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700702 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700703
Jeff Sharkey497e4432011-06-14 17:27:29 -0700704 final long start = computeLastCycleBoundary(currentTime, policy);
705 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700706 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700707
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700708 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800709 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700710 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
711 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700712 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
713 notifyOverLimitLocked(policy.template);
714 }
715
Jeff Sharkey497e4432011-06-14 17:27:29 -0700716 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700717 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700718
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800719 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700720 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700721 }
722 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700723 }
724
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700725 // ongoing notification when restricting background data
726 if (mRestrictBackground) {
727 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700728 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700729
730 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700731 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
732 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700733 if (!mActiveNotifs.contains(tag)) {
734 cancelNotification(tag);
735 }
736 }
737 }
738
739 /**
740 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700741 * current device state, such as when
742 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
743 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700744 */
745 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800746 if (template.isMatchRuleMobile()) {
747 final TelephonyManager tele = TelephonyManager.from(mContext);
748 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700749
Jeff Sharkey32566012014-12-02 18:30:14 -0800750 // Mobile template is relevant when any active subscriber matches
751 final int[] subIds = sub.getActiveSubscriptionIdList();
752 for (int subId : subIds) {
753 final String subscriberId = tele.getSubscriberId(subId);
754 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
755 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
756 if (template.matches(probeIdent)) {
757 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700758 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800759 }
760 return false;
761 } else {
762 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700763 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700764 }
765
766 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700767 * Notify that given {@link NetworkTemplate} is over
768 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
769 */
770 private void notifyOverLimitLocked(NetworkTemplate template) {
771 if (!mOverLimitNotified.contains(template)) {
772 mContext.startActivity(buildNetworkOverLimitIntent(template));
773 mOverLimitNotified.add(template);
774 }
775 }
776
777 private void notifyUnderLimitLocked(NetworkTemplate template) {
778 mOverLimitNotified.remove(template);
779 }
780
781 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700782 * Build unique tag that identifies an active {@link NetworkPolicy}
783 * notification of a specific type, like {@link #TYPE_LIMIT}.
784 */
785 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700786 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700787 }
788
789 /**
790 * Show notification for combined {@link NetworkPolicy} and specific type,
791 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
792 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700793 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700794 final String tag = buildNotificationTag(policy, type);
795 final Notification.Builder builder = new Notification.Builder(mContext);
796 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800797 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700798 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200799 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700800
801 final Resources res = mContext.getResources();
802 switch (type) {
803 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700804 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700805 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700806
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700807 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700808 builder.setTicker(title);
809 builder.setContentTitle(title);
810 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700811
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800812 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
813 builder.setDeleteIntent(PendingIntent.getBroadcast(
814 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
815
816 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700817 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800818 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
819
Jeff Sharkey497e4432011-06-14 17:27:29 -0700820 break;
821 }
822 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700823 final CharSequence body = res.getText(R.string.data_usage_limit_body);
824
825 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -0400826 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700827 switch (policy.template.getMatchRule()) {
828 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700829 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700830 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700831 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700832 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700833 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700834 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700835 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700836 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700837 case MATCH_WIFI:
838 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -0400839 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700840 break;
841 default:
842 title = null;
843 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700844 }
845
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800846 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -0400847 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700848 builder.setTicker(title);
849 builder.setContentTitle(title);
850 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700851
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700852 final Intent intent = buildNetworkOverLimitIntent(policy.template);
853 builder.setContentIntent(PendingIntent.getActivity(
854 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
855 break;
856 }
857 case TYPE_LIMIT_SNOOZED: {
858 final long overBytes = totalBytes - policy.limitBytes;
859 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
860 Formatter.formatFileSize(mContext, overBytes));
861
862 final CharSequence title;
863 switch (policy.template.getMatchRule()) {
864 case MATCH_MOBILE_3G_LOWER:
865 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
866 break;
867 case MATCH_MOBILE_4G:
868 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
869 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700870 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700871 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
872 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700873 case MATCH_WIFI:
874 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
875 break;
876 default:
877 title = null;
878 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700879 }
880
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800881 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700882 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700883 builder.setTicker(title);
884 builder.setContentTitle(title);
885 builder.setContentText(body);
886
887 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700888 builder.setContentIntent(PendingIntent.getActivity(
889 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700890 break;
891 }
892 }
893
894 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700895 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700896 try {
897 final String packageName = mContext.getPackageName();
898 final int[] idReceived = new int[1];
899 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800900 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Dianne Hackborn41203752012-08-31 14:05:51 -0700901 UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700902 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700903 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700904 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700905 }
906 }
907
908 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700909 * Show ongoing notification to reflect that {@link #mRestrictBackground}
910 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700911 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700912 private void enqueueRestrictedNotification(String tag) {
913 final Resources res = mContext.getResources();
914 final Notification.Builder builder = new Notification.Builder(mContext);
915
916 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
917 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
918
919 builder.setOnlyAlertOnce(true);
920 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700921 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700922 builder.setTicker(title);
923 builder.setContentTitle(title);
924 builder.setContentText(body);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700925 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200926 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700927
928 final Intent intent = buildAllowBackgroundDataIntent();
929 builder.setContentIntent(
930 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700931
932 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700933 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700934 try {
935 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700936 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800937 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Dianne Hackborn41203752012-08-31 14:05:51 -0700938 0x0, builder.getNotification(), idReceived, UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700939 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700940 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700941 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700942 }
943 }
944
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700945 private void cancelNotification(String tag) {
946 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700947 // XXX what to do about multi-user?
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700948 try {
949 final String packageName = mContext.getPackageName();
950 mNotifManager.cancelNotificationWithTag(
Dianne Hackborn41203752012-08-31 14:05:51 -0700951 packageName, tag, 0x0, UserHandle.USER_OWNER);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700952 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700953 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700954 }
955 }
956
957 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700958 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700959 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700960 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700961 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700962 @Override
963 public void onReceive(Context context, Intent intent) {
964 // on background handler thread, and verified CONNECTIVITY_INTERNAL
965 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800966
967 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700968 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700969 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -0800970 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700971 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700972 updateNetworkRulesLocked();
973 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700974 }
975 }
976 };
977
978 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700979 * Proactively control network data connections when they exceed
980 * {@link NetworkPolicy#limitBytes}.
981 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700982 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700983 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
984
985 // TODO: reset any policy-disabled networks when any policy is removed
986 // completely, which is currently rare case.
987
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800988 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700989 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
990 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700991 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700992 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700993 setNetworkTemplateEnabled(policy.template, true);
994 continue;
995 }
996
997 final long start = computeLastCycleBoundary(currentTime, policy);
998 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700999 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001000
1001 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001002 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1003 && policy.lastLimitSnooze < start;
1004 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001005
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001006 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001007 }
1008 }
1009
1010 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001011 * Proactively disable networks that match the given
1012 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001013 */
1014 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001015 // TODO: reach into ConnectivityManager to proactively disable bringing
1016 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001017 }
1018
1019 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001020 * Examine all connected {@link NetworkState}, looking for
1021 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1022 * remaining quota based on usage cycle and historical stats.
1023 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001024 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001025 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001026
1027 final NetworkState[] states;
1028 try {
1029 states = mConnManager.getAllNetworkState();
1030 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001031 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001032 return;
1033 }
1034
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001035 // If we are in restrict power mode, we want to treat all interfaces
1036 // as metered, to restrict access to the network by uid. However, we
1037 // will not have a bandwidth limit. Also only do this if restrict
1038 // background data use is *not* enabled, since that takes precendence
1039 // use over those networks can have a cost associated with it).
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001040 final boolean powerSave = (mRestrictPower || mDeviceIdleMode) && !mRestrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001041
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001042 // First, generate identities of all connected networks so we can
1043 // quickly compare them against all defined policies below.
1044 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001045 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001046 for (NetworkState state : states) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001047 if (state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001048 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001049
1050 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001051 if (baseIface != null) {
1052 connIdents.add(Pair.create(baseIface, ident));
1053 if (powerSave) {
1054 connIfaces.add(baseIface);
1055 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001056 }
1057
1058 // Stacked interfaces are considered to have same identity as
1059 // their parent network.
1060 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1061 for (LinkProperties stackedLink : stackedLinks) {
1062 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001063 if (stackedIface != null) {
1064 connIdents.add(Pair.create(stackedIface, ident));
1065 if (powerSave) {
1066 connIfaces.add(stackedIface);
1067 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001068 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001069 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001070 }
1071 }
1072
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001073 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001074 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001075 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001076 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001077 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001078
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001079 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001080 for (int j = connIdents.size() - 1; j >= 0; j--) {
1081 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1082 if (policy.template.matches(ident.second)) {
1083 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001084 }
1085 }
1086
1087 if (ifaceList.size() > 0) {
1088 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001089 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001090 }
1091 }
1092
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001093 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001094 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001095
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001096 // apply each policy that we found ifaces for; compute remaining data
1097 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001098 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001099 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1100 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1101 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001102
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001103 final long start;
1104 final long totalBytes;
1105 if (policy.hasCycle()) {
1106 start = computeLastCycleBoundary(currentTime, policy);
1107 totalBytes = getTotalBytes(policy.template, start, currentTime);
1108 } else {
1109 start = Long.MAX_VALUE;
1110 totalBytes = 0;
1111 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001112
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001113 if (LOGD) {
1114 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001115 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001116 }
1117
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001118 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001119 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001120 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001121 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001122 if (!hasLimit) {
1123 // metered network, but no policy limit; we still need to
1124 // restrict apps, so push really high quota.
1125 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001126 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001127 // snoozing past quota, but we still need to restrict apps,
1128 // so push really high quota.
1129 quotaBytes = Long.MAX_VALUE;
1130 } else {
1131 // remaining "quota" bytes are based on total usage in
1132 // current cycle. kernel doesn't like 0-byte rules, so we
1133 // set 1-byte quota and disable the radio later.
1134 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1135 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001136
1137 if (ifaces.length > 1) {
1138 // TODO: switch to shared quota once NMS supports
1139 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001140 }
1141
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001142 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001143 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001144 setInterfaceQuota(iface, quotaBytes);
1145 newMeteredIfaces.add(iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001146 if (powerSave) {
1147 connIfaces.remove(iface);
1148 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001149 }
1150 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001151
1152 // keep track of lowest warning or limit of active policies
1153 if (hasWarning && policy.warningBytes < lowestRule) {
1154 lowestRule = policy.warningBytes;
1155 }
1156 if (hasLimit && policy.limitBytes < lowestRule) {
1157 lowestRule = policy.limitBytes;
1158 }
1159 }
1160
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001161 for (int i = connIfaces.size()-1; i >= 0; i--) {
1162 String iface = connIfaces.valueAt(i);
1163 removeInterfaceQuota(iface);
1164 setInterfaceQuota(iface, Long.MAX_VALUE);
1165 newMeteredIfaces.add(iface);
1166 }
1167
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001168 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001169
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001170 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001171 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1172 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001173 if (!newMeteredIfaces.contains(iface)) {
1174 removeInterfaceQuota(iface);
1175 }
1176 }
1177 mMeteredIfaces = newMeteredIfaces;
1178
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001179 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001180 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001181 }
1182
1183 /**
1184 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1185 * have at least a default mobile policy defined.
1186 */
1187 private void ensureActiveMobilePolicyLocked() {
1188 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001189 if (mSuppressDefaultPolicy) return;
1190
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001191 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001192 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001193
Jeff Sharkey32566012014-12-02 18:30:14 -08001194 final int[] subIds = sub.getActiveSubscriptionIdList();
1195 for (int subId : subIds) {
1196 final String subscriberId = tele.getSubscriberId(subId);
1197 ensureActiveMobilePolicyLocked(subscriberId);
1198 }
1199 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001200
Jeff Sharkey32566012014-12-02 18:30:14 -08001201 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1202 // Poke around to see if we already have a policy
1203 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1204 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1205 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1206 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1207 if (template.matches(probeIdent)) {
1208 if (LOGD) {
1209 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1210 + NetworkIdentity.scrubSubscriberId(subscriberId));
1211 }
1212 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001213 }
1214 }
1215
Jeff Sharkey32566012014-12-02 18:30:14 -08001216 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1217 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001218
Jeff Sharkey32566012014-12-02 18:30:14 -08001219 // Build default mobile policy, and assume usage cycle starts today
1220 final long warningBytes = mContext.getResources().getInteger(
1221 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001222
Jeff Sharkey32566012014-12-02 18:30:14 -08001223 final Time time = new Time();
1224 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001225
Jeff Sharkey32566012014-12-02 18:30:14 -08001226 final int cycleDay = time.monthDay;
1227 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001228
Jeff Sharkey32566012014-12-02 18:30:14 -08001229 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1230 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1231 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1232 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001233 }
1234
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001235 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001236 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001237
1238 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001239 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001240 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001241
1242 FileInputStream fis = null;
1243 try {
1244 fis = mPolicyFile.openRead();
1245 final XmlPullParser in = Xml.newPullParser();
1246 in.setInput(fis, null);
1247
1248 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001249 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001250 while ((type = in.next()) != END_DOCUMENT) {
1251 final String tag = in.getName();
1252 if (type == START_TAG) {
1253 if (TAG_POLICY_LIST.equals(tag)) {
1254 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001255 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1256 mRestrictBackground = readBooleanAttribute(
1257 in, ATTR_RESTRICT_BACKGROUND);
1258 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001259 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001260 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001261
1262 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1263 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1264 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001265 final String networkId;
1266 if (version >= VERSION_ADDED_NETWORK_ID) {
1267 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1268 } else {
1269 networkId = null;
1270 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001271 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001272 final String cycleTimezone;
1273 if (version >= VERSION_ADDED_TIMEZONE) {
1274 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1275 } else {
1276 cycleTimezone = Time.TIMEZONE_UTC;
1277 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001278 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1279 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001280 final long lastLimitSnooze;
1281 if (version >= VERSION_SPLIT_SNOOZE) {
1282 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1283 } else if (version >= VERSION_ADDED_SNOOZE) {
1284 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001285 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001286 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001287 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001288 final boolean metered;
1289 if (version >= VERSION_ADDED_METERED) {
1290 metered = readBooleanAttribute(in, ATTR_METERED);
1291 } else {
1292 switch (networkTemplate) {
1293 case MATCH_MOBILE_3G_LOWER:
1294 case MATCH_MOBILE_4G:
1295 case MATCH_MOBILE_ALL:
1296 metered = true;
1297 break;
1298 default:
1299 metered = false;
1300 }
1301 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001302 final long lastWarningSnooze;
1303 if (version >= VERSION_SPLIT_SNOOZE) {
1304 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1305 } else {
1306 lastWarningSnooze = SNOOZE_NEVER;
1307 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001308 final boolean inferred;
1309 if (version >= VERSION_ADDED_INFERRED) {
1310 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1311 } else {
1312 inferred = false;
1313 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001314
Jeff Sharkey32566012014-12-02 18:30:14 -08001315 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1316 subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001317 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001318 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001319 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001320
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001321 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001322 final int uid = readIntAttribute(in, ATTR_UID);
1323 final int policy = readIntAttribute(in, ATTR_POLICY);
1324
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001325 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001326 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001327 } else {
1328 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1329 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001330 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001331 final int appId = readIntAttribute(in, ATTR_APP_ID);
1332 final int policy = readIntAttribute(in, ATTR_POLICY);
1333
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001334 // TODO: set for other users during upgrade
1335 final int uid = UserHandle.getUid(UserHandle.USER_OWNER, appId);
1336 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001337 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001338 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001339 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001340 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001341 }
1342 }
1343 }
1344
1345 } catch (FileNotFoundException e) {
1346 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001347 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001348 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001349 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001350 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001351 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001352 } finally {
1353 IoUtils.closeQuietly(fis);
1354 }
1355 }
1356
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001357 /**
1358 * Upgrade legacy background data flags, notifying listeners of one last
1359 * change to always-true.
1360 */
1361 private void upgradeLegacyBackgroundData() {
1362 mRestrictBackground = Settings.Secure.getInt(
1363 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1364
1365 // kick off one last broadcast if restricted
1366 if (mRestrictBackground) {
1367 final Intent broadcast = new Intent(
1368 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001369 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001370 }
1371 }
1372
Dianne Hackborn497175b2014-07-01 12:56:08 -07001373 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001374 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001375
1376 FileOutputStream fos = null;
1377 try {
1378 fos = mPolicyFile.startWrite();
1379
1380 XmlSerializer out = new FastXmlSerializer();
1381 out.setOutput(fos, "utf-8");
1382 out.startDocument(null, true);
1383
1384 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001385 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001386 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001387
1388 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001389 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1390 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001391 final NetworkTemplate template = policy.template;
1392
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001393 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001394 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1395 final String subscriberId = template.getSubscriberId();
1396 if (subscriberId != null) {
1397 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001398 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001399 final String networkId = template.getNetworkId();
1400 if (networkId != null) {
1401 out.attribute(null, ATTR_NETWORK_ID, networkId);
1402 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001403 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001404 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001405 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1406 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001407 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1408 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001409 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001410 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001411 out.endTag(null, TAG_NETWORK_POLICY);
1412 }
1413
1414 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001415 for (int i = 0; i < mUidPolicy.size(); i++) {
1416 final int uid = mUidPolicy.keyAt(i);
1417 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001418
Jeff Sharkey497e4432011-06-14 17:27:29 -07001419 // skip writing empty policies
1420 if (policy == POLICY_NONE) continue;
1421
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001422 out.startTag(null, TAG_UID_POLICY);
1423 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001424 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001425 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001426 }
1427
1428 out.endTag(null, TAG_POLICY_LIST);
1429 out.endDocument();
1430
1431 mPolicyFile.finishWrite(fos);
1432 } catch (IOException e) {
1433 if (fos != null) {
1434 mPolicyFile.failWrite(fos);
1435 }
1436 }
1437 }
1438
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001439 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001440 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001441 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001442
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001443 if (!UserHandle.isApp(uid)) {
1444 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001445 }
1446
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001447 synchronized (mRulesLock) {
1448 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1449 if (oldPolicy != policy) {
1450 setUidPolicyUncheckedLocked(uid, policy, true);
1451 }
1452 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001453 }
1454
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001455 @Override
1456 public void addUidPolicy(int uid, int policy) {
1457 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001458
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001459 if (!UserHandle.isApp(uid)) {
1460 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1461 }
1462
1463 synchronized (mRulesLock) {
1464 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1465 policy |= oldPolicy;
1466 if (oldPolicy != policy) {
1467 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001468 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001469 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001470 }
1471
1472 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001473 public void removeUidPolicy(int uid, int policy) {
1474 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1475
1476 if (!UserHandle.isApp(uid)) {
1477 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1478 }
1479
1480 synchronized (mRulesLock) {
1481 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1482 policy = oldPolicy & ~policy;
1483 if (oldPolicy != policy) {
1484 setUidPolicyUncheckedLocked(uid, policy, true);
1485 }
1486 }
1487 }
1488
1489 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1490 mUidPolicy.put(uid, policy);
1491
1492 // uid policy changed, recompute rules and persist policy.
1493 updateRulesForUidLocked(uid);
1494 if (persist) {
1495 writePolicyLocked();
1496 }
1497 }
1498
1499 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001500 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001501 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1502
Jeff Sharkeya4620792011-05-20 15:29:23 -07001503 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001504 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001505 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001506 }
1507
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001508 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001509 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001510 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1511
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001512 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001513 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001514 for (int i = 0; i < mUidPolicy.size(); i++) {
1515 final int uid = mUidPolicy.keyAt(i);
1516 final int uidPolicy = mUidPolicy.valueAt(i);
1517 if (uidPolicy == policy) {
1518 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001519 }
1520 }
1521 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001522 return uids;
1523 }
1524
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001525 @Override
1526 public int[] getPowerSaveAppIdWhitelist() {
1527 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1528
1529 synchronized (mRulesLock) {
1530 int size = mPowerSaveWhitelistAppIds.size();
1531 int[] appids = new int[size];
1532 for (int i = 0; i < size; i++) {
1533 appids[i] = mPowerSaveWhitelistAppIds.keyAt(i);
1534 }
1535 return appids;
1536 }
1537 }
1538
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001539 /**
1540 * Remove any policies associated with given {@link UserHandle}, persisting
1541 * if any changes are made.
1542 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001543 void removePoliciesForUserLocked(int userId) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001544 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1545
1546 int[] uids = new int[0];
1547 for (int i = 0; i < mUidPolicy.size(); i++) {
1548 final int uid = mUidPolicy.keyAt(i);
1549 if (UserHandle.getUserId(uid) == userId) {
1550 uids = appendInt(uids, uid);
1551 }
1552 }
1553
1554 if (uids.length > 0) {
1555 for (int uid : uids) {
1556 mUidPolicy.delete(uid);
1557 updateRulesForUidLocked(uid);
1558 }
1559 writePolicyLocked();
1560 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001561 }
1562
1563 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001564 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001565 // TODO: create permission for observing network policy
1566 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1567
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001568 mListeners.register(listener);
1569
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001570 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001571 }
1572
1573 @Override
1574 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001575 // TODO: create permission for observing network policy
1576 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1577
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001578 mListeners.unregister(listener);
1579 }
1580
Jeff Sharkey1b861272011-05-22 00:34:52 -07001581 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001582 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001583 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1584
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001585 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001586 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001587 normalizePoliciesLocked(policies);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001588 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001589 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001590 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001591 writePolicyLocked();
1592 }
1593 }
1594
Dianne Hackborn497175b2014-07-01 12:56:08 -07001595 void addNetworkPolicyLocked(NetworkPolicy policy) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001596 NetworkPolicy[] policies = getNetworkPolicies();
1597 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1598 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001599 }
1600
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001601 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001602 public NetworkPolicy[] getNetworkPolicies() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001603 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001604 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001605
1606 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001607 final int size = mNetworkPolicy.size();
1608 final NetworkPolicy[] policies = new NetworkPolicy[size];
1609 for (int i = 0; i < size; i++) {
1610 policies[i] = mNetworkPolicy.valueAt(i);
1611 }
1612 return policies;
1613 }
1614 }
1615
1616 private void normalizePoliciesLocked() {
1617 normalizePoliciesLocked(getNetworkPolicies());
1618 }
1619
1620 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1621 final TelephonyManager tele = TelephonyManager.from(mContext);
1622 final String[] merged = tele.getMergedSubscriberIds();
1623
1624 mNetworkPolicy.clear();
1625 for (NetworkPolicy policy : policies) {
1626 // When two normalized templates conflict, prefer the most
1627 // restrictive policy
1628 policy.template = NetworkTemplate.normalize(policy.template, merged);
1629 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1630 if (existing == null || existing.compareTo(policy) > 0) {
1631 if (existing != null) {
1632 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1633 }
1634 mNetworkPolicy.put(policy.template, policy);
1635 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001636 }
1637 }
1638
1639 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001640 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001641 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001642
1643 final long token = Binder.clearCallingIdentity();
1644 try {
1645 performSnooze(template, TYPE_LIMIT);
1646 } finally {
1647 Binder.restoreCallingIdentity(token);
1648 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001649 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001650
Dianne Hackborn497175b2014-07-01 12:56:08 -07001651 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001652 maybeRefreshTrustedTime();
1653 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001654 synchronized (mRulesLock) {
1655 // find and snooze local policy that matches
1656 final NetworkPolicy policy = mNetworkPolicy.get(template);
1657 if (policy == null) {
1658 throw new IllegalArgumentException("unable to find policy for " + template);
1659 }
1660
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001661 switch (type) {
1662 case TYPE_WARNING:
1663 policy.lastWarningSnooze = currentTime;
1664 break;
1665 case TYPE_LIMIT:
1666 policy.lastLimitSnooze = currentTime;
1667 break;
1668 default:
1669 throw new IllegalArgumentException("unexpected type");
1670 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001671
Jeff Sharkey32566012014-12-02 18:30:14 -08001672 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001673 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001674 updateNetworkRulesLocked();
1675 updateNotificationsLocked();
1676 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001677 }
1678 }
1679
1680 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001681 public void setRestrictBackground(boolean restrictBackground) {
1682 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1683
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001684 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001685 synchronized (mRulesLock) {
1686 mRestrictBackground = restrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001687 updateRulesForGlobalChangeLocked(false);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001688 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001689 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001690 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001691
1692 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1693 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001694 }
1695
1696 @Override
1697 public boolean getRestrictBackground() {
1698 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1699
1700 synchronized (mRulesLock) {
1701 return mRestrictBackground;
1702 }
1703 }
1704
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001705 @Override
1706 public void setDeviceIdleMode(boolean enabled) {
1707 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1708
1709 synchronized (mRulesLock) {
1710 if (mDeviceIdleMode != enabled) {
1711 mDeviceIdleMode = enabled;
1712 if (mSystemReady) {
1713 updateRulesForGlobalChangeLocked(true);
1714 }
1715 }
1716 }
1717 }
1718
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001719 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001720 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1721 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001722 if (policy.template.matches(ident)) {
1723 return policy;
1724 }
1725 }
1726 return null;
1727 }
1728
1729 @Override
1730 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1731 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1732
1733 // only returns usage summary, so we don't require caller to have
1734 // READ_NETWORK_USAGE_HISTORY.
1735 final long token = Binder.clearCallingIdentity();
1736 try {
1737 return getNetworkQuotaInfoUnchecked(state);
1738 } finally {
1739 Binder.restoreCallingIdentity(token);
1740 }
1741 }
1742
1743 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1744 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1745
1746 final NetworkPolicy policy;
1747 synchronized (mRulesLock) {
1748 policy = findPolicyForNetworkLocked(ident);
1749 }
1750
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001751 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001752 // missing policy means we can't derive useful quota info
1753 return null;
1754 }
1755
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001756 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001757
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001758 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001759 final long start = computeLastCycleBoundary(currentTime, policy);
1760 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001761 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001762
1763 // report soft and hard limits under policy
1764 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1765 : NetworkQuotaInfo.NO_LIMIT;
1766 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1767 : NetworkQuotaInfo.NO_LIMIT;
1768
1769 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1770 }
1771
Jeff Sharkey46645002011-07-27 21:11:21 -07001772 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001773 public boolean isNetworkMetered(NetworkState state) {
1774 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1775
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001776 // roaming networks are always considered metered
1777 if (ident.getRoaming()) {
1778 return true;
1779 }
1780
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001781 final NetworkPolicy policy;
1782 synchronized (mRulesLock) {
1783 policy = findPolicyForNetworkLocked(ident);
1784 }
1785
1786 if (policy != null) {
1787 return policy.metered;
1788 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001789 final int type = state.networkInfo.getType();
1790 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1791 return true;
1792 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001793 return false;
1794 }
1795 }
1796
1797 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001798 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001799 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001800
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001801 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1802
Dianne Hackborn497175b2014-07-01 12:56:08 -07001803 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001804 for (String arg : args) {
1805 argSet.add(arg);
1806 }
1807
Jeff Sharkey1b861272011-05-22 00:34:52 -07001808 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001809 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001810 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1811 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001812 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001813
Jeff Sharkey32566012014-12-02 18:30:14 -08001814 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001815 updateNetworkEnabledLocked();
1816 updateNetworkRulesLocked();
1817 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001818 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001819
1820 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001821 return;
1822 }
1823
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001824 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07001825 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001826 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001827 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001828 fout.print("Current foreground state: "); fout.println(mCurForegroundState);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001829 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001830 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001831 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1832 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001833 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001834 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001835
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001836 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
1837
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001838 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001839 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001840 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001841 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001842 final int uid = mUidPolicy.keyAt(i);
1843 final int policy = mUidPolicy.valueAt(i);
1844 fout.print("UID=");
1845 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001846 fout.print(" policy=");
1847 dumpPolicy(fout, policy);
1848 fout.println();
1849 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001850 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001851
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001852 size = mPowerSaveWhitelistAppIds.size();
1853 if (size > 0) {
1854 fout.println("Power save whitelist app ids:");
1855 fout.increaseIndent();
1856 for (int i = 0; i < size; i++) {
1857 fout.print("UID=");
1858 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
1859 fout.print(": ");
1860 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
1861 fout.println();
1862 }
1863 fout.decreaseIndent();
1864 }
1865
Jeff Sharkey1b861272011-05-22 00:34:52 -07001866 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07001867 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001868 collectKeys(mUidRules, knownUids);
1869
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001870 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001871 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001872 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001873 for (int i = 0; i < size; i++) {
1874 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001875 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001876 fout.print(uid);
1877
Dianne Hackborn497175b2014-07-01 12:56:08 -07001878 int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1879 fout.print(" state=");
1880 fout.print(state);
1881 fout.print(state <= mCurForegroundState ? " (fg)" : " (bg)");
1882
1883 fout.print(" pids=");
1884 final int foregroundIndex = mUidPidState.indexOfKey(uid);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001885 if (foregroundIndex < 0) {
1886 fout.print("UNKNOWN");
1887 } else {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001888 dumpSparseIntArray(fout, mUidPidState.valueAt(foregroundIndex));
Jeff Sharkey1b861272011-05-22 00:34:52 -07001889 }
1890
1891 fout.print(" rules=");
1892 final int rulesIndex = mUidRules.indexOfKey(uid);
1893 if (rulesIndex < 0) {
1894 fout.print("UNKNOWN");
1895 } else {
1896 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1897 }
1898
1899 fout.println();
1900 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001901 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001902 }
1903 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001904
1905 @Override
1906 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001907 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1908
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001909 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001910 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001911 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001912 }
1913
Dianne Hackborn497175b2014-07-01 12:56:08 -07001914 boolean isUidForegroundLocked(int uid) {
1915 // only really in foreground when screen is also on
1916 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
1917 <= mCurForegroundState;
1918 }
1919
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001920 /**
Dianne Hackborn497175b2014-07-01 12:56:08 -07001921 * Process state of PID changed; recompute state at UID level. If
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001922 * changed, will trigger {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001923 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001924 void computeUidStateLocked(int uid) {
1925 final SparseIntArray pidState = mUidPidState.get(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001926
1927 // current pid is dropping foreground; examine other pids
Dianne Hackborn497175b2014-07-01 12:56:08 -07001928 int uidState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
1929 if (pidState != null) {
1930 final int size = pidState.size();
1931 for (int i = 0; i < size; i++) {
1932 final int state = pidState.valueAt(i);
1933 if (state < uidState) {
1934 uidState = state;
1935 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001936 }
1937 }
1938
Dianne Hackborn497175b2014-07-01 12:56:08 -07001939 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1940 if (oldUidState != uidState) {
1941 // state changed, push updated rules
1942 mUidState.put(uid, uidState);
1943 final boolean oldForeground = oldUidState <= mCurForegroundState;
1944 final boolean newForeground = uidState <= mCurForegroundState;
1945 if (oldForeground != newForeground) {
1946 updateRulesForUidLocked(uid);
1947 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001948 }
1949 }
1950
Jeff Sharkeya4620792011-05-20 15:29:23 -07001951 private void updateScreenOn() {
1952 synchronized (mRulesLock) {
1953 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07001954 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001955 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001956 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07001957 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001958 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001959 }
1960 }
1961
1962 /**
1963 * Update rules that might be changed by {@link #mScreenOn} value.
1964 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001965 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07001966 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07001967 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001968 for (int i = 0; i < size; i++) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001969 if (mUidState.valueAt(i) <= mCurForegroundState) {
1970 final int uid = mUidState.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001971 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001972 }
1973 }
1974 }
1975
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001976 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001977 * Update rules that might be changed by {@link #mRestrictBackground},
1978 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001979 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001980 void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001981 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001982 final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1983
Dianne Hackborn497175b2014-07-01 12:56:08 -07001984 // If we are in restrict power mode, we allow all important apps
1985 // to have data access. Otherwise, we restrict data access to only
1986 // the top apps.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001987 mCurForegroundState = (!mRestrictBackground && (mRestrictPower || mDeviceIdleMode))
Dianne Hackborn497175b2014-07-01 12:56:08 -07001988 ? ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
1989 : ActivityManager.PROCESS_STATE_TOP;
1990
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001991 // update rules for all installed applications
1992 final List<UserInfo> users = um.getUsers();
1993 final List<ApplicationInfo> apps = pm.getInstalledApplications(
1994 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
1995
1996 for (UserInfo user : users) {
1997 for (ApplicationInfo app : apps) {
1998 final int uid = UserHandle.getUid(user.id, app.uid);
1999 updateRulesForUidLocked(uid);
2000 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002001 }
2002
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002003 // limit data usage for some internal system services
2004 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
2005 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002006
2007 // If the set of restricted networks may have changed, re-evaluate those.
2008 if (restrictedNetworksChanged) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002009 normalizePoliciesLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002010 updateNetworkRulesLocked();
2011 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002012 }
2013
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002014 private static boolean isUidValidForRules(int uid) {
2015 // allow rules on specific system services, and any apps
2016 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002017 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002018 return true;
2019 }
2020
2021 return false;
2022 }
2023
Dianne Hackborn497175b2014-07-01 12:56:08 -07002024 void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002025 if (!isUidValidForRules(uid)) return;
2026
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002027 // quick check: if this uid doesn't have INTERNET permission, it doesn't have
2028 // network access anyway, so it is a waste to mess with it here.
2029 final IPackageManager ipm = AppGlobals.getPackageManager();
2030 try {
2031 if (ipm.checkUidPermission(Manifest.permission.INTERNET, uid)
2032 != PackageManager.PERMISSION_GRANTED) {
2033 return;
2034 }
2035 } catch (RemoteException e) {
2036 }
2037
Dianne Hackborn497175b2014-07-01 12:56:08 -07002038 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2039 final boolean uidForeground = isUidForegroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002040
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002041 // derive active rules based on policy and active state
2042 int uidRules = RULE_ALLOW_ALL;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002043 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002044 // uid in background, and policy says to block metered data
2045 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002046 } else if (mRestrictBackground) {
2047 if (!uidForeground) {
2048 // uid in background, and global background disabled
2049 uidRules = RULE_REJECT_METERED;
2050 }
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002051 } else if (mRestrictPower || mDeviceIdleMode) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002052 final boolean whitelisted = mPowerSaveWhitelistAppIds.get(UserHandle.getAppId(uid));
2053 if (!whitelisted && !uidForeground
2054 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
2055 // uid is in background, restrict power use mode is on (so we want to
2056 // restrict all background network access), and this uid is not on the
2057 // white list of those allowed background access.
2058 uidRules = RULE_REJECT_METERED;
2059 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002060 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002061
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002062 // TODO: only dispatch when rules actually change
2063
Jeff Sharkey350083e2011-06-29 10:45:16 -07002064 if (uidRules == RULE_ALLOW_ALL) {
2065 mUidRules.delete(uid);
2066 } else {
2067 mUidRules.put(uid, uidRules);
2068 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002069
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002070 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Ashish Sharma50fd36d2011-06-15 19:34:53 -07002071 setUidNetworkRules(uid, rejectMetered);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002072
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002073 // dispatch changed rule to existing listeners
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002074 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002075
2076 try {
2077 // adjust stats accounting based on foreground status
2078 mNetworkStats.setUidForeground(uid, uidForeground);
2079 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002080 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002081 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002082 }
2083
2084 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002085 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002086 public boolean handleMessage(Message msg) {
2087 switch (msg.what) {
2088 case MSG_RULES_CHANGED: {
2089 final int uid = msg.arg1;
2090 final int uidRules = msg.arg2;
2091 final int length = mListeners.beginBroadcast();
2092 for (int i = 0; i < length; i++) {
2093 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2094 if (listener != null) {
2095 try {
2096 listener.onUidRulesChanged(uid, uidRules);
2097 } catch (RemoteException e) {
2098 }
2099 }
2100 }
2101 mListeners.finishBroadcast();
2102 return true;
2103 }
2104 case MSG_METERED_IFACES_CHANGED: {
2105 final String[] meteredIfaces = (String[]) msg.obj;
2106 final int length = mListeners.beginBroadcast();
2107 for (int i = 0; i < length; i++) {
2108 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2109 if (listener != null) {
2110 try {
2111 listener.onMeteredIfacesChanged(meteredIfaces);
2112 } catch (RemoteException e) {
2113 }
2114 }
2115 }
2116 mListeners.finishBroadcast();
2117 return true;
2118 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002119 case MSG_LIMIT_REACHED: {
2120 final String iface = (String) msg.obj;
2121
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002122 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002123 synchronized (mRulesLock) {
2124 if (mMeteredIfaces.contains(iface)) {
2125 try {
2126 // force stats update to make sure we have
2127 // numbers that caused alert to trigger.
2128 mNetworkStats.forceUpdate();
2129 } catch (RemoteException e) {
2130 // ignored; service lives in system_server
2131 }
2132
2133 updateNetworkEnabledLocked();
2134 updateNotificationsLocked();
2135 }
2136 }
2137 return true;
2138 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002139 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2140 final boolean restrictBackground = msg.arg1 != 0;
2141 final int length = mListeners.beginBroadcast();
2142 for (int i = 0; i < length; i++) {
2143 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2144 if (listener != null) {
2145 try {
2146 listener.onRestrictBackgroundChanged(restrictBackground);
2147 } catch (RemoteException e) {
2148 }
2149 }
2150 }
2151 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002152 return true;
2153 }
2154 case MSG_ADVISE_PERSIST_THRESHOLD: {
2155 final long lowestRule = (Long) msg.obj;
2156 try {
2157 // make sure stats are recorded frequently enough; we aim
2158 // for 2MB threshold for 2GB/month rules.
2159 final long persistThreshold = lowestRule / 1000;
2160 mNetworkStats.advisePersistThreshold(persistThreshold);
2161 } catch (RemoteException e) {
2162 // ignored; service lives in system_server
2163 }
2164 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002165 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002166 case MSG_SCREEN_ON_CHANGED: {
2167 updateScreenOn();
2168 return true;
2169 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002170 default: {
2171 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002172 }
2173 }
2174 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002175 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002176
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002177 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002178 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002179 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002180 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002181 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002182 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002183 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002184 }
2185 }
2186
2187 private void removeInterfaceQuota(String iface) {
2188 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002189 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002190 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002191 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002192 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002193 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002194 }
2195 }
2196
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002197 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2198 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002199 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002200 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002201 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002202 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002203 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002204 }
2205 }
2206
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002207 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2208 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002209 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002210 } catch (RuntimeException e) {
2211 Slog.w(TAG, "problem reading network stats: " + e);
2212 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002213 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002214 // ignored; service lives in system_server
2215 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002216 }
2217 }
2218
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002219 private boolean isBandwidthControlEnabled() {
2220 final long token = Binder.clearCallingIdentity();
2221 try {
2222 return mNetworkManager.isBandwidthControlEnabled();
2223 } catch (RemoteException e) {
2224 // ignored; service lives in system_server
2225 return false;
2226 } finally {
2227 Binder.restoreCallingIdentity(token);
2228 }
2229 }
2230
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002231 /**
2232 * Try refreshing {@link #mTime} when stale.
2233 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002234 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002235 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002236 mTime.forceRefresh();
2237 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002238 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002239
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002240 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002241 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2242 }
2243
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002244 private static Intent buildAllowBackgroundDataIntent() {
2245 return new Intent(ACTION_ALLOW_BACKGROUND);
2246 }
2247
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002248 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2249 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2250 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2251 return intent;
2252 }
2253
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002254 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2255 final Intent intent = new Intent();
2256 intent.setComponent(new ComponentName(
2257 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2258 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2259 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2260 return intent;
2261 }
2262
2263 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2264 final Intent intent = new Intent();
2265 intent.setComponent(new ComponentName(
2266 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2267 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2268 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2269 return intent;
2270 }
2271
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002272 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002273 public void addIdleHandler(IdleHandler handler) {
2274 mHandler.getLooper().getQueue().addIdleHandler(handler);
2275 }
2276
Jeff Sharkey1b861272011-05-22 00:34:52 -07002277 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2278 final int size = source.size();
2279 for (int i = 0; i < size; i++) {
2280 target.put(source.keyAt(i), true);
2281 }
2282 }
2283
Dianne Hackborn497175b2014-07-01 12:56:08 -07002284 private static void dumpSparseIntArray(PrintWriter fout, SparseIntArray value) {
Jeff Sharkey1b861272011-05-22 00:34:52 -07002285 fout.print("[");
2286 final int size = value.size();
2287 for (int i = 0; i < size; i++) {
2288 fout.print(value.keyAt(i) + "=" + value.valueAt(i));
2289 if (i < size - 1) fout.print(",");
2290 }
2291 fout.print("]");
2292 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002293}