blob: 818f0aa0b36ed6e3dc0a74b61bd17dc0172023d0 [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;
Erik Klinef851d6d2015-04-20 16:03:48 +090030import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
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;
Svet Ganov16a16892015-04-16 10:32:04 -070077import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070078import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070079import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070080import android.app.IProcessObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070081import android.app.Notification;
82import android.app.PendingIntent;
Jeff Sharkeya4620792011-05-20 15:29:23 -070083import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070084import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070085import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070086import android.content.Intent;
87import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070088import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070089import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070090import android.content.pm.PackageManager;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -070091import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -070092import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070093import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070094import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070095import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070096import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070097import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -070098import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070099import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700100import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700101import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700102import android.net.NetworkPolicy;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700103import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700104import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700105import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700106import android.net.wifi.WifiConfiguration;
107import android.net.wifi.WifiInfo;
108import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700109import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700110import android.os.Environment;
111import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700112import android.os.HandlerThread;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700113import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700114import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700115import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700116import android.os.MessageQueue.IdleHandler;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700117import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700118import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700119import android.os.RemoteException;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700120import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700121import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700122import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800123import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700124import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700125import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700126import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700127import android.util.ArrayMap;
128import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700129import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700130import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700131import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700132import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700133import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700134import android.util.SparseArray;
135import android.util.SparseBooleanArray;
136import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700137import android.util.TrustedTime;
138import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700139
Svet Ganov16a16892015-04-16 10:32:04 -0700140import com.android.server.AppOpsService;
Jeff Sharkey32566012014-12-02 18:30:14 -0800141import libcore.io.IoUtils;
142
Jeff Sharkey497e4432011-06-14 17:27:29 -0700143import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800144import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey32566012014-12-02 18:30:14 -0800145import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700146import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700147import com.android.internal.util.IndentingPrintWriter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700148import com.android.server.LocalServices;
149import com.android.server.SystemConfig;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700150import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700151
152import org.xmlpull.v1.XmlPullParser;
153import org.xmlpull.v1.XmlPullParserException;
154import org.xmlpull.v1.XmlSerializer;
155
156import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700157import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700158import java.io.FileInputStream;
159import java.io.FileNotFoundException;
160import java.io.FileOutputStream;
161import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700162import java.io.PrintWriter;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700163import java.util.ArrayList;
164import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700165import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700166
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700167/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700168 * Service that maintains low-level network policy rules, using
169 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700170 * <p>
171 * Derives active rules by combining a given policy with other system status,
172 * and delivers to listeners, such as {@link ConnectivityManager}, for
173 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700174 */
175public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
176 private static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700177 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700178 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700179
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700180 private static final int VERSION_INIT = 1;
181 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700182 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800183 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800184 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800185 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700186 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700187 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700188 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700189 private static final int VERSION_SWITCH_UID = 10;
190 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700191
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800192 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700193 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800194 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700195 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800196 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700197 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700198
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700199 private static final String TAG_POLICY_LIST = "policy-list";
200 private static final String TAG_NETWORK_POLICY = "network-policy";
201 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700202 private static final String TAG_APP_POLICY = "app-policy";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700203
204 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700205 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700206 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
207 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700208 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700209 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800210 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700211 private static final String ATTR_WARNING_BYTES = "warningBytes";
212 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700213 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800214 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
215 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800216 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700217 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700218 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700219 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700220 private static final String ATTR_POLICY = "policy";
221
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700222 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
223
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800224 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800225 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800226 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800227 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700228
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700229 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
230
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700231 private static final int MSG_RULES_CHANGED = 1;
232 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800233 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800234 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700235 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700236 private static final int MSG_SCREEN_ON_CHANGED = 8;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700237
Jeff Sharkey75279902011-05-24 18:39:45 -0700238 private final Context mContext;
239 private final IActivityManager mActivityManager;
240 private final IPowerManager mPowerManager;
241 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700242 private final INetworkManagementService mNetworkManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700243 private final TrustedTime mTime;
244
245 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700246 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700247 private PowerManagerInternal mPowerManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700248
Dianne Hackborn497175b2014-07-01 12:56:08 -0700249 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700250
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700251 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700252 volatile boolean mScreenOn;
253 volatile boolean mRestrictBackground;
254 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700255 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700256
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700257 private final boolean mSuppressDefaultPolicy;
258
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700259 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800260 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700261 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800262 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700263
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700264 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700265 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700266 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800267 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700268
Jeff Sharkey32566012014-12-02 18:30:14 -0800269 /**
270 * UIDs that have been white-listed to always be able to have network access
271 * in power save mode.
272 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700273 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700274
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700275 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800276 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700277 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800278 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700279
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700280 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700281 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700282
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700283 /** Foreground at both UID and PID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800284 final SparseIntArray mUidState = new SparseIntArray();
285 final SparseArray<SparseIntArray> mUidPidState = new SparseArray<>();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700286
287 /** The current maximum process state that we are considering to be foreground. */
288 private int mCurForegroundState = ActivityManager.PROCESS_STATE_TOP;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700289
Jeff Sharkey32566012014-12-02 18:30:14 -0800290 private final RemoteCallbackList<INetworkPolicyListener>
291 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700292
Dianne Hackborn497175b2014-07-01 12:56:08 -0700293 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700294
295 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700296
Svet Ganov16a16892015-04-16 10:32:04 -0700297 private final AppOpsManager mAppOps;
298
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700299 // TODO: keep whitelist of system-critical services that should never have
300 // rules enforced, such as system, phone, and radio UIDs.
301
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700302 // TODO: migrate notifications to SystemUI
303
Jeff Sharkey75279902011-05-24 18:39:45 -0700304 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700305 IPowerManager powerManager, INetworkStatsService networkStats,
306 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700307 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700308 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700309 }
310
311 private static File getSystemDir() {
312 return new File(Environment.getDataDirectory(), "system");
313 }
314
315 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700316 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700317 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
318 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700319 mContext = checkNotNull(context, "missing context");
320 mActivityManager = checkNotNull(activityManager, "missing activityManager");
321 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700322 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700323 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700324 mTime = checkNotNull(time, "missing TrustedTime");
325
Amith Yamasani450a16b2013-09-18 16:28:50 -0700326 HandlerThread thread = new HandlerThread(TAG);
327 thread.start();
328 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700329
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700330 mSuppressDefaultPolicy = suppressDefaultPolicy;
331
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700332 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700333
334 mAppOps = context.getSystemService(AppOpsManager.class);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700335 }
336
337 public void bindConnectivityManager(IConnectivityManager connManager) {
338 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700339 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700340
Jeff Sharkey497e4432011-06-14 17:27:29 -0700341 public void bindNotificationManager(INotificationManager notifManager) {
342 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
343 }
344
Jeff Sharkeya4620792011-05-20 15:29:23 -0700345 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700346 if (!isBandwidthControlEnabled()) {
347 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
348 return;
349 }
350
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700351 final PackageManager pm = mContext.getPackageManager();
352
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700353 synchronized (mRulesLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700354 SystemConfig sysConfig = SystemConfig.getInstance();
355 ArraySet<String> allowPower = sysConfig.getAllowInPowerSave();
356 for (int i=0; i<allowPower.size(); i++) {
357 String pkg = allowPower.valueAt(i);
358 try {
359 ApplicationInfo ai = pm.getApplicationInfo(pkg, 0);
360 if ((ai.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
361 mPowerSaveWhitelistAppIds.put(UserHandle.getAppId(ai.uid), true);
362 }
363 } catch (PackageManager.NameNotFoundException e) {
364 }
365 }
366
367 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
368 mPowerManagerInternal.registerLowPowerModeObserver(
369 new PowerManagerInternal.LowPowerModeListener() {
370 @Override
371 public void onLowPowerModeChanged(boolean enabled) {
372 synchronized (mRulesLock) {
373 if (mRestrictPower != enabled) {
374 mRestrictPower = enabled;
375 updateRulesForGlobalChangeLocked(true);
376 }
377 }
378 }
379 });
380 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700381 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700382
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700383 // read policy from disk
384 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700385
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700386 if (mRestrictBackground || mRestrictPower || mDeviceIdleMode) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700387 updateRulesForGlobalChangeLocked(true);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700388 updateNotificationsLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700389 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700390 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700391
Jeff Sharkeya4620792011-05-20 15:29:23 -0700392 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700393
Jeff Sharkeya4620792011-05-20 15:29:23 -0700394 try {
395 mActivityManager.registerProcessObserver(mProcessObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700396 mNetworkManager.registerObserver(mAlertObserver);
397 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700398 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700399 }
400
Jeff Sharkeya4620792011-05-20 15:29:23 -0700401 // TODO: traverse existing processes to know foreground state, or have
402 // activitymanager dispatch current state when new observer attached.
403
404 final IntentFilter screenFilter = new IntentFilter();
405 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
406 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700407 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700408
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700409 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900410 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700411 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
412
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700413 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700414 final IntentFilter packageFilter = new IntentFilter();
415 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700416 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700417 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700418
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700419 // listen for UID changes to update policy
420 mContext.registerReceiver(
421 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
422
423 // listen for user changes to update policy
424 final IntentFilter userFilter = new IntentFilter();
425 userFilter.addAction(ACTION_USER_ADDED);
426 userFilter.addAction(ACTION_USER_REMOVED);
427 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
428
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700429 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700430 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
431 mContext.registerReceiver(
432 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
433
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700434 // listen for restrict background changes from notifications
435 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
436 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
437
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800438 // listen for snooze warning from notifications
439 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
440 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
441 MANAGE_NETWORK_POLICY, mHandler);
442
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700443 // listen for configured wifi networks to be removed
444 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700445 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700446
447 // listen for wifi state changes to catch metered hint
448 final IntentFilter wifiStateFilter = new IntentFilter(
449 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700450 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700451
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700452 }
453
Jeff Sharkeya4620792011-05-20 15:29:23 -0700454 private IProcessObserver mProcessObserver = new IProcessObserver.Stub() {
455 @Override
456 public void onForegroundActivitiesChanged(int pid, int uid, boolean foregroundActivities) {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700457 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700458
459 @Override
Dianne Hackborn684bf342014-04-29 17:56:57 -0700460 public void onProcessStateChanged(int pid, int uid, int procState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700461 synchronized (mRulesLock) {
462 // because a uid can have multiple pids running inside, we need to
463 // remember all pid states and summarize foreground at uid level.
464
465 // record foreground for this specific pid
466 SparseIntArray pidState = mUidPidState.get(uid);
467 if (pidState == null) {
468 pidState = new SparseIntArray(2);
469 mUidPidState.put(uid, pidState);
470 }
471 pidState.put(pid, procState);
472 computeUidStateLocked(uid);
473 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700474 }
475
476 @Override
Jeff Sharkeya4620792011-05-20 15:29:23 -0700477 public void onProcessDied(int pid, int uid) {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700478 synchronized (mRulesLock) {
479 // clear records and recompute, when they exist
480 final SparseIntArray pidState = mUidPidState.get(uid);
481 if (pidState != null) {
482 pidState.delete(pid);
483 if (pidState.size() <= 0) {
484 mUidPidState.remove(uid);
485 }
486 computeUidStateLocked(uid);
487 }
488 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700489 }
490 };
491
492 private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
493 @Override
494 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800495 // screen-related broadcasts are protected by system, no need
496 // for permissions check.
497 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700498 }
499 };
500
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700501 private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700502 @Override
503 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700504 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700505
506 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700507 final int uid = intent.getIntExtra(EXTRA_UID, -1);
508 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700509
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700510 if (ACTION_PACKAGE_ADDED.equals(action)) {
511 // update rules for UID, since it might be subject to
512 // global background data policy
513 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
514 synchronized (mRulesLock) {
515 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700516 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700517 }
518 }
519 };
520
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700521 private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
522 @Override
523 public void onReceive(Context context, Intent intent) {
524 // on background handler thread, and UID_REMOVED is protected
525
526 final int uid = intent.getIntExtra(EXTRA_UID, -1);
527 if (uid == -1) return;
528
529 // remove any policy and update rules to clean up
530 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
531 synchronized (mRulesLock) {
532 mUidPolicy.delete(uid);
533 updateRulesForUidLocked(uid);
534 writePolicyLocked();
535 }
536 }
537 };
538
539 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
540 @Override
541 public void onReceive(Context context, Intent intent) {
542 // on background handler thread, and USER_ADDED and USER_REMOVED
543 // broadcasts are protected
544
545 final String action = intent.getAction();
546 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
547 if (userId == -1) return;
548
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700549 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700550 // Remove any policies for given user; both cleaning up after a
551 // USER_REMOVED, and one last sanity check during USER_ADDED
552 removePoliciesForUserLocked(userId);
553 // Update global restrict for new user
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700554 updateRulesForGlobalChangeLocked(true);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700555 }
556 }
557 };
558
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700559 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700560 * Receiver that watches for {@link INetworkStatsService} updates, which we
561 * use to check against {@link NetworkPolicy#warningBytes}.
562 */
563 private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
564 @Override
565 public void onReceive(Context context, Intent intent) {
566 // on background handler thread, and verified
567 // READ_NETWORK_USAGE_HISTORY permission above.
568
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800569 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700570 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700571 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700572 updateNotificationsLocked();
573 }
574 }
575 };
576
577 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700578 * Receiver that watches for {@link Notification} control of
579 * {@link #mRestrictBackground}.
580 */
581 private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
582 @Override
583 public void onReceive(Context context, Intent intent) {
584 // on background handler thread, and verified MANAGE_NETWORK_POLICY
585 // permission above.
586
587 setRestrictBackground(false);
588 }
589 };
590
591 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800592 * Receiver that watches for {@link Notification} control of
593 * {@link NetworkPolicy#lastWarningSnooze}.
594 */
595 private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
596 @Override
597 public void onReceive(Context context, Intent intent) {
598 // on background handler thread, and verified MANAGE_NETWORK_POLICY
599 // permission above.
600
601 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
602 performSnooze(template, TYPE_WARNING);
603 }
604 };
605
606 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700607 * Receiver that watches for {@link WifiConfiguration} to be changed.
608 */
609 private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
610 @Override
611 public void onReceive(Context context, Intent intent) {
612 // on background handler thread, and verified CONNECTIVITY_INTERNAL
613 // permission above.
614
615 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
616 if (reason == CHANGE_REASON_REMOVED) {
617 final WifiConfiguration config = intent.getParcelableExtra(
618 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700619 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800620 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700621 synchronized (mRulesLock) {
622 if (mNetworkPolicy.containsKey(template)) {
623 mNetworkPolicy.remove(template);
624 writePolicyLocked();
625 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700626 }
627 }
628 }
629 }
630 };
631
632 /**
633 * Receiver that watches {@link WifiInfo} state changes to infer metered
634 * state. Ignores hints when policy is user-defined.
635 */
636 private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
637 @Override
638 public void onReceive(Context context, Intent intent) {
639 // on background handler thread, and verified CONNECTIVITY_INTERNAL
640 // permission above.
641
642 // ignore when not connected
643 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
644 if (!netInfo.isConnected()) return;
645
646 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
647 final boolean meteredHint = info.getMeteredHint();
648
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800649 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700650 synchronized (mRulesLock) {
651 NetworkPolicy policy = mNetworkPolicy.get(template);
652 if (policy == null && meteredHint) {
653 // policy doesn't exist, and AP is hinting that it's
654 // metered: create an inferred policy.
655 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
656 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
657 meteredHint, true);
658 addNetworkPolicyLocked(policy);
659
660 } else if (policy != null && policy.inferred) {
661 // policy exists, and was inferred: update its current
662 // metered state.
663 policy.metered = meteredHint;
664
665 // since this is inferred for each wifi session, just update
666 // rules without persisting.
667 updateNetworkRulesLocked();
668 }
669 }
670 }
671 };
672
673 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700674 * Observer that watches for {@link INetworkManagementService} alerts.
675 */
Jeff Sharkey216c1812012-08-05 14:29:23 -0700676 private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700677 @Override
678 public void limitReached(String limitName, String iface) {
679 // only someone like NMS should be calling us
680 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
681
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800682 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
683 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700684 }
685 }
686 };
687
688 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700689 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
690 * to show visible notifications as needed.
691 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700692 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700693 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
694
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700695 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700696 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700697 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700698
699 // TODO: when switching to kernel notifications, compute next future
700 // cycle boundary to recompute notifications.
701
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700702 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800703 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700704 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
705 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700706 // ignore policies that aren't relevant to user
707 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700708 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700709
Jeff Sharkey497e4432011-06-14 17:27:29 -0700710 final long start = computeLastCycleBoundary(currentTime, policy);
711 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700712 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700713
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700714 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800715 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700716 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
717 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700718 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
719 notifyOverLimitLocked(policy.template);
720 }
721
Jeff Sharkey497e4432011-06-14 17:27:29 -0700722 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700723 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700724
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800725 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700726 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700727 }
728 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700729 }
730
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700731 // ongoing notification when restricting background data
732 if (mRestrictBackground) {
733 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700734 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700735
736 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700737 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
738 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700739 if (!mActiveNotifs.contains(tag)) {
740 cancelNotification(tag);
741 }
742 }
743 }
744
745 /**
746 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700747 * current device state, such as when
748 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
749 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700750 */
751 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800752 if (template.isMatchRuleMobile()) {
753 final TelephonyManager tele = TelephonyManager.from(mContext);
754 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700755
Jeff Sharkey32566012014-12-02 18:30:14 -0800756 // Mobile template is relevant when any active subscriber matches
757 final int[] subIds = sub.getActiveSubscriptionIdList();
758 for (int subId : subIds) {
759 final String subscriberId = tele.getSubscriberId(subId);
760 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
761 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
762 if (template.matches(probeIdent)) {
763 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700764 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800765 }
766 return false;
767 } else {
768 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700769 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700770 }
771
772 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700773 * Notify that given {@link NetworkTemplate} is over
774 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
775 */
776 private void notifyOverLimitLocked(NetworkTemplate template) {
777 if (!mOverLimitNotified.contains(template)) {
778 mContext.startActivity(buildNetworkOverLimitIntent(template));
779 mOverLimitNotified.add(template);
780 }
781 }
782
783 private void notifyUnderLimitLocked(NetworkTemplate template) {
784 mOverLimitNotified.remove(template);
785 }
786
787 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700788 * Build unique tag that identifies an active {@link NetworkPolicy}
789 * notification of a specific type, like {@link #TYPE_LIMIT}.
790 */
791 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700792 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700793 }
794
795 /**
796 * Show notification for combined {@link NetworkPolicy} and specific type,
797 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
798 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700799 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700800 final String tag = buildNotificationTag(policy, type);
801 final Notification.Builder builder = new Notification.Builder(mContext);
802 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800803 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700804 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200805 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700806
807 final Resources res = mContext.getResources();
808 switch (type) {
809 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700810 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700811 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700812
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700813 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700814 builder.setTicker(title);
815 builder.setContentTitle(title);
816 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700817
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800818 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
819 builder.setDeleteIntent(PendingIntent.getBroadcast(
820 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
821
822 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700823 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800824 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
825
Jeff Sharkey497e4432011-06-14 17:27:29 -0700826 break;
827 }
828 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700829 final CharSequence body = res.getText(R.string.data_usage_limit_body);
830
831 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -0400832 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700833 switch (policy.template.getMatchRule()) {
834 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700835 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700836 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700837 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700838 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700839 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700840 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700841 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700842 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700843 case MATCH_WIFI:
844 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -0400845 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700846 break;
847 default:
848 title = null;
849 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700850 }
851
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800852 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -0400853 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700854 builder.setTicker(title);
855 builder.setContentTitle(title);
856 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700857
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700858 final Intent intent = buildNetworkOverLimitIntent(policy.template);
859 builder.setContentIntent(PendingIntent.getActivity(
860 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
861 break;
862 }
863 case TYPE_LIMIT_SNOOZED: {
864 final long overBytes = totalBytes - policy.limitBytes;
865 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
866 Formatter.formatFileSize(mContext, overBytes));
867
868 final CharSequence title;
869 switch (policy.template.getMatchRule()) {
870 case MATCH_MOBILE_3G_LOWER:
871 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
872 break;
873 case MATCH_MOBILE_4G:
874 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
875 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700876 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700877 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
878 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700879 case MATCH_WIFI:
880 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
881 break;
882 default:
883 title = null;
884 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700885 }
886
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800887 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700888 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700889 builder.setTicker(title);
890 builder.setContentTitle(title);
891 builder.setContentText(body);
892
893 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700894 builder.setContentIntent(PendingIntent.getActivity(
895 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700896 break;
897 }
898 }
899
900 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700901 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700902 try {
903 final String packageName = mContext.getPackageName();
904 final int[] idReceived = new int[1];
905 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800906 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Dianne Hackborn41203752012-08-31 14:05:51 -0700907 UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700908 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700909 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700910 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700911 }
912 }
913
914 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700915 * Show ongoing notification to reflect that {@link #mRestrictBackground}
916 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700917 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700918 private void enqueueRestrictedNotification(String tag) {
919 final Resources res = mContext.getResources();
920 final Notification.Builder builder = new Notification.Builder(mContext);
921
922 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
923 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
924
925 builder.setOnlyAlertOnce(true);
926 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700927 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700928 builder.setTicker(title);
929 builder.setContentTitle(title);
930 builder.setContentText(body);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700931 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200932 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700933
934 final Intent intent = buildAllowBackgroundDataIntent();
935 builder.setContentIntent(
936 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700937
938 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700939 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700940 try {
941 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700942 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800943 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Dianne Hackborn41203752012-08-31 14:05:51 -0700944 0x0, builder.getNotification(), idReceived, UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700945 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700946 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700947 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700948 }
949 }
950
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700951 private void cancelNotification(String tag) {
952 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700953 // XXX what to do about multi-user?
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700954 try {
955 final String packageName = mContext.getPackageName();
956 mNotifManager.cancelNotificationWithTag(
Dianne Hackborn41203752012-08-31 14:05:51 -0700957 packageName, tag, 0x0, UserHandle.USER_OWNER);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700958 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700959 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700960 }
961 }
962
963 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700964 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700965 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700966 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700967 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700968 @Override
969 public void onReceive(Context context, Intent intent) {
970 // on background handler thread, and verified CONNECTIVITY_INTERNAL
971 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800972
973 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700974 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700975 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -0800976 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700977 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700978 updateNetworkRulesLocked();
979 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700980 }
981 }
982 };
983
984 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700985 * Proactively control network data connections when they exceed
986 * {@link NetworkPolicy#limitBytes}.
987 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700988 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700989 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
990
991 // TODO: reset any policy-disabled networks when any policy is removed
992 // completely, which is currently rare case.
993
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800994 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700995 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
996 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700997 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700998 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700999 setNetworkTemplateEnabled(policy.template, true);
1000 continue;
1001 }
1002
1003 final long start = computeLastCycleBoundary(currentTime, policy);
1004 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001005 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001006
1007 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001008 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1009 && policy.lastLimitSnooze < start;
1010 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001011
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001012 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001013 }
1014 }
1015
1016 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001017 * Proactively disable networks that match the given
1018 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001019 */
1020 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001021 // TODO: reach into ConnectivityManager to proactively disable bringing
1022 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001023 }
1024
1025 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001026 * Examine all connected {@link NetworkState}, looking for
1027 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1028 * remaining quota based on usage cycle and historical stats.
1029 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001030 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001031 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001032
1033 final NetworkState[] states;
1034 try {
1035 states = mConnManager.getAllNetworkState();
1036 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001037 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001038 return;
1039 }
1040
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001041 // If we are in restrict power mode, we want to treat all interfaces
1042 // as metered, to restrict access to the network by uid. However, we
1043 // will not have a bandwidth limit. Also only do this if restrict
1044 // background data use is *not* enabled, since that takes precendence
1045 // use over those networks can have a cost associated with it).
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001046 final boolean powerSave = (mRestrictPower || mDeviceIdleMode) && !mRestrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001047
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001048 // First, generate identities of all connected networks so we can
1049 // quickly compare them against all defined policies below.
1050 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001051 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001052 for (NetworkState state : states) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001053 if (state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001054 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001055
1056 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001057 if (baseIface != null) {
1058 connIdents.add(Pair.create(baseIface, ident));
1059 if (powerSave) {
1060 connIfaces.add(baseIface);
1061 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001062 }
1063
1064 // Stacked interfaces are considered to have same identity as
1065 // their parent network.
1066 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1067 for (LinkProperties stackedLink : stackedLinks) {
1068 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001069 if (stackedIface != null) {
1070 connIdents.add(Pair.create(stackedIface, ident));
1071 if (powerSave) {
1072 connIfaces.add(stackedIface);
1073 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001074 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001075 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001076 }
1077 }
1078
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001079 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001080 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001081 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001082 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001083 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001084
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001085 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001086 for (int j = connIdents.size() - 1; j >= 0; j--) {
1087 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1088 if (policy.template.matches(ident.second)) {
1089 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001090 }
1091 }
1092
1093 if (ifaceList.size() > 0) {
1094 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001095 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001096 }
1097 }
1098
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001099 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001100 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001101
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001102 // apply each policy that we found ifaces for; compute remaining data
1103 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001104 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001105 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1106 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1107 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001108
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001109 final long start;
1110 final long totalBytes;
1111 if (policy.hasCycle()) {
1112 start = computeLastCycleBoundary(currentTime, policy);
1113 totalBytes = getTotalBytes(policy.template, start, currentTime);
1114 } else {
1115 start = Long.MAX_VALUE;
1116 totalBytes = 0;
1117 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001118
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001119 if (LOGD) {
1120 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001121 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001122 }
1123
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001124 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001125 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001126 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001127 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001128 if (!hasLimit) {
1129 // metered network, but no policy limit; we still need to
1130 // restrict apps, so push really high quota.
1131 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001132 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001133 // snoozing past quota, but we still need to restrict apps,
1134 // so push really high quota.
1135 quotaBytes = Long.MAX_VALUE;
1136 } else {
1137 // remaining "quota" bytes are based on total usage in
1138 // current cycle. kernel doesn't like 0-byte rules, so we
1139 // set 1-byte quota and disable the radio later.
1140 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1141 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001142
1143 if (ifaces.length > 1) {
1144 // TODO: switch to shared quota once NMS supports
1145 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001146 }
1147
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001148 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001149 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001150 setInterfaceQuota(iface, quotaBytes);
1151 newMeteredIfaces.add(iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001152 if (powerSave) {
1153 connIfaces.remove(iface);
1154 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001155 }
1156 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001157
1158 // keep track of lowest warning or limit of active policies
1159 if (hasWarning && policy.warningBytes < lowestRule) {
1160 lowestRule = policy.warningBytes;
1161 }
1162 if (hasLimit && policy.limitBytes < lowestRule) {
1163 lowestRule = policy.limitBytes;
1164 }
1165 }
1166
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001167 for (int i = connIfaces.size()-1; i >= 0; i--) {
1168 String iface = connIfaces.valueAt(i);
1169 removeInterfaceQuota(iface);
1170 setInterfaceQuota(iface, Long.MAX_VALUE);
1171 newMeteredIfaces.add(iface);
1172 }
1173
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001174 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001175
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001176 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001177 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1178 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001179 if (!newMeteredIfaces.contains(iface)) {
1180 removeInterfaceQuota(iface);
1181 }
1182 }
1183 mMeteredIfaces = newMeteredIfaces;
1184
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001185 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001186 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001187 }
1188
1189 /**
1190 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1191 * have at least a default mobile policy defined.
1192 */
1193 private void ensureActiveMobilePolicyLocked() {
1194 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001195 if (mSuppressDefaultPolicy) return;
1196
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001197 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001198 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001199
Jeff Sharkey32566012014-12-02 18:30:14 -08001200 final int[] subIds = sub.getActiveSubscriptionIdList();
1201 for (int subId : subIds) {
1202 final String subscriberId = tele.getSubscriberId(subId);
1203 ensureActiveMobilePolicyLocked(subscriberId);
1204 }
1205 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001206
Jeff Sharkey32566012014-12-02 18:30:14 -08001207 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1208 // Poke around to see if we already have a policy
1209 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1210 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1211 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1212 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1213 if (template.matches(probeIdent)) {
1214 if (LOGD) {
1215 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1216 + NetworkIdentity.scrubSubscriberId(subscriberId));
1217 }
1218 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001219 }
1220 }
1221
Jeff Sharkey32566012014-12-02 18:30:14 -08001222 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1223 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001224
Jeff Sharkey32566012014-12-02 18:30:14 -08001225 // Build default mobile policy, and assume usage cycle starts today
1226 final long warningBytes = mContext.getResources().getInteger(
1227 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001228
Jeff Sharkey32566012014-12-02 18:30:14 -08001229 final Time time = new Time();
1230 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001231
Jeff Sharkey32566012014-12-02 18:30:14 -08001232 final int cycleDay = time.monthDay;
1233 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001234
Jeff Sharkey32566012014-12-02 18:30:14 -08001235 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1236 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1237 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1238 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001239 }
1240
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001241 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001242 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001243
1244 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001245 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001246 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001247
1248 FileInputStream fis = null;
1249 try {
1250 fis = mPolicyFile.openRead();
1251 final XmlPullParser in = Xml.newPullParser();
1252 in.setInput(fis, null);
1253
1254 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001255 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001256 while ((type = in.next()) != END_DOCUMENT) {
1257 final String tag = in.getName();
1258 if (type == START_TAG) {
1259 if (TAG_POLICY_LIST.equals(tag)) {
1260 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001261 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1262 mRestrictBackground = readBooleanAttribute(
1263 in, ATTR_RESTRICT_BACKGROUND);
1264 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001265 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001266 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001267
1268 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1269 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1270 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001271 final String networkId;
1272 if (version >= VERSION_ADDED_NETWORK_ID) {
1273 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1274 } else {
1275 networkId = null;
1276 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001277 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001278 final String cycleTimezone;
1279 if (version >= VERSION_ADDED_TIMEZONE) {
1280 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1281 } else {
1282 cycleTimezone = Time.TIMEZONE_UTC;
1283 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001284 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1285 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001286 final long lastLimitSnooze;
1287 if (version >= VERSION_SPLIT_SNOOZE) {
1288 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1289 } else if (version >= VERSION_ADDED_SNOOZE) {
1290 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001291 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001292 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001293 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001294 final boolean metered;
1295 if (version >= VERSION_ADDED_METERED) {
1296 metered = readBooleanAttribute(in, ATTR_METERED);
1297 } else {
1298 switch (networkTemplate) {
1299 case MATCH_MOBILE_3G_LOWER:
1300 case MATCH_MOBILE_4G:
1301 case MATCH_MOBILE_ALL:
1302 metered = true;
1303 break;
1304 default:
1305 metered = false;
1306 }
1307 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001308 final long lastWarningSnooze;
1309 if (version >= VERSION_SPLIT_SNOOZE) {
1310 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1311 } else {
1312 lastWarningSnooze = SNOOZE_NEVER;
1313 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001314 final boolean inferred;
1315 if (version >= VERSION_ADDED_INFERRED) {
1316 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1317 } else {
1318 inferred = false;
1319 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001320
Jeff Sharkey32566012014-12-02 18:30:14 -08001321 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1322 subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001323 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001324 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001325 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001326
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001327 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001328 final int uid = readIntAttribute(in, ATTR_UID);
1329 final int policy = readIntAttribute(in, ATTR_POLICY);
1330
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001331 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001332 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001333 } else {
1334 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1335 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001336 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001337 final int appId = readIntAttribute(in, ATTR_APP_ID);
1338 final int policy = readIntAttribute(in, ATTR_POLICY);
1339
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001340 // TODO: set for other users during upgrade
1341 final int uid = UserHandle.getUid(UserHandle.USER_OWNER, appId);
1342 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001343 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001344 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001345 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001346 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001347 }
1348 }
1349 }
1350
1351 } catch (FileNotFoundException e) {
1352 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001353 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001354 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001355 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001356 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001357 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001358 } finally {
1359 IoUtils.closeQuietly(fis);
1360 }
1361 }
1362
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001363 /**
1364 * Upgrade legacy background data flags, notifying listeners of one last
1365 * change to always-true.
1366 */
1367 private void upgradeLegacyBackgroundData() {
1368 mRestrictBackground = Settings.Secure.getInt(
1369 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1370
1371 // kick off one last broadcast if restricted
1372 if (mRestrictBackground) {
1373 final Intent broadcast = new Intent(
1374 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001375 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001376 }
1377 }
1378
Dianne Hackborn497175b2014-07-01 12:56:08 -07001379 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001380 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001381
1382 FileOutputStream fos = null;
1383 try {
1384 fos = mPolicyFile.startWrite();
1385
1386 XmlSerializer out = new FastXmlSerializer();
1387 out.setOutput(fos, "utf-8");
1388 out.startDocument(null, true);
1389
1390 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001391 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001392 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001393
1394 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001395 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1396 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001397 final NetworkTemplate template = policy.template;
1398
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001399 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001400 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1401 final String subscriberId = template.getSubscriberId();
1402 if (subscriberId != null) {
1403 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001404 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001405 final String networkId = template.getNetworkId();
1406 if (networkId != null) {
1407 out.attribute(null, ATTR_NETWORK_ID, networkId);
1408 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001409 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001410 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001411 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1412 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001413 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1414 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001415 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001416 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001417 out.endTag(null, TAG_NETWORK_POLICY);
1418 }
1419
1420 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001421 for (int i = 0; i < mUidPolicy.size(); i++) {
1422 final int uid = mUidPolicy.keyAt(i);
1423 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001424
Jeff Sharkey497e4432011-06-14 17:27:29 -07001425 // skip writing empty policies
1426 if (policy == POLICY_NONE) continue;
1427
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001428 out.startTag(null, TAG_UID_POLICY);
1429 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001430 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001431 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001432 }
1433
1434 out.endTag(null, TAG_POLICY_LIST);
1435 out.endDocument();
1436
1437 mPolicyFile.finishWrite(fos);
1438 } catch (IOException e) {
1439 if (fos != null) {
1440 mPolicyFile.failWrite(fos);
1441 }
1442 }
1443 }
1444
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001445 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001446 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001447 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001448
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001449 if (!UserHandle.isApp(uid)) {
1450 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001451 }
1452
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001453 synchronized (mRulesLock) {
1454 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1455 if (oldPolicy != policy) {
1456 setUidPolicyUncheckedLocked(uid, policy, true);
1457 }
1458 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001459 }
1460
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001461 @Override
1462 public void addUidPolicy(int uid, int policy) {
1463 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001464
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001465 if (!UserHandle.isApp(uid)) {
1466 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1467 }
1468
1469 synchronized (mRulesLock) {
1470 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1471 policy |= oldPolicy;
1472 if (oldPolicy != policy) {
1473 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001474 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001475 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001476 }
1477
1478 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001479 public void removeUidPolicy(int uid, int policy) {
1480 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1481
1482 if (!UserHandle.isApp(uid)) {
1483 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1484 }
1485
1486 synchronized (mRulesLock) {
1487 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1488 policy = oldPolicy & ~policy;
1489 if (oldPolicy != policy) {
1490 setUidPolicyUncheckedLocked(uid, policy, true);
1491 }
1492 }
1493 }
1494
1495 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1496 mUidPolicy.put(uid, policy);
1497
1498 // uid policy changed, recompute rules and persist policy.
1499 updateRulesForUidLocked(uid);
1500 if (persist) {
1501 writePolicyLocked();
1502 }
1503 }
1504
1505 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001506 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001507 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1508
Jeff Sharkeya4620792011-05-20 15:29:23 -07001509 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001510 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001511 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001512 }
1513
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001514 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001515 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001516 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1517
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001518 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001519 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001520 for (int i = 0; i < mUidPolicy.size(); i++) {
1521 final int uid = mUidPolicy.keyAt(i);
1522 final int uidPolicy = mUidPolicy.valueAt(i);
1523 if (uidPolicy == policy) {
1524 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001525 }
1526 }
1527 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001528 return uids;
1529 }
1530
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001531 @Override
1532 public int[] getPowerSaveAppIdWhitelist() {
1533 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1534
1535 synchronized (mRulesLock) {
1536 int size = mPowerSaveWhitelistAppIds.size();
1537 int[] appids = new int[size];
1538 for (int i = 0; i < size; i++) {
1539 appids[i] = mPowerSaveWhitelistAppIds.keyAt(i);
1540 }
1541 return appids;
1542 }
1543 }
1544
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001545 /**
1546 * Remove any policies associated with given {@link UserHandle}, persisting
1547 * if any changes are made.
1548 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001549 void removePoliciesForUserLocked(int userId) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001550 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1551
1552 int[] uids = new int[0];
1553 for (int i = 0; i < mUidPolicy.size(); i++) {
1554 final int uid = mUidPolicy.keyAt(i);
1555 if (UserHandle.getUserId(uid) == userId) {
1556 uids = appendInt(uids, uid);
1557 }
1558 }
1559
1560 if (uids.length > 0) {
1561 for (int uid : uids) {
1562 mUidPolicy.delete(uid);
1563 updateRulesForUidLocked(uid);
1564 }
1565 writePolicyLocked();
1566 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001567 }
1568
1569 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001570 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001571 // TODO: create permission for observing network policy
1572 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1573
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001574 mListeners.register(listener);
1575
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001576 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001577 }
1578
1579 @Override
1580 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001581 // TODO: create permission for observing network policy
1582 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1583
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001584 mListeners.unregister(listener);
1585 }
1586
Jeff Sharkey1b861272011-05-22 00:34:52 -07001587 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001588 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001589 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1590
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001591 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001592 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001593 normalizePoliciesLocked(policies);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001594 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001595 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001596 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001597 writePolicyLocked();
1598 }
1599 }
1600
Dianne Hackborn497175b2014-07-01 12:56:08 -07001601 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001602 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001603 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1604 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001605 }
1606
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001607 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001608 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001609 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001610 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001611
Svet Ganov16a16892015-04-16 10:32:04 -07001612 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1613 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1614 return new NetworkPolicy[0];
1615 }
1616
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001617 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001618 final int size = mNetworkPolicy.size();
1619 final NetworkPolicy[] policies = new NetworkPolicy[size];
1620 for (int i = 0; i < size; i++) {
1621 policies[i] = mNetworkPolicy.valueAt(i);
1622 }
1623 return policies;
1624 }
1625 }
1626
1627 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001628 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001629 }
1630
1631 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1632 final TelephonyManager tele = TelephonyManager.from(mContext);
1633 final String[] merged = tele.getMergedSubscriberIds();
1634
1635 mNetworkPolicy.clear();
1636 for (NetworkPolicy policy : policies) {
1637 // When two normalized templates conflict, prefer the most
1638 // restrictive policy
1639 policy.template = NetworkTemplate.normalize(policy.template, merged);
1640 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1641 if (existing == null || existing.compareTo(policy) > 0) {
1642 if (existing != null) {
1643 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1644 }
1645 mNetworkPolicy.put(policy.template, policy);
1646 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001647 }
1648 }
1649
1650 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001651 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001652 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001653
1654 final long token = Binder.clearCallingIdentity();
1655 try {
1656 performSnooze(template, TYPE_LIMIT);
1657 } finally {
1658 Binder.restoreCallingIdentity(token);
1659 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001660 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001661
Dianne Hackborn497175b2014-07-01 12:56:08 -07001662 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001663 maybeRefreshTrustedTime();
1664 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001665 synchronized (mRulesLock) {
1666 // find and snooze local policy that matches
1667 final NetworkPolicy policy = mNetworkPolicy.get(template);
1668 if (policy == null) {
1669 throw new IllegalArgumentException("unable to find policy for " + template);
1670 }
1671
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001672 switch (type) {
1673 case TYPE_WARNING:
1674 policy.lastWarningSnooze = currentTime;
1675 break;
1676 case TYPE_LIMIT:
1677 policy.lastLimitSnooze = currentTime;
1678 break;
1679 default:
1680 throw new IllegalArgumentException("unexpected type");
1681 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001682
Jeff Sharkey32566012014-12-02 18:30:14 -08001683 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001684 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001685 updateNetworkRulesLocked();
1686 updateNotificationsLocked();
1687 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001688 }
1689 }
1690
1691 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001692 public void setRestrictBackground(boolean restrictBackground) {
1693 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1694
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001695 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001696 synchronized (mRulesLock) {
1697 mRestrictBackground = restrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001698 updateRulesForGlobalChangeLocked(false);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001699 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001700 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001701 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001702
1703 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1704 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001705 }
1706
1707 @Override
1708 public boolean getRestrictBackground() {
1709 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1710
1711 synchronized (mRulesLock) {
1712 return mRestrictBackground;
1713 }
1714 }
1715
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001716 @Override
1717 public void setDeviceIdleMode(boolean enabled) {
1718 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1719
1720 synchronized (mRulesLock) {
1721 if (mDeviceIdleMode != enabled) {
1722 mDeviceIdleMode = enabled;
1723 if (mSystemReady) {
1724 updateRulesForGlobalChangeLocked(true);
1725 }
1726 }
1727 }
1728 }
1729
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001730 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001731 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1732 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001733 if (policy.template.matches(ident)) {
1734 return policy;
1735 }
1736 }
1737 return null;
1738 }
1739
1740 @Override
1741 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1742 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1743
1744 // only returns usage summary, so we don't require caller to have
1745 // READ_NETWORK_USAGE_HISTORY.
1746 final long token = Binder.clearCallingIdentity();
1747 try {
1748 return getNetworkQuotaInfoUnchecked(state);
1749 } finally {
1750 Binder.restoreCallingIdentity(token);
1751 }
1752 }
1753
1754 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1755 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1756
1757 final NetworkPolicy policy;
1758 synchronized (mRulesLock) {
1759 policy = findPolicyForNetworkLocked(ident);
1760 }
1761
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001762 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001763 // missing policy means we can't derive useful quota info
1764 return null;
1765 }
1766
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001767 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001768
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001769 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001770 final long start = computeLastCycleBoundary(currentTime, policy);
1771 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001772 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001773
1774 // report soft and hard limits under policy
1775 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1776 : NetworkQuotaInfo.NO_LIMIT;
1777 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1778 : NetworkQuotaInfo.NO_LIMIT;
1779
1780 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1781 }
1782
Jeff Sharkey46645002011-07-27 21:11:21 -07001783 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001784 public boolean isNetworkMetered(NetworkState state) {
1785 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1786
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001787 // roaming networks are always considered metered
1788 if (ident.getRoaming()) {
1789 return true;
1790 }
1791
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001792 final NetworkPolicy policy;
1793 synchronized (mRulesLock) {
1794 policy = findPolicyForNetworkLocked(ident);
1795 }
1796
1797 if (policy != null) {
1798 return policy.metered;
1799 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001800 final int type = state.networkInfo.getType();
1801 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1802 return true;
1803 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001804 return false;
1805 }
1806 }
1807
1808 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001809 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001810 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001811
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001812 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1813
Dianne Hackborn497175b2014-07-01 12:56:08 -07001814 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001815 for (String arg : args) {
1816 argSet.add(arg);
1817 }
1818
Jeff Sharkey1b861272011-05-22 00:34:52 -07001819 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001820 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001821 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1822 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001823 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001824
Jeff Sharkey32566012014-12-02 18:30:14 -08001825 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001826 updateNetworkEnabledLocked();
1827 updateNetworkRulesLocked();
1828 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001829 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001830
1831 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001832 return;
1833 }
1834
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001835 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07001836 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001837 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001838 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001839 fout.print("Current foreground state: "); fout.println(mCurForegroundState);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001840 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001841 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001842 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1843 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001844 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001845 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001846
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001847 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
1848
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001849 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001850 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001851 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001852 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001853 final int uid = mUidPolicy.keyAt(i);
1854 final int policy = mUidPolicy.valueAt(i);
1855 fout.print("UID=");
1856 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001857 fout.print(" policy=");
1858 dumpPolicy(fout, policy);
1859 fout.println();
1860 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001861 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001862
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001863 size = mPowerSaveWhitelistAppIds.size();
1864 if (size > 0) {
1865 fout.println("Power save whitelist app ids:");
1866 fout.increaseIndent();
1867 for (int i = 0; i < size; i++) {
1868 fout.print("UID=");
1869 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
1870 fout.print(": ");
1871 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
1872 fout.println();
1873 }
1874 fout.decreaseIndent();
1875 }
1876
Jeff Sharkey1b861272011-05-22 00:34:52 -07001877 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07001878 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001879 collectKeys(mUidRules, knownUids);
1880
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001881 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001882 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001883 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001884 for (int i = 0; i < size; i++) {
1885 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001886 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001887 fout.print(uid);
1888
Dianne Hackborn497175b2014-07-01 12:56:08 -07001889 int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1890 fout.print(" state=");
1891 fout.print(state);
1892 fout.print(state <= mCurForegroundState ? " (fg)" : " (bg)");
1893
1894 fout.print(" pids=");
1895 final int foregroundIndex = mUidPidState.indexOfKey(uid);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001896 if (foregroundIndex < 0) {
1897 fout.print("UNKNOWN");
1898 } else {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001899 dumpSparseIntArray(fout, mUidPidState.valueAt(foregroundIndex));
Jeff Sharkey1b861272011-05-22 00:34:52 -07001900 }
1901
1902 fout.print(" rules=");
1903 final int rulesIndex = mUidRules.indexOfKey(uid);
1904 if (rulesIndex < 0) {
1905 fout.print("UNKNOWN");
1906 } else {
1907 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1908 }
1909
1910 fout.println();
1911 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001912 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001913 }
1914 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001915
1916 @Override
1917 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001918 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1919
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001920 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001921 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001922 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001923 }
1924
Dianne Hackborn497175b2014-07-01 12:56:08 -07001925 boolean isUidForegroundLocked(int uid) {
1926 // only really in foreground when screen is also on
1927 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
1928 <= mCurForegroundState;
1929 }
1930
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001931 /**
Dianne Hackborn497175b2014-07-01 12:56:08 -07001932 * Process state of PID changed; recompute state at UID level. If
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001933 * changed, will trigger {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001934 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001935 void computeUidStateLocked(int uid) {
1936 final SparseIntArray pidState = mUidPidState.get(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001937
1938 // current pid is dropping foreground; examine other pids
Dianne Hackborn497175b2014-07-01 12:56:08 -07001939 int uidState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
1940 if (pidState != null) {
1941 final int size = pidState.size();
1942 for (int i = 0; i < size; i++) {
1943 final int state = pidState.valueAt(i);
1944 if (state < uidState) {
1945 uidState = state;
1946 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001947 }
1948 }
1949
Dianne Hackborn497175b2014-07-01 12:56:08 -07001950 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1951 if (oldUidState != uidState) {
1952 // state changed, push updated rules
1953 mUidState.put(uid, uidState);
1954 final boolean oldForeground = oldUidState <= mCurForegroundState;
1955 final boolean newForeground = uidState <= mCurForegroundState;
1956 if (oldForeground != newForeground) {
1957 updateRulesForUidLocked(uid);
1958 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001959 }
1960 }
1961
Jeff Sharkeya4620792011-05-20 15:29:23 -07001962 private void updateScreenOn() {
1963 synchronized (mRulesLock) {
1964 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07001965 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001966 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001967 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07001968 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001969 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001970 }
1971 }
1972
1973 /**
1974 * Update rules that might be changed by {@link #mScreenOn} value.
1975 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001976 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07001977 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07001978 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001979 for (int i = 0; i < size; i++) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001980 if (mUidState.valueAt(i) <= mCurForegroundState) {
1981 final int uid = mUidState.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001982 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001983 }
1984 }
1985 }
1986
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001987 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001988 * Update rules that might be changed by {@link #mRestrictBackground},
1989 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001990 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001991 void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001992 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001993 final UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1994
Dianne Hackborn497175b2014-07-01 12:56:08 -07001995 // If we are in restrict power mode, we allow all important apps
1996 // to have data access. Otherwise, we restrict data access to only
1997 // the top apps.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001998 mCurForegroundState = (!mRestrictBackground && (mRestrictPower || mDeviceIdleMode))
Dianne Hackborn497175b2014-07-01 12:56:08 -07001999 ? ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND
2000 : ActivityManager.PROCESS_STATE_TOP;
2001
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002002 // update rules for all installed applications
2003 final List<UserInfo> users = um.getUsers();
2004 final List<ApplicationInfo> apps = pm.getInstalledApplications(
2005 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
2006
2007 for (UserInfo user : users) {
2008 for (ApplicationInfo app : apps) {
2009 final int uid = UserHandle.getUid(user.id, app.uid);
2010 updateRulesForUidLocked(uid);
2011 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002012 }
2013
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002014 // limit data usage for some internal system services
2015 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
2016 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002017
2018 // If the set of restricted networks may have changed, re-evaluate those.
2019 if (restrictedNetworksChanged) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002020 normalizePoliciesLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002021 updateNetworkRulesLocked();
2022 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002023 }
2024
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002025 private static boolean isUidValidForRules(int uid) {
2026 // allow rules on specific system services, and any apps
2027 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002028 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002029 return true;
2030 }
2031
2032 return false;
2033 }
2034
Dianne Hackborn497175b2014-07-01 12:56:08 -07002035 void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002036 if (!isUidValidForRules(uid)) return;
2037
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002038 // quick check: if this uid doesn't have INTERNET permission, it doesn't have
2039 // network access anyway, so it is a waste to mess with it here.
2040 final IPackageManager ipm = AppGlobals.getPackageManager();
2041 try {
2042 if (ipm.checkUidPermission(Manifest.permission.INTERNET, uid)
2043 != PackageManager.PERMISSION_GRANTED) {
2044 return;
2045 }
2046 } catch (RemoteException e) {
2047 }
2048
Dianne Hackborn497175b2014-07-01 12:56:08 -07002049 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2050 final boolean uidForeground = isUidForegroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002051
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002052 // derive active rules based on policy and active state
2053 int uidRules = RULE_ALLOW_ALL;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002054 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002055 // uid in background, and policy says to block metered data
2056 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002057 } else if (mRestrictBackground) {
2058 if (!uidForeground) {
2059 // uid in background, and global background disabled
2060 uidRules = RULE_REJECT_METERED;
2061 }
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002062 } else if (mRestrictPower || mDeviceIdleMode) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002063 final boolean whitelisted = mPowerSaveWhitelistAppIds.get(UserHandle.getAppId(uid));
2064 if (!whitelisted && !uidForeground
2065 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
2066 // uid is in background, restrict power use mode is on (so we want to
2067 // restrict all background network access), and this uid is not on the
2068 // white list of those allowed background access.
2069 uidRules = RULE_REJECT_METERED;
2070 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002071 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002072
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002073 // TODO: only dispatch when rules actually change
2074
Jeff Sharkey350083e2011-06-29 10:45:16 -07002075 if (uidRules == RULE_ALLOW_ALL) {
2076 mUidRules.delete(uid);
2077 } else {
2078 mUidRules.put(uid, uidRules);
2079 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002080
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002081 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Ashish Sharma50fd36d2011-06-15 19:34:53 -07002082 setUidNetworkRules(uid, rejectMetered);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002083
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002084 // dispatch changed rule to existing listeners
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002085 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002086
2087 try {
2088 // adjust stats accounting based on foreground status
2089 mNetworkStats.setUidForeground(uid, uidForeground);
2090 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002091 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002092 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002093 }
2094
2095 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002096 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002097 public boolean handleMessage(Message msg) {
2098 switch (msg.what) {
2099 case MSG_RULES_CHANGED: {
2100 final int uid = msg.arg1;
2101 final int uidRules = msg.arg2;
2102 final int length = mListeners.beginBroadcast();
2103 for (int i = 0; i < length; i++) {
2104 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2105 if (listener != null) {
2106 try {
2107 listener.onUidRulesChanged(uid, uidRules);
2108 } catch (RemoteException e) {
2109 }
2110 }
2111 }
2112 mListeners.finishBroadcast();
2113 return true;
2114 }
2115 case MSG_METERED_IFACES_CHANGED: {
2116 final String[] meteredIfaces = (String[]) msg.obj;
2117 final int length = mListeners.beginBroadcast();
2118 for (int i = 0; i < length; i++) {
2119 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2120 if (listener != null) {
2121 try {
2122 listener.onMeteredIfacesChanged(meteredIfaces);
2123 } catch (RemoteException e) {
2124 }
2125 }
2126 }
2127 mListeners.finishBroadcast();
2128 return true;
2129 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002130 case MSG_LIMIT_REACHED: {
2131 final String iface = (String) msg.obj;
2132
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002133 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002134 synchronized (mRulesLock) {
2135 if (mMeteredIfaces.contains(iface)) {
2136 try {
2137 // force stats update to make sure we have
2138 // numbers that caused alert to trigger.
2139 mNetworkStats.forceUpdate();
2140 } catch (RemoteException e) {
2141 // ignored; service lives in system_server
2142 }
2143
2144 updateNetworkEnabledLocked();
2145 updateNotificationsLocked();
2146 }
2147 }
2148 return true;
2149 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002150 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2151 final boolean restrictBackground = msg.arg1 != 0;
2152 final int length = mListeners.beginBroadcast();
2153 for (int i = 0; i < length; i++) {
2154 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2155 if (listener != null) {
2156 try {
2157 listener.onRestrictBackgroundChanged(restrictBackground);
2158 } catch (RemoteException e) {
2159 }
2160 }
2161 }
2162 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002163 return true;
2164 }
2165 case MSG_ADVISE_PERSIST_THRESHOLD: {
2166 final long lowestRule = (Long) msg.obj;
2167 try {
2168 // make sure stats are recorded frequently enough; we aim
2169 // for 2MB threshold for 2GB/month rules.
2170 final long persistThreshold = lowestRule / 1000;
2171 mNetworkStats.advisePersistThreshold(persistThreshold);
2172 } catch (RemoteException e) {
2173 // ignored; service lives in system_server
2174 }
2175 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002176 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002177 case MSG_SCREEN_ON_CHANGED: {
2178 updateScreenOn();
2179 return true;
2180 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002181 default: {
2182 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002183 }
2184 }
2185 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002186 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002187
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002188 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002189 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002190 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002191 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002192 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002193 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002194 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002195 }
2196 }
2197
2198 private void removeInterfaceQuota(String iface) {
2199 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002200 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002201 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002202 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002203 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002204 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002205 }
2206 }
2207
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002208 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2209 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002210 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002211 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002212 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002213 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002214 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002215 }
2216 }
2217
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002218 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2219 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002220 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002221 } catch (RuntimeException e) {
2222 Slog.w(TAG, "problem reading network stats: " + e);
2223 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002224 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002225 // ignored; service lives in system_server
2226 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002227 }
2228 }
2229
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002230 private boolean isBandwidthControlEnabled() {
2231 final long token = Binder.clearCallingIdentity();
2232 try {
2233 return mNetworkManager.isBandwidthControlEnabled();
2234 } catch (RemoteException e) {
2235 // ignored; service lives in system_server
2236 return false;
2237 } finally {
2238 Binder.restoreCallingIdentity(token);
2239 }
2240 }
2241
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002242 /**
2243 * Try refreshing {@link #mTime} when stale.
2244 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002245 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002246 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002247 mTime.forceRefresh();
2248 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002249 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002250
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002251 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002252 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2253 }
2254
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002255 private static Intent buildAllowBackgroundDataIntent() {
2256 return new Intent(ACTION_ALLOW_BACKGROUND);
2257 }
2258
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002259 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2260 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2261 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2262 return intent;
2263 }
2264
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002265 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2266 final Intent intent = new Intent();
2267 intent.setComponent(new ComponentName(
2268 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2269 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2270 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2271 return intent;
2272 }
2273
2274 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2275 final Intent intent = new Intent();
2276 intent.setComponent(new ComponentName(
2277 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2278 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2279 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2280 return intent;
2281 }
2282
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002283 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002284 public void addIdleHandler(IdleHandler handler) {
2285 mHandler.getLooper().getQueue().addIdleHandler(handler);
2286 }
2287
Jeff Sharkey1b861272011-05-22 00:34:52 -07002288 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2289 final int size = source.size();
2290 for (int i = 0; i < size; i++) {
2291 target.put(source.keyAt(i), true);
2292 }
2293 }
2294
Dianne Hackborn497175b2014-07-01 12:56:08 -07002295 private static void dumpSparseIntArray(PrintWriter fout, SparseIntArray value) {
Jeff Sharkey1b861272011-05-22 00:34:52 -07002296 fout.print("[");
2297 final int size = value.size();
2298 for (int i = 0; i < size; i++) {
2299 fout.print(value.keyAt(i) + "=" + value.valueAt(i));
2300 if (i < size - 1) fout.print(",");
2301 }
2302 fout.print("]");
2303 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07002304
2305 @Override
2306 public void factoryReset(String subscriber) {
2307 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2308
2309 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07002310 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07002311 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
2312 for (NetworkPolicy policy : policies) {
2313 if (policy.template.equals(template)) {
2314 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2315 policy.inferred = false;
2316 policy.clearSnooze();
2317 }
2318 }
2319 setNetworkPolicies(policies);
2320
2321 // Turn restrict background data off
2322 setRestrictBackground(false);
2323
2324 // Remove app's "restrict background data" flag
2325 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
2326 setUidPolicy(uid, POLICY_NONE);
2327 }
2328 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002329}