blob: 792d4ba08b390a620b877fa0c7e6d3816a0a1724 [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;
Amith Yamasani15e472352015-04-24 19:06:07 -070039import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
40import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -070041import static android.net.NetworkPolicyManager.POLICY_ALLOW_BACKGROUND_BATTERY_SAVE;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070042import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070043import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070044import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070045import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Amith Yamasani15e472352015-04-24 19:06:07 -070046import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070047import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Jeff Sharkey1b861272011-05-22 00:34:52 -070048import static android.net.NetworkPolicyManager.dumpPolicy;
49import static android.net.NetworkPolicyManager.dumpRules;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070050import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
51import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070052import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
53import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070054import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080055import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070056import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
57import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
58import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
59import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
60import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
61import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
62import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070063import static android.text.format.DateUtils.DAY_IN_MILLIS;
Jeff Sharkey854b2b12012-04-13 16:03:40 -070064import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070065import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070066import static com.android.internal.util.XmlUtils.readBooleanAttribute;
67import static com.android.internal.util.XmlUtils.readIntAttribute;
68import static com.android.internal.util.XmlUtils.readLongAttribute;
69import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
70import static com.android.internal.util.XmlUtils.writeIntAttribute;
71import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070072import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070073import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070074import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
75import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070076
Dianne Hackborn88e98df2015-03-23 13:29:14 -070077import android.Manifest;
Dianne Hackborn497175b2014-07-01 12:56:08 -070078import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070079import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070080import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070081import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070082import android.app.INotificationManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070083import android.app.IProcessObserver;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070084import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070085import android.app.Notification;
86import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -070087import android.app.usage.UsageStatsManagerInternal;
88import android.app.usage.UsageStatsManagerInternal.AppIdleStateChangeListener;
Jeff Sharkeya4620792011-05-20 15:29:23 -070089import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070090import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070091import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070092import android.content.Intent;
93import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070094import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070095import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070096import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -070097import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -070098import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -070099import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700100import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700101import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700102import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700103import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700104import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700105import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700106import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700107import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700108import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700109import android.net.NetworkPolicy;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700110import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700111import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700112import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700113import android.net.wifi.WifiConfiguration;
114import android.net.wifi.WifiInfo;
115import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700116import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700117import android.os.Environment;
118import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700119import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700120import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700121import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700122import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700123import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700124import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700125import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700126import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700127import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700128import android.os.RemoteException;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700129import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700130import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700131import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700132import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800133import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700134import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700135import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700136import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700137import android.util.ArrayMap;
138import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700139import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700140import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700141import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700142import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700143import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700144import android.util.SparseArray;
145import android.util.SparseBooleanArray;
146import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700147import android.util.TrustedTime;
148import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700149
Jeff Sharkey32566012014-12-02 18:30:14 -0800150import libcore.io.IoUtils;
151
Jeff Sharkey497e4432011-06-14 17:27:29 -0700152import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800153import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey32566012014-12-02 18:30:14 -0800154import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700155import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700156import com.android.internal.util.IndentingPrintWriter;
Amith Yamasani15e472352015-04-24 19:06:07 -0700157import com.android.server.DeviceIdleController;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700158import com.android.server.LocalServices;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700159import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700160
161import org.xmlpull.v1.XmlPullParser;
162import org.xmlpull.v1.XmlPullParserException;
163import org.xmlpull.v1.XmlSerializer;
164
165import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700166import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700167import java.io.FileInputStream;
168import java.io.FileNotFoundException;
169import java.io.FileOutputStream;
170import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700171import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100172import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700173import java.util.ArrayList;
174import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700175import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700176
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700177/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700178 * Service that maintains low-level network policy rules, using
179 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700180 * <p>
181 * Derives active rules by combining a given policy with other system status,
182 * and delivers to listeners, such as {@link ConnectivityManager}, for
183 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700184 */
Amith Yamasani15e472352015-04-24 19:06:07 -0700185public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub
186 implements AppIdleStateChangeListener {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700187 private static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700188 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700189 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700190
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700191 private static final int VERSION_INIT = 1;
192 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700193 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800194 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800195 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800196 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700197 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700198 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700199 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700200 private static final int VERSION_SWITCH_UID = 10;
201 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700202
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800203 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700204 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800205 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700206 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800207 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700208 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700209
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700210 private static final String TAG_POLICY_LIST = "policy-list";
211 private static final String TAG_NETWORK_POLICY = "network-policy";
212 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700213 private static final String TAG_APP_POLICY = "app-policy";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700214
215 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700216 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700217 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
218 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700219 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700220 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800221 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700222 private static final String ATTR_WARNING_BYTES = "warningBytes";
223 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700224 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800225 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
226 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800227 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700228 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700229 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700230 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700231 private static final String ATTR_POLICY = "policy";
232
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700233 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
234
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800235 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800236 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800237 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800238 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700239
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700240 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
241
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700242 private static final int MSG_RULES_CHANGED = 1;
243 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800244 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800245 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700246 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700247 private static final int MSG_SCREEN_ON_CHANGED = 8;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700248
Jeff Sharkey75279902011-05-24 18:39:45 -0700249 private final Context mContext;
250 private final IActivityManager mActivityManager;
251 private final IPowerManager mPowerManager;
252 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700253 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700254 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700255 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700256 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700257
258 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700259 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700260 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700261 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700262
Dianne Hackborn497175b2014-07-01 12:56:08 -0700263 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700264
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700265 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700266 volatile boolean mScreenOn;
267 volatile boolean mRestrictBackground;
268 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700269 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700270
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700271 private final boolean mSuppressDefaultPolicy;
272
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700273 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800274 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700275 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800276 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700277
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700278 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700279 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700280 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800281 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700282
Jeff Sharkey32566012014-12-02 18:30:14 -0800283 /**
284 * UIDs that have been white-listed to always be able to have network access
285 * in power save mode.
286 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700287 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700288
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700289 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800290 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700291 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800292 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700293
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700294 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700295 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700296
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700297 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800298 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700299
300 /** The current maximum process state that we are considering to be foreground. */
301 private int mCurForegroundState = ActivityManager.PROCESS_STATE_TOP;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700302
Jeff Sharkey32566012014-12-02 18:30:14 -0800303 private final RemoteCallbackList<INetworkPolicyListener>
304 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700305
Dianne Hackborn497175b2014-07-01 12:56:08 -0700306 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700307
308 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700309
Svet Ganov16a16892015-04-16 10:32:04 -0700310 private final AppOpsManager mAppOps;
311
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700312 // TODO: keep whitelist of system-critical services that should never have
313 // rules enforced, such as system, phone, and radio UIDs.
314
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700315 // TODO: migrate notifications to SystemUI
316
Jeff Sharkey75279902011-05-24 18:39:45 -0700317 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700318 IPowerManager powerManager, INetworkStatsService networkStats,
319 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700320 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700321 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700322 }
323
324 private static File getSystemDir() {
325 return new File(Environment.getDataDirectory(), "system");
326 }
327
328 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700329 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700330 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
331 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700332 mContext = checkNotNull(context, "missing context");
333 mActivityManager = checkNotNull(activityManager, "missing activityManager");
334 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700335 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700336 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700337 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
338 DeviceIdleController.SERVICE_NAME));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700339 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700340 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700341
Amith Yamasani450a16b2013-09-18 16:28:50 -0700342 HandlerThread thread = new HandlerThread(TAG);
343 thread.start();
344 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700345
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700346 mSuppressDefaultPolicy = suppressDefaultPolicy;
347
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700348 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700349
350 mAppOps = context.getSystemService(AppOpsManager.class);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700351 }
352
353 public void bindConnectivityManager(IConnectivityManager connManager) {
354 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700355 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700356
Jeff Sharkey497e4432011-06-14 17:27:29 -0700357 public void bindNotificationManager(INotificationManager notifManager) {
358 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
359 }
360
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700361 void updatePowerSaveWhitelistLocked() {
362 try {
363 final int[] whitelist = mDeviceIdleController.getAppIdWhitelist();
364 mPowerSaveWhitelistAppIds.clear();
365 if (whitelist != null) {
366 for (int uid : whitelist) {
367 mPowerSaveWhitelistAppIds.put(uid, true);
368 }
369 }
370 } catch (RemoteException e) {
371 }
372 }
373
Jeff Sharkeya4620792011-05-20 15:29:23 -0700374 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700375 if (!isBandwidthControlEnabled()) {
376 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
377 return;
378 }
379
Amith Yamasani15e472352015-04-24 19:06:07 -0700380 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
381
382 final PackageManager pm = mContext.getPackageManager();
383
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700384 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700385 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700386 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
387 mPowerManagerInternal.registerLowPowerModeObserver(
388 new PowerManagerInternal.LowPowerModeListener() {
389 @Override
390 public void onLowPowerModeChanged(boolean enabled) {
391 synchronized (mRulesLock) {
392 if (mRestrictPower != enabled) {
393 mRestrictPower = enabled;
394 updateRulesForGlobalChangeLocked(true);
395 }
396 }
397 }
398 });
399 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700400 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700401
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700402 // read policy from disk
403 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700404
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700405 if (mRestrictBackground || mRestrictPower || mDeviceIdleMode) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700406 updateRulesForGlobalChangeLocked(true);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700407 updateNotificationsLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700408 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700409 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700410
Jeff Sharkeya4620792011-05-20 15:29:23 -0700411 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700412
Jeff Sharkeya4620792011-05-20 15:29:23 -0700413 try {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700414 mActivityManager.registerUidObserver(mUidObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700415 mNetworkManager.registerObserver(mAlertObserver);
416 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700417 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700418 }
419
Jeff Sharkeya4620792011-05-20 15:29:23 -0700420 // TODO: traverse existing processes to know foreground state, or have
421 // activitymanager dispatch current state when new observer attached.
422
423 final IntentFilter screenFilter = new IntentFilter();
424 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
425 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700426 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700427
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700428 // listen for changes to power save whitelist
429 final IntentFilter whitelistFilter = new IntentFilter(
430 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
431 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
432
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700433 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900434 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700435 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
436
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700437 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700438 final IntentFilter packageFilter = new IntentFilter();
439 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700440 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700441 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700442
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700443 // listen for UID changes to update policy
444 mContext.registerReceiver(
445 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
446
447 // listen for user changes to update policy
448 final IntentFilter userFilter = new IntentFilter();
449 userFilter.addAction(ACTION_USER_ADDED);
450 userFilter.addAction(ACTION_USER_REMOVED);
451 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
452
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700453 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700454 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
455 mContext.registerReceiver(
456 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
457
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700458 // listen for restrict background changes from notifications
459 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
460 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
461
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800462 // listen for snooze warning from notifications
463 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
464 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
465 MANAGE_NETWORK_POLICY, mHandler);
466
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700467 // listen for configured wifi networks to be removed
468 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700469 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700470
471 // listen for wifi state changes to catch metered hint
472 final IntentFilter wifiStateFilter = new IntentFilter(
473 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700474 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700475
Amith Yamasani15e472352015-04-24 19:06:07 -0700476 mUsageStats.addAppIdleStateChangeListener(this);
477
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700478 }
479
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700480 private IUidObserver mUidObserver = new IUidObserver.Stub() {
481 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700482 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700483 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700484 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700485 }
486
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700487 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700488 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700489 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700490 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700491 }
492 };
493
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700494 private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
495 @Override
496 public void onReceive(Context context, Intent intent) {
497 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
498 synchronized (mRulesLock) {
499 updatePowerSaveWhitelistLocked();
500 updateRulesForGlobalChangeLocked(false);
501 }
502 }
503 };
504
Jeff Sharkeya4620792011-05-20 15:29:23 -0700505 private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
506 @Override
507 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800508 // screen-related broadcasts are protected by system, no need
509 // for permissions check.
510 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700511 }
512 };
513
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700514 private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700515 @Override
516 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700517 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700518
519 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700520 final int uid = intent.getIntExtra(EXTRA_UID, -1);
521 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700522
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700523 if (ACTION_PACKAGE_ADDED.equals(action)) {
524 // update rules for UID, since it might be subject to
525 // global background data policy
526 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
527 synchronized (mRulesLock) {
528 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700529 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700530 }
531 }
532 };
533
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700534 private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
535 @Override
536 public void onReceive(Context context, Intent intent) {
537 // on background handler thread, and UID_REMOVED is protected
538
539 final int uid = intent.getIntExtra(EXTRA_UID, -1);
540 if (uid == -1) return;
541
542 // remove any policy and update rules to clean up
543 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
544 synchronized (mRulesLock) {
545 mUidPolicy.delete(uid);
546 updateRulesForUidLocked(uid);
547 writePolicyLocked();
548 }
549 }
550 };
551
552 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
553 @Override
554 public void onReceive(Context context, Intent intent) {
555 // on background handler thread, and USER_ADDED and USER_REMOVED
556 // broadcasts are protected
557
558 final String action = intent.getAction();
559 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
560 if (userId == -1) return;
561
Amith Yamasani15e472352015-04-24 19:06:07 -0700562 switch (action) {
563 case ACTION_USER_REMOVED:
564 case ACTION_USER_ADDED:
565 synchronized (mRulesLock) {
566 // Remove any policies for given user; both cleaning up after a
567 // USER_REMOVED, and one last sanity check during USER_ADDED
568 removePoliciesForUserLocked(userId);
569 // Update global restrict for new user
570 updateRulesForGlobalChangeLocked(true);
571 }
572 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700573 }
574 }
575 };
576
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700577 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700578 * Receiver that watches for {@link INetworkStatsService} updates, which we
579 * use to check against {@link NetworkPolicy#warningBytes}.
580 */
581 private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
582 @Override
583 public void onReceive(Context context, Intent intent) {
584 // on background handler thread, and verified
585 // READ_NETWORK_USAGE_HISTORY permission above.
586
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800587 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700588 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700589 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700590 updateNotificationsLocked();
591 }
592 }
593 };
594
595 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700596 * Receiver that watches for {@link Notification} control of
597 * {@link #mRestrictBackground}.
598 */
599 private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
600 @Override
601 public void onReceive(Context context, Intent intent) {
602 // on background handler thread, and verified MANAGE_NETWORK_POLICY
603 // permission above.
604
605 setRestrictBackground(false);
606 }
607 };
608
609 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800610 * Receiver that watches for {@link Notification} control of
611 * {@link NetworkPolicy#lastWarningSnooze}.
612 */
613 private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
614 @Override
615 public void onReceive(Context context, Intent intent) {
616 // on background handler thread, and verified MANAGE_NETWORK_POLICY
617 // permission above.
618
619 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
620 performSnooze(template, TYPE_WARNING);
621 }
622 };
623
624 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700625 * Receiver that watches for {@link WifiConfiguration} to be changed.
626 */
627 private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
628 @Override
629 public void onReceive(Context context, Intent intent) {
630 // on background handler thread, and verified CONNECTIVITY_INTERNAL
631 // permission above.
632
633 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
634 if (reason == CHANGE_REASON_REMOVED) {
635 final WifiConfiguration config = intent.getParcelableExtra(
636 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700637 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800638 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700639 synchronized (mRulesLock) {
640 if (mNetworkPolicy.containsKey(template)) {
641 mNetworkPolicy.remove(template);
642 writePolicyLocked();
643 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700644 }
645 }
646 }
647 }
648 };
649
650 /**
651 * Receiver that watches {@link WifiInfo} state changes to infer metered
652 * state. Ignores hints when policy is user-defined.
653 */
654 private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
655 @Override
656 public void onReceive(Context context, Intent intent) {
657 // on background handler thread, and verified CONNECTIVITY_INTERNAL
658 // permission above.
659
660 // ignore when not connected
661 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
662 if (!netInfo.isConnected()) return;
663
664 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
665 final boolean meteredHint = info.getMeteredHint();
666
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800667 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700668 synchronized (mRulesLock) {
669 NetworkPolicy policy = mNetworkPolicy.get(template);
670 if (policy == null && meteredHint) {
671 // policy doesn't exist, and AP is hinting that it's
672 // metered: create an inferred policy.
673 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
674 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
675 meteredHint, true);
676 addNetworkPolicyLocked(policy);
677
678 } else if (policy != null && policy.inferred) {
679 // policy exists, and was inferred: update its current
680 // metered state.
681 policy.metered = meteredHint;
682
683 // since this is inferred for each wifi session, just update
684 // rules without persisting.
685 updateNetworkRulesLocked();
686 }
687 }
688 }
689 };
690
691 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700692 * Observer that watches for {@link INetworkManagementService} alerts.
693 */
Jeff Sharkey216c1812012-08-05 14:29:23 -0700694 private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700695 @Override
696 public void limitReached(String limitName, String iface) {
697 // only someone like NMS should be calling us
698 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
699
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800700 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
701 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700702 }
703 }
704 };
705
706 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700707 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
708 * to show visible notifications as needed.
709 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700710 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700711 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
712
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700713 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700714 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700715 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700716
717 // TODO: when switching to kernel notifications, compute next future
718 // cycle boundary to recompute notifications.
719
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700720 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800721 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700722 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
723 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700724 // ignore policies that aren't relevant to user
725 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700726 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700727
Jeff Sharkey497e4432011-06-14 17:27:29 -0700728 final long start = computeLastCycleBoundary(currentTime, policy);
729 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700730 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700731
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700732 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800733 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700734 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
735 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700736 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
737 notifyOverLimitLocked(policy.template);
738 }
739
Jeff Sharkey497e4432011-06-14 17:27:29 -0700740 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700741 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700742
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800743 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700744 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700745 }
746 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700747 }
748
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700749 // ongoing notification when restricting background data
750 if (mRestrictBackground) {
751 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700752 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700753
754 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700755 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
756 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700757 if (!mActiveNotifs.contains(tag)) {
758 cancelNotification(tag);
759 }
760 }
761 }
762
763 /**
764 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700765 * current device state, such as when
766 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
767 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700768 */
769 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800770 if (template.isMatchRuleMobile()) {
771 final TelephonyManager tele = TelephonyManager.from(mContext);
772 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700773
Jeff Sharkey32566012014-12-02 18:30:14 -0800774 // Mobile template is relevant when any active subscriber matches
775 final int[] subIds = sub.getActiveSubscriptionIdList();
776 for (int subId : subIds) {
777 final String subscriberId = tele.getSubscriberId(subId);
778 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
779 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
780 if (template.matches(probeIdent)) {
781 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700782 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800783 }
784 return false;
785 } else {
786 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700787 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700788 }
789
790 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700791 * Notify that given {@link NetworkTemplate} is over
792 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
793 */
794 private void notifyOverLimitLocked(NetworkTemplate template) {
795 if (!mOverLimitNotified.contains(template)) {
796 mContext.startActivity(buildNetworkOverLimitIntent(template));
797 mOverLimitNotified.add(template);
798 }
799 }
800
801 private void notifyUnderLimitLocked(NetworkTemplate template) {
802 mOverLimitNotified.remove(template);
803 }
804
805 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700806 * Build unique tag that identifies an active {@link NetworkPolicy}
807 * notification of a specific type, like {@link #TYPE_LIMIT}.
808 */
809 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700810 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700811 }
812
813 /**
814 * Show notification for combined {@link NetworkPolicy} and specific type,
815 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
816 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700817 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700818 final String tag = buildNotificationTag(policy, type);
819 final Notification.Builder builder = new Notification.Builder(mContext);
820 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800821 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700822 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200823 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700824
825 final Resources res = mContext.getResources();
826 switch (type) {
827 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700828 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700829 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700830
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700831 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700832 builder.setTicker(title);
833 builder.setContentTitle(title);
834 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700835
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800836 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
837 builder.setDeleteIntent(PendingIntent.getBroadcast(
838 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
839
840 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700841 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800842 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
843
Jeff Sharkey497e4432011-06-14 17:27:29 -0700844 break;
845 }
846 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700847 final CharSequence body = res.getText(R.string.data_usage_limit_body);
848
849 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -0400850 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700851 switch (policy.template.getMatchRule()) {
852 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700853 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700854 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700855 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700856 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700857 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700858 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700859 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700860 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700861 case MATCH_WIFI:
862 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -0400863 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700864 break;
865 default:
866 title = null;
867 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700868 }
869
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800870 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -0400871 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700872 builder.setTicker(title);
873 builder.setContentTitle(title);
874 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700875
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700876 final Intent intent = buildNetworkOverLimitIntent(policy.template);
877 builder.setContentIntent(PendingIntent.getActivity(
878 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
879 break;
880 }
881 case TYPE_LIMIT_SNOOZED: {
882 final long overBytes = totalBytes - policy.limitBytes;
883 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
884 Formatter.formatFileSize(mContext, overBytes));
885
886 final CharSequence title;
887 switch (policy.template.getMatchRule()) {
888 case MATCH_MOBILE_3G_LOWER:
889 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
890 break;
891 case MATCH_MOBILE_4G:
892 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
893 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700894 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700895 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
896 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700897 case MATCH_WIFI:
898 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
899 break;
900 default:
901 title = null;
902 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700903 }
904
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800905 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700906 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700907 builder.setTicker(title);
908 builder.setContentTitle(title);
909 builder.setContentText(body);
910
911 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700912 builder.setContentIntent(PendingIntent.getActivity(
913 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700914 break;
915 }
916 }
917
918 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700919 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700920 try {
921 final String packageName = mContext.getPackageName();
922 final int[] idReceived = new int[1];
923 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800924 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Dianne Hackborn41203752012-08-31 14:05:51 -0700925 UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700926 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700927 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700928 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700929 }
930 }
931
932 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700933 * Show ongoing notification to reflect that {@link #mRestrictBackground}
934 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700935 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700936 private void enqueueRestrictedNotification(String tag) {
937 final Resources res = mContext.getResources();
938 final Notification.Builder builder = new Notification.Builder(mContext);
939
940 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
941 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
942
943 builder.setOnlyAlertOnce(true);
944 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700945 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700946 builder.setTicker(title);
947 builder.setContentTitle(title);
948 builder.setContentText(body);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700949 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200950 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700951
952 final Intent intent = buildAllowBackgroundDataIntent();
953 builder.setContentIntent(
954 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700955
956 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700957 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700958 try {
959 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700960 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800961 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Dianne Hackborn41203752012-08-31 14:05:51 -0700962 0x0, builder.getNotification(), idReceived, UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700963 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700964 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700965 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700966 }
967 }
968
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700969 private void cancelNotification(String tag) {
970 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700971 // XXX what to do about multi-user?
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700972 try {
973 final String packageName = mContext.getPackageName();
974 mNotifManager.cancelNotificationWithTag(
Dianne Hackborn41203752012-08-31 14:05:51 -0700975 packageName, tag, 0x0, UserHandle.USER_OWNER);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700976 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700977 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700978 }
979 }
980
981 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700982 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700983 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700984 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700985 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700986 @Override
987 public void onReceive(Context context, Intent intent) {
988 // on background handler thread, and verified CONNECTIVITY_INTERNAL
989 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800990
991 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700992 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700993 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -0800994 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700995 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700996 updateNetworkRulesLocked();
997 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700998 }
999 }
1000 };
1001
1002 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001003 * Proactively control network data connections when they exceed
1004 * {@link NetworkPolicy#limitBytes}.
1005 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001006 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001007 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1008
1009 // TODO: reset any policy-disabled networks when any policy is removed
1010 // completely, which is currently rare case.
1011
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001012 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001013 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1014 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001015 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001016 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001017 setNetworkTemplateEnabled(policy.template, true);
1018 continue;
1019 }
1020
1021 final long start = computeLastCycleBoundary(currentTime, policy);
1022 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001023 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001024
1025 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001026 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1027 && policy.lastLimitSnooze < start;
1028 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001029
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001030 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001031 }
1032 }
1033
1034 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001035 * Proactively disable networks that match the given
1036 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001037 */
1038 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001039 // TODO: reach into ConnectivityManager to proactively disable bringing
1040 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001041 }
1042
1043 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001044 * Examine all connected {@link NetworkState}, looking for
1045 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1046 * remaining quota based on usage cycle and historical stats.
1047 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001048 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001049 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001050
1051 final NetworkState[] states;
1052 try {
1053 states = mConnManager.getAllNetworkState();
1054 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001055 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001056 return;
1057 }
1058
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001059 // If we are in restrict power mode, we want to treat all interfaces
1060 // as metered, to restrict access to the network by uid. However, we
1061 // will not have a bandwidth limit. Also only do this if restrict
1062 // background data use is *not* enabled, since that takes precendence
1063 // use over those networks can have a cost associated with it).
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001064 final boolean powerSave = (mRestrictPower || mDeviceIdleMode) && !mRestrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001065
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001066 // First, generate identities of all connected networks so we can
1067 // quickly compare them against all defined policies below.
1068 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001069 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001070 for (NetworkState state : states) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001071 if (state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001072 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001073
1074 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001075 if (baseIface != null) {
1076 connIdents.add(Pair.create(baseIface, ident));
1077 if (powerSave) {
1078 connIfaces.add(baseIface);
1079 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001080 }
1081
1082 // Stacked interfaces are considered to have same identity as
1083 // their parent network.
1084 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1085 for (LinkProperties stackedLink : stackedLinks) {
1086 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001087 if (stackedIface != null) {
1088 connIdents.add(Pair.create(stackedIface, ident));
1089 if (powerSave) {
1090 connIfaces.add(stackedIface);
1091 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001092 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001093 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001094 }
1095 }
1096
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001097 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001098 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001099 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001100 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001101 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001102
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001103 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001104 for (int j = connIdents.size() - 1; j >= 0; j--) {
1105 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1106 if (policy.template.matches(ident.second)) {
1107 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001108 }
1109 }
1110
1111 if (ifaceList.size() > 0) {
1112 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001113 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001114 }
1115 }
1116
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001117 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001118 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001119
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001120 // apply each policy that we found ifaces for; compute remaining data
1121 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001122 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001123 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1124 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1125 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001126
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001127 final long start;
1128 final long totalBytes;
1129 if (policy.hasCycle()) {
1130 start = computeLastCycleBoundary(currentTime, policy);
1131 totalBytes = getTotalBytes(policy.template, start, currentTime);
1132 } else {
1133 start = Long.MAX_VALUE;
1134 totalBytes = 0;
1135 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001136
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001137 if (LOGD) {
1138 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001139 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001140 }
1141
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001142 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001143 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001144 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001145 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001146 if (!hasLimit) {
1147 // metered network, but no policy limit; we still need to
1148 // restrict apps, so push really high quota.
1149 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001150 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001151 // snoozing past quota, but we still need to restrict apps,
1152 // so push really high quota.
1153 quotaBytes = Long.MAX_VALUE;
1154 } else {
1155 // remaining "quota" bytes are based on total usage in
1156 // current cycle. kernel doesn't like 0-byte rules, so we
1157 // set 1-byte quota and disable the radio later.
1158 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1159 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001160
1161 if (ifaces.length > 1) {
1162 // TODO: switch to shared quota once NMS supports
1163 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001164 }
1165
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001166 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001167 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001168 setInterfaceQuota(iface, quotaBytes);
1169 newMeteredIfaces.add(iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001170 if (powerSave) {
1171 connIfaces.remove(iface);
1172 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001173 }
1174 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001175
1176 // keep track of lowest warning or limit of active policies
1177 if (hasWarning && policy.warningBytes < lowestRule) {
1178 lowestRule = policy.warningBytes;
1179 }
1180 if (hasLimit && policy.limitBytes < lowestRule) {
1181 lowestRule = policy.limitBytes;
1182 }
1183 }
1184
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001185 for (int i = connIfaces.size()-1; i >= 0; i--) {
1186 String iface = connIfaces.valueAt(i);
1187 removeInterfaceQuota(iface);
1188 setInterfaceQuota(iface, Long.MAX_VALUE);
1189 newMeteredIfaces.add(iface);
1190 }
1191
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001192 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001193
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001194 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001195 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1196 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001197 if (!newMeteredIfaces.contains(iface)) {
1198 removeInterfaceQuota(iface);
1199 }
1200 }
1201 mMeteredIfaces = newMeteredIfaces;
1202
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001203 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001204 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001205 }
1206
1207 /**
1208 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1209 * have at least a default mobile policy defined.
1210 */
1211 private void ensureActiveMobilePolicyLocked() {
1212 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001213 if (mSuppressDefaultPolicy) return;
1214
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001215 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001216 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001217
Jeff Sharkey32566012014-12-02 18:30:14 -08001218 final int[] subIds = sub.getActiveSubscriptionIdList();
1219 for (int subId : subIds) {
1220 final String subscriberId = tele.getSubscriberId(subId);
1221 ensureActiveMobilePolicyLocked(subscriberId);
1222 }
1223 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001224
Jeff Sharkey32566012014-12-02 18:30:14 -08001225 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1226 // Poke around to see if we already have a policy
1227 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1228 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1229 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1230 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1231 if (template.matches(probeIdent)) {
1232 if (LOGD) {
1233 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1234 + NetworkIdentity.scrubSubscriberId(subscriberId));
1235 }
1236 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001237 }
1238 }
1239
Jeff Sharkey32566012014-12-02 18:30:14 -08001240 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1241 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001242
Jeff Sharkey32566012014-12-02 18:30:14 -08001243 // Build default mobile policy, and assume usage cycle starts today
1244 final long warningBytes = mContext.getResources().getInteger(
1245 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001246
Jeff Sharkey32566012014-12-02 18:30:14 -08001247 final Time time = new Time();
1248 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001249
Jeff Sharkey32566012014-12-02 18:30:14 -08001250 final int cycleDay = time.monthDay;
1251 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001252
Jeff Sharkey32566012014-12-02 18:30:14 -08001253 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1254 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1255 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1256 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001257 }
1258
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001259 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001260 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001261
1262 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001263 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001264 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001265
1266 FileInputStream fis = null;
1267 try {
1268 fis = mPolicyFile.openRead();
1269 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001270 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001271
1272 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001273 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001274 while ((type = in.next()) != END_DOCUMENT) {
1275 final String tag = in.getName();
1276 if (type == START_TAG) {
1277 if (TAG_POLICY_LIST.equals(tag)) {
1278 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001279 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1280 mRestrictBackground = readBooleanAttribute(
1281 in, ATTR_RESTRICT_BACKGROUND);
1282 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001283 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001284 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001285
1286 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1287 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1288 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001289 final String networkId;
1290 if (version >= VERSION_ADDED_NETWORK_ID) {
1291 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1292 } else {
1293 networkId = null;
1294 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001295 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001296 final String cycleTimezone;
1297 if (version >= VERSION_ADDED_TIMEZONE) {
1298 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1299 } else {
1300 cycleTimezone = Time.TIMEZONE_UTC;
1301 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001302 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1303 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001304 final long lastLimitSnooze;
1305 if (version >= VERSION_SPLIT_SNOOZE) {
1306 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1307 } else if (version >= VERSION_ADDED_SNOOZE) {
1308 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001309 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001310 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001311 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001312 final boolean metered;
1313 if (version >= VERSION_ADDED_METERED) {
1314 metered = readBooleanAttribute(in, ATTR_METERED);
1315 } else {
1316 switch (networkTemplate) {
1317 case MATCH_MOBILE_3G_LOWER:
1318 case MATCH_MOBILE_4G:
1319 case MATCH_MOBILE_ALL:
1320 metered = true;
1321 break;
1322 default:
1323 metered = false;
1324 }
1325 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001326 final long lastWarningSnooze;
1327 if (version >= VERSION_SPLIT_SNOOZE) {
1328 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1329 } else {
1330 lastWarningSnooze = SNOOZE_NEVER;
1331 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001332 final boolean inferred;
1333 if (version >= VERSION_ADDED_INFERRED) {
1334 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1335 } else {
1336 inferred = false;
1337 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001338
Jeff Sharkey32566012014-12-02 18:30:14 -08001339 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1340 subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001341 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001342 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001343 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001344
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001345 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001346 final int uid = readIntAttribute(in, ATTR_UID);
1347 final int policy = readIntAttribute(in, ATTR_POLICY);
1348
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001349 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001350 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001351 } else {
1352 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1353 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001354 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001355 final int appId = readIntAttribute(in, ATTR_APP_ID);
1356 final int policy = readIntAttribute(in, ATTR_POLICY);
1357
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001358 // TODO: set for other users during upgrade
1359 final int uid = UserHandle.getUid(UserHandle.USER_OWNER, appId);
1360 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001361 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001362 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001363 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001364 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001365 }
1366 }
1367 }
1368
1369 } catch (FileNotFoundException e) {
1370 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001371 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001372 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001373 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001374 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001375 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001376 } finally {
1377 IoUtils.closeQuietly(fis);
1378 }
1379 }
1380
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001381 /**
1382 * Upgrade legacy background data flags, notifying listeners of one last
1383 * change to always-true.
1384 */
1385 private void upgradeLegacyBackgroundData() {
1386 mRestrictBackground = Settings.Secure.getInt(
1387 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1388
1389 // kick off one last broadcast if restricted
1390 if (mRestrictBackground) {
1391 final Intent broadcast = new Intent(
1392 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001393 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001394 }
1395 }
1396
Dianne Hackborn497175b2014-07-01 12:56:08 -07001397 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001398 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001399
1400 FileOutputStream fos = null;
1401 try {
1402 fos = mPolicyFile.startWrite();
1403
1404 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001405 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001406 out.startDocument(null, true);
1407
1408 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001409 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001410 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001411
1412 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001413 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1414 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001415 final NetworkTemplate template = policy.template;
1416
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001417 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001418 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1419 final String subscriberId = template.getSubscriberId();
1420 if (subscriberId != null) {
1421 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001422 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001423 final String networkId = template.getNetworkId();
1424 if (networkId != null) {
1425 out.attribute(null, ATTR_NETWORK_ID, networkId);
1426 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001427 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001428 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001429 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1430 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001431 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1432 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001433 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001434 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001435 out.endTag(null, TAG_NETWORK_POLICY);
1436 }
1437
1438 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001439 for (int i = 0; i < mUidPolicy.size(); i++) {
1440 final int uid = mUidPolicy.keyAt(i);
1441 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001442
Jeff Sharkey497e4432011-06-14 17:27:29 -07001443 // skip writing empty policies
1444 if (policy == POLICY_NONE) continue;
1445
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001446 out.startTag(null, TAG_UID_POLICY);
1447 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001448 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001449 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001450 }
1451
1452 out.endTag(null, TAG_POLICY_LIST);
1453 out.endDocument();
1454
1455 mPolicyFile.finishWrite(fos);
1456 } catch (IOException e) {
1457 if (fos != null) {
1458 mPolicyFile.failWrite(fos);
1459 }
1460 }
1461 }
1462
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001463 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001464 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001465 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001466
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001467 if (!UserHandle.isApp(uid)) {
1468 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001469 }
1470
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001471 synchronized (mRulesLock) {
1472 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1473 if (oldPolicy != policy) {
1474 setUidPolicyUncheckedLocked(uid, policy, true);
1475 }
1476 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001477 }
1478
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001479 @Override
1480 public void addUidPolicy(int uid, int policy) {
1481 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001482
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001483 if (!UserHandle.isApp(uid)) {
1484 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1485 }
1486
1487 synchronized (mRulesLock) {
1488 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1489 policy |= oldPolicy;
1490 if (oldPolicy != policy) {
1491 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001492 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001493 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001494 }
1495
1496 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001497 public void removeUidPolicy(int uid, int policy) {
1498 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1499
1500 if (!UserHandle.isApp(uid)) {
1501 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1502 }
1503
1504 synchronized (mRulesLock) {
1505 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1506 policy = oldPolicy & ~policy;
1507 if (oldPolicy != policy) {
1508 setUidPolicyUncheckedLocked(uid, policy, true);
1509 }
1510 }
1511 }
1512
1513 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1514 mUidPolicy.put(uid, policy);
1515
1516 // uid policy changed, recompute rules and persist policy.
1517 updateRulesForUidLocked(uid);
1518 if (persist) {
1519 writePolicyLocked();
1520 }
1521 }
1522
1523 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001524 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001525 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1526
Jeff Sharkeya4620792011-05-20 15:29:23 -07001527 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001528 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001529 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001530 }
1531
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001532 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001533 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001534 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1535
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001536 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001537 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001538 for (int i = 0; i < mUidPolicy.size(); i++) {
1539 final int uid = mUidPolicy.keyAt(i);
1540 final int uidPolicy = mUidPolicy.valueAt(i);
1541 if (uidPolicy == policy) {
1542 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001543 }
1544 }
1545 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001546 return uids;
1547 }
1548
1549 /**
1550 * Remove any policies associated with given {@link UserHandle}, persisting
1551 * if any changes are made.
1552 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001553 void removePoliciesForUserLocked(int userId) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001554 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1555
1556 int[] uids = new int[0];
1557 for (int i = 0; i < mUidPolicy.size(); i++) {
1558 final int uid = mUidPolicy.keyAt(i);
1559 if (UserHandle.getUserId(uid) == userId) {
1560 uids = appendInt(uids, uid);
1561 }
1562 }
1563
1564 if (uids.length > 0) {
1565 for (int uid : uids) {
1566 mUidPolicy.delete(uid);
1567 updateRulesForUidLocked(uid);
1568 }
1569 writePolicyLocked();
1570 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001571 }
1572
1573 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001574 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001575 // TODO: create permission for observing network policy
1576 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1577
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001578 mListeners.register(listener);
1579
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001580 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001581 }
1582
1583 @Override
1584 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001585 // TODO: create permission for observing network policy
1586 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1587
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001588 mListeners.unregister(listener);
1589 }
1590
Jeff Sharkey1b861272011-05-22 00:34:52 -07001591 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001592 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001593 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1594
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001595 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001596 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001597 normalizePoliciesLocked(policies);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001598 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001599 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001600 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001601 writePolicyLocked();
1602 }
1603 }
1604
Dianne Hackborn497175b2014-07-01 12:56:08 -07001605 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001606 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001607 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1608 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001609 }
1610
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001611 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001612 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001613 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001614 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001615
Svet Ganov16a16892015-04-16 10:32:04 -07001616 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1617 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1618 return new NetworkPolicy[0];
1619 }
1620
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001621 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001622 final int size = mNetworkPolicy.size();
1623 final NetworkPolicy[] policies = new NetworkPolicy[size];
1624 for (int i = 0; i < size; i++) {
1625 policies[i] = mNetworkPolicy.valueAt(i);
1626 }
1627 return policies;
1628 }
1629 }
1630
1631 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001632 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001633 }
1634
1635 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1636 final TelephonyManager tele = TelephonyManager.from(mContext);
1637 final String[] merged = tele.getMergedSubscriberIds();
1638
1639 mNetworkPolicy.clear();
1640 for (NetworkPolicy policy : policies) {
1641 // When two normalized templates conflict, prefer the most
1642 // restrictive policy
1643 policy.template = NetworkTemplate.normalize(policy.template, merged);
1644 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1645 if (existing == null || existing.compareTo(policy) > 0) {
1646 if (existing != null) {
1647 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1648 }
1649 mNetworkPolicy.put(policy.template, policy);
1650 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001651 }
1652 }
1653
1654 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001655 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001656 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001657
1658 final long token = Binder.clearCallingIdentity();
1659 try {
1660 performSnooze(template, TYPE_LIMIT);
1661 } finally {
1662 Binder.restoreCallingIdentity(token);
1663 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001664 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001665
Dianne Hackborn497175b2014-07-01 12:56:08 -07001666 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001667 maybeRefreshTrustedTime();
1668 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001669 synchronized (mRulesLock) {
1670 // find and snooze local policy that matches
1671 final NetworkPolicy policy = mNetworkPolicy.get(template);
1672 if (policy == null) {
1673 throw new IllegalArgumentException("unable to find policy for " + template);
1674 }
1675
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001676 switch (type) {
1677 case TYPE_WARNING:
1678 policy.lastWarningSnooze = currentTime;
1679 break;
1680 case TYPE_LIMIT:
1681 policy.lastLimitSnooze = currentTime;
1682 break;
1683 default:
1684 throw new IllegalArgumentException("unexpected type");
1685 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001686
Jeff Sharkey32566012014-12-02 18:30:14 -08001687 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001688 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001689 updateNetworkRulesLocked();
1690 updateNotificationsLocked();
1691 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001692 }
1693 }
1694
1695 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001696 public void setRestrictBackground(boolean restrictBackground) {
1697 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1698
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001699 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001700 synchronized (mRulesLock) {
1701 mRestrictBackground = restrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001702 updateRulesForGlobalChangeLocked(false);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001703 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001704 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001705 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001706
1707 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1708 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001709 }
1710
1711 @Override
1712 public boolean getRestrictBackground() {
1713 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1714
1715 synchronized (mRulesLock) {
1716 return mRestrictBackground;
1717 }
1718 }
1719
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001720 @Override
1721 public void setDeviceIdleMode(boolean enabled) {
1722 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1723
1724 synchronized (mRulesLock) {
1725 if (mDeviceIdleMode != enabled) {
1726 mDeviceIdleMode = enabled;
1727 if (mSystemReady) {
1728 updateRulesForGlobalChangeLocked(true);
1729 }
1730 }
1731 }
1732 }
1733
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001734 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001735 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1736 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001737 if (policy.template.matches(ident)) {
1738 return policy;
1739 }
1740 }
1741 return null;
1742 }
1743
1744 @Override
1745 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1746 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1747
1748 // only returns usage summary, so we don't require caller to have
1749 // READ_NETWORK_USAGE_HISTORY.
1750 final long token = Binder.clearCallingIdentity();
1751 try {
1752 return getNetworkQuotaInfoUnchecked(state);
1753 } finally {
1754 Binder.restoreCallingIdentity(token);
1755 }
1756 }
1757
1758 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1759 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1760
1761 final NetworkPolicy policy;
1762 synchronized (mRulesLock) {
1763 policy = findPolicyForNetworkLocked(ident);
1764 }
1765
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001766 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001767 // missing policy means we can't derive useful quota info
1768 return null;
1769 }
1770
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001771 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001772
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001773 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001774 final long start = computeLastCycleBoundary(currentTime, policy);
1775 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001776 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001777
1778 // report soft and hard limits under policy
1779 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1780 : NetworkQuotaInfo.NO_LIMIT;
1781 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1782 : NetworkQuotaInfo.NO_LIMIT;
1783
1784 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1785 }
1786
Jeff Sharkey46645002011-07-27 21:11:21 -07001787 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001788 public boolean isNetworkMetered(NetworkState state) {
1789 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1790
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001791 // roaming networks are always considered metered
1792 if (ident.getRoaming()) {
1793 return true;
1794 }
1795
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001796 final NetworkPolicy policy;
1797 synchronized (mRulesLock) {
1798 policy = findPolicyForNetworkLocked(ident);
1799 }
1800
1801 if (policy != null) {
1802 return policy.metered;
1803 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001804 final int type = state.networkInfo.getType();
1805 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1806 return true;
1807 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001808 return false;
1809 }
1810 }
1811
1812 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001813 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001814 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001815
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001816 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1817
Dianne Hackborn497175b2014-07-01 12:56:08 -07001818 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001819 for (String arg : args) {
1820 argSet.add(arg);
1821 }
1822
Jeff Sharkey1b861272011-05-22 00:34:52 -07001823 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001824 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001825 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1826 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001827 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001828
Jeff Sharkey32566012014-12-02 18:30:14 -08001829 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001830 updateNetworkEnabledLocked();
1831 updateNetworkRulesLocked();
1832 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001833 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001834
1835 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001836 return;
1837 }
1838
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001839 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07001840 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001841 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001842 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001843 fout.print("Current foreground state: "); fout.println(mCurForegroundState);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001844 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001845 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001846 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1847 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001848 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001849 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001850
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001851 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
1852
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001853 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001854 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001855 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001856 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001857 final int uid = mUidPolicy.keyAt(i);
1858 final int policy = mUidPolicy.valueAt(i);
1859 fout.print("UID=");
1860 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001861 fout.print(" policy=");
1862 dumpPolicy(fout, policy);
1863 fout.println();
1864 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001865 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001866
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001867 size = mPowerSaveWhitelistAppIds.size();
1868 if (size > 0) {
1869 fout.println("Power save whitelist app ids:");
1870 fout.increaseIndent();
1871 for (int i = 0; i < size; i++) {
1872 fout.print("UID=");
1873 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
1874 fout.print(": ");
1875 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
1876 fout.println();
1877 }
1878 fout.decreaseIndent();
1879 }
1880
Jeff Sharkey1b861272011-05-22 00:34:52 -07001881 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07001882 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001883 collectKeys(mUidRules, knownUids);
1884
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001885 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001886 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001887 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001888 for (int i = 0; i < size; i++) {
1889 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001890 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001891 fout.print(uid);
1892
Dianne Hackborn497175b2014-07-01 12:56:08 -07001893 int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1894 fout.print(" state=");
1895 fout.print(state);
1896 fout.print(state <= mCurForegroundState ? " (fg)" : " (bg)");
1897
Jeff Sharkey1b861272011-05-22 00:34:52 -07001898 fout.print(" rules=");
1899 final int rulesIndex = mUidRules.indexOfKey(uid);
1900 if (rulesIndex < 0) {
1901 fout.print("UNKNOWN");
1902 } else {
1903 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1904 }
1905
1906 fout.println();
1907 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001908 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001909 }
1910 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001911
1912 @Override
1913 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001914 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1915
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001916 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001917 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001918 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001919 }
1920
Dianne Hackborn497175b2014-07-01 12:56:08 -07001921 boolean isUidForegroundLocked(int uid) {
1922 // only really in foreground when screen is also on
1923 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
1924 <= mCurForegroundState;
1925 }
1926
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001927 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07001928 * Process state of UID changed; if needed, will trigger
1929 * {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001930 */
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07001931 void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001932 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1933 if (oldUidState != uidState) {
1934 // state changed, push updated rules
1935 mUidState.put(uid, uidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07001936 updateRulesForUidStateChangeLocked(uid, oldUidState, uidState);
1937 }
1938 }
1939
1940 void removeUidStateLocked(int uid) {
1941 final int index = mUidState.indexOfKey(uid);
1942 if (index >= 0) {
1943 final int oldUidState = mUidState.valueAt(index);
1944 mUidState.removeAt(index);
1945 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
1946 updateRulesForUidStateChangeLocked(uid, oldUidState,
1947 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001948 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001949 }
1950 }
1951
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07001952 void updateRulesForUidStateChangeLocked(int uid, int oldUidState, int newUidState) {
1953 final boolean oldForeground = oldUidState <= mCurForegroundState;
1954 final boolean newForeground = newUidState <= mCurForegroundState;
1955 if (oldForeground != newForeground) {
1956 updateRulesForUidLocked(uid);
1957 }
1958 }
1959
Jeff Sharkeya4620792011-05-20 15:29:23 -07001960 private void updateScreenOn() {
1961 synchronized (mRulesLock) {
1962 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07001963 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001964 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001965 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07001966 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001967 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001968 }
1969 }
1970
1971 /**
1972 * Update rules that might be changed by {@link #mScreenOn} value.
1973 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001974 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07001975 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07001976 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001977 for (int i = 0; i < size; i++) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001978 if (mUidState.valueAt(i) <= mCurForegroundState) {
1979 final int uid = mUidState.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001980 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001981 }
1982 }
1983 }
1984
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001985 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001986 * Update rules that might be changed by {@link #mRestrictBackground},
1987 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001988 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001989 void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001990 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001991
Dianne Hackborn497175b2014-07-01 12:56:08 -07001992 // If we are in restrict power mode, we allow all important apps
1993 // to have data access. Otherwise, we restrict data access to only
1994 // the top apps.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001995 mCurForegroundState = (!mRestrictBackground && (mRestrictPower || mDeviceIdleMode))
Dianne Hackbornd69e4c12015-04-24 09:54:54 -07001996 ? ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
Dianne Hackborn497175b2014-07-01 12:56:08 -07001997 : ActivityManager.PROCESS_STATE_TOP;
1998
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001999 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002000 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002001 final List<ApplicationInfo> apps = pm.getInstalledApplications(
2002 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
2003
2004 for (UserInfo user : users) {
2005 for (ApplicationInfo app : apps) {
2006 final int uid = UserHandle.getUid(user.id, app.uid);
2007 updateRulesForUidLocked(uid);
2008 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002009 }
2010
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002011 // limit data usage for some internal system services
2012 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
2013 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002014
2015 // If the set of restricted networks may have changed, re-evaluate those.
2016 if (restrictedNetworksChanged) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002017 normalizePoliciesLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002018 updateNetworkRulesLocked();
2019 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002020 }
2021
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002022 private static boolean isUidValidForRules(int uid) {
2023 // allow rules on specific system services, and any apps
2024 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002025 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002026 return true;
2027 }
2028
2029 return false;
2030 }
2031
Amith Yamasani15e472352015-04-24 19:06:07 -07002032 private boolean isUidIdle(int uid) {
2033 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2034 final int userId = UserHandle.getUserId(uid);
2035
2036 for (String packageName : packages) {
2037 if (!mUsageStats.isAppIdle(packageName, userId)) {
2038 return false;
2039 }
2040 }
2041 return true;
2042 }
2043
2044 /**
2045 * Applies network rules to bandwidth and firewall controllers based on uid policy.
2046 * @param uid The uid for which to apply the latest policy
2047 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002048 void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002049 if (!isUidValidForRules(uid)) return;
2050
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002051 // quick check: if this uid doesn't have INTERNET permission, it doesn't have
2052 // network access anyway, so it is a waste to mess with it here.
2053 final IPackageManager ipm = AppGlobals.getPackageManager();
2054 try {
2055 if (ipm.checkUidPermission(Manifest.permission.INTERNET, uid)
2056 != PackageManager.PERMISSION_GRANTED) {
2057 return;
2058 }
2059 } catch (RemoteException e) {
2060 }
2061
Dianne Hackborn497175b2014-07-01 12:56:08 -07002062 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2063 final boolean uidForeground = isUidForegroundLocked(uid);
Amith Yamasani15e472352015-04-24 19:06:07 -07002064 final boolean uidIdle = isUidIdle(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002065
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002066 // derive active rules based on policy and active state
Amith Yamasani15e472352015-04-24 19:06:07 -07002067
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002068 int uidRules = RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -07002069 if (uidIdle && !mPowerSaveWhitelistAppIds.get(UserHandle.getAppId(uid))) {
2070 uidRules = RULE_REJECT_ALL;
2071 } else if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002072 // uid in background, and policy says to block metered data
2073 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002074 } else if (mRestrictBackground) {
2075 if (!uidForeground) {
2076 // uid in background, and global background disabled
2077 uidRules = RULE_REJECT_METERED;
2078 }
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002079 } else if (mRestrictPower || mDeviceIdleMode) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002080 final boolean whitelisted = mPowerSaveWhitelistAppIds.get(UserHandle.getAppId(uid));
2081 if (!whitelisted && !uidForeground
2082 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
2083 // uid is in background, restrict power use mode is on (so we want to
2084 // restrict all background network access), and this uid is not on the
2085 // white list of those allowed background access.
2086 uidRules = RULE_REJECT_METERED;
2087 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002088 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002089
Amith Yamasani15e472352015-04-24 19:06:07 -07002090 final int oldRules = mUidRules.get(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002091
Jeff Sharkey350083e2011-06-29 10:45:16 -07002092 if (uidRules == RULE_ALLOW_ALL) {
2093 mUidRules.delete(uid);
2094 } else {
2095 mUidRules.put(uid, uidRules);
2096 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002097
Amith Yamasani15e472352015-04-24 19:06:07 -07002098 // Update bandwidth rules if necessary
2099 final boolean oldRejectMetered = (oldRules & RULE_REJECT_METERED) != 0;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002100 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Amith Yamasani15e472352015-04-24 19:06:07 -07002101 if (oldRejectMetered != rejectMetered) {
2102 setUidNetworkRules(uid, rejectMetered);
2103 }
2104
2105 // Update firewall rules if necessary
2106 final boolean oldFirewallReject = (oldRules & RULE_REJECT_ALL) != 0;
2107 final boolean firewallReject = (uidRules & RULE_REJECT_ALL) != 0;
2108 if (oldFirewallReject != firewallReject) {
2109 setUidFirewallRules(uid, firewallReject);
2110 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002111
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002112 // dispatch changed rule to existing listeners
Amith Yamasani15e472352015-04-24 19:06:07 -07002113 if (oldRules != uidRules) {
2114 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
2115 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002116
2117 try {
2118 // adjust stats accounting based on foreground status
2119 mNetworkStats.setUidForeground(uid, uidForeground);
2120 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002121 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002122 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002123 }
2124
Amith Yamasani15e472352015-04-24 19:06:07 -07002125 @Override
2126 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2127 try {
2128 int uid = mContext.getPackageManager().getPackageUid(packageName, userId);
2129 synchronized (mRulesLock) {
2130 updateRulesForUidLocked(uid);
2131 }
2132 } catch (NameNotFoundException nnfe) {
2133 return;
2134 }
2135 }
2136
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002137 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002138 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002139 public boolean handleMessage(Message msg) {
2140 switch (msg.what) {
2141 case MSG_RULES_CHANGED: {
2142 final int uid = msg.arg1;
2143 final int uidRules = msg.arg2;
2144 final int length = mListeners.beginBroadcast();
2145 for (int i = 0; i < length; i++) {
2146 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2147 if (listener != null) {
2148 try {
2149 listener.onUidRulesChanged(uid, uidRules);
2150 } catch (RemoteException e) {
2151 }
2152 }
2153 }
2154 mListeners.finishBroadcast();
2155 return true;
2156 }
2157 case MSG_METERED_IFACES_CHANGED: {
2158 final String[] meteredIfaces = (String[]) msg.obj;
2159 final int length = mListeners.beginBroadcast();
2160 for (int i = 0; i < length; i++) {
2161 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2162 if (listener != null) {
2163 try {
2164 listener.onMeteredIfacesChanged(meteredIfaces);
2165 } catch (RemoteException e) {
2166 }
2167 }
2168 }
2169 mListeners.finishBroadcast();
2170 return true;
2171 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002172 case MSG_LIMIT_REACHED: {
2173 final String iface = (String) msg.obj;
2174
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002175 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002176 synchronized (mRulesLock) {
2177 if (mMeteredIfaces.contains(iface)) {
2178 try {
2179 // force stats update to make sure we have
2180 // numbers that caused alert to trigger.
2181 mNetworkStats.forceUpdate();
2182 } catch (RemoteException e) {
2183 // ignored; service lives in system_server
2184 }
2185
2186 updateNetworkEnabledLocked();
2187 updateNotificationsLocked();
2188 }
2189 }
2190 return true;
2191 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002192 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2193 final boolean restrictBackground = msg.arg1 != 0;
2194 final int length = mListeners.beginBroadcast();
2195 for (int i = 0; i < length; i++) {
2196 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2197 if (listener != null) {
2198 try {
2199 listener.onRestrictBackgroundChanged(restrictBackground);
2200 } catch (RemoteException e) {
2201 }
2202 }
2203 }
2204 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002205 return true;
2206 }
2207 case MSG_ADVISE_PERSIST_THRESHOLD: {
2208 final long lowestRule = (Long) msg.obj;
2209 try {
2210 // make sure stats are recorded frequently enough; we aim
2211 // for 2MB threshold for 2GB/month rules.
2212 final long persistThreshold = lowestRule / 1000;
2213 mNetworkStats.advisePersistThreshold(persistThreshold);
2214 } catch (RemoteException e) {
2215 // ignored; service lives in system_server
2216 }
2217 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002218 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002219 case MSG_SCREEN_ON_CHANGED: {
2220 updateScreenOn();
2221 return true;
2222 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002223 default: {
2224 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002225 }
2226 }
2227 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002228 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002229
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002230 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002231 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002232 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002233 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002234 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002235 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002236 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002237 }
2238 }
2239
2240 private void removeInterfaceQuota(String iface) {
2241 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002242 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002243 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002244 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002245 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002246 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002247 }
2248 }
2249
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002250 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2251 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002252 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002253 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002254 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002255 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002256 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002257 }
2258 }
2259
Amith Yamasani15e472352015-04-24 19:06:07 -07002260 /**
2261 * Add or remove a uid to the firewall blacklist for all network ifaces.
2262 * @param uid
2263 * @param rejectOnAll
2264 */
2265 private void setUidFirewallRules(int uid, boolean rejectOnAll) {
2266 try {
2267 mNetworkManager.setFirewallUidRule(uid,
2268 rejectOnAll ? FIREWALL_RULE_DENY : FIREWALL_RULE_DEFAULT);
2269 } catch (IllegalStateException e) {
2270 Log.wtf(TAG, "problem setting firewall uid rules", e);
2271 } catch (RemoteException e) {
2272 // ignored; service lives in system_server
2273 }
2274 }
2275
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002276 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2277 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002278 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002279 } catch (RuntimeException e) {
2280 Slog.w(TAG, "problem reading network stats: " + e);
2281 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002282 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002283 // ignored; service lives in system_server
2284 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002285 }
2286 }
2287
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002288 private boolean isBandwidthControlEnabled() {
2289 final long token = Binder.clearCallingIdentity();
2290 try {
2291 return mNetworkManager.isBandwidthControlEnabled();
2292 } catch (RemoteException e) {
2293 // ignored; service lives in system_server
2294 return false;
2295 } finally {
2296 Binder.restoreCallingIdentity(token);
2297 }
2298 }
2299
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002300 /**
2301 * Try refreshing {@link #mTime} when stale.
2302 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002303 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002304 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002305 mTime.forceRefresh();
2306 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002307 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002308
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002309 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002310 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2311 }
2312
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002313 private static Intent buildAllowBackgroundDataIntent() {
2314 return new Intent(ACTION_ALLOW_BACKGROUND);
2315 }
2316
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002317 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2318 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2319 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2320 return intent;
2321 }
2322
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002323 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2324 final Intent intent = new Intent();
2325 intent.setComponent(new ComponentName(
2326 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2327 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2328 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2329 return intent;
2330 }
2331
2332 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2333 final Intent intent = new Intent();
2334 intent.setComponent(new ComponentName(
2335 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2336 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2337 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2338 return intent;
2339 }
2340
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002341 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002342 public void addIdleHandler(IdleHandler handler) {
2343 mHandler.getLooper().getQueue().addIdleHandler(handler);
2344 }
2345
Jeff Sharkey1b861272011-05-22 00:34:52 -07002346 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2347 final int size = source.size();
2348 for (int i = 0; i < size; i++) {
2349 target.put(source.keyAt(i), true);
2350 }
2351 }
2352
Stuart Scottf1fb3972015-04-02 18:00:02 -07002353 @Override
2354 public void factoryReset(String subscriber) {
2355 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2356
Stuart Scotte3e314d2015-04-20 14:07:45 -07002357 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
2358 return;
2359 }
2360
Stuart Scottf1fb3972015-04-02 18:00:02 -07002361 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07002362 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07002363 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
2364 for (NetworkPolicy policy : policies) {
2365 if (policy.template.equals(template)) {
2366 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2367 policy.inferred = false;
2368 policy.clearSnooze();
2369 }
2370 }
2371 setNetworkPolicies(policies);
2372
2373 // Turn restrict background data off
2374 setRestrictBackground(false);
2375
Stuart Scotte3e314d2015-04-20 14:07:45 -07002376 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
2377 // Remove app's "restrict background data" flag
2378 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
2379 setUidPolicy(uid, POLICY_NONE);
2380 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07002381 }
2382 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002383}