blob: 7673af44f5ac6e60005a29685a4e976bd0f17bf8 [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.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700286 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800287 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700288 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700289
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700290 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
291
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700292 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800293 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700294 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800295 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700296
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700297 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700298 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700299
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700300 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800301 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700302
303 /** The current maximum process state that we are considering to be foreground. */
304 private int mCurForegroundState = ActivityManager.PROCESS_STATE_TOP;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700305
Jeff Sharkey32566012014-12-02 18:30:14 -0800306 private final RemoteCallbackList<INetworkPolicyListener>
307 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700308
Dianne Hackborn497175b2014-07-01 12:56:08 -0700309 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700310
311 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700312
Svet Ganov16a16892015-04-16 10:32:04 -0700313 private final AppOpsManager mAppOps;
314
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700315 // TODO: keep whitelist of system-critical services that should never have
316 // rules enforced, such as system, phone, and radio UIDs.
317
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700318 // TODO: migrate notifications to SystemUI
319
Jeff Sharkey75279902011-05-24 18:39:45 -0700320 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700321 IPowerManager powerManager, INetworkStatsService networkStats,
322 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700323 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700324 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700325 }
326
327 private static File getSystemDir() {
328 return new File(Environment.getDataDirectory(), "system");
329 }
330
331 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700332 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700333 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
334 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700335 mContext = checkNotNull(context, "missing context");
336 mActivityManager = checkNotNull(activityManager, "missing activityManager");
337 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700338 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700339 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700340 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
341 DeviceIdleController.SERVICE_NAME));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700342 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700343 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700344
Amith Yamasani450a16b2013-09-18 16:28:50 -0700345 HandlerThread thread = new HandlerThread(TAG);
346 thread.start();
347 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700348
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700349 mSuppressDefaultPolicy = suppressDefaultPolicy;
350
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700351 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700352
353 mAppOps = context.getSystemService(AppOpsManager.class);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700354 }
355
356 public void bindConnectivityManager(IConnectivityManager connManager) {
357 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700358 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700359
Jeff Sharkey497e4432011-06-14 17:27:29 -0700360 public void bindNotificationManager(INotificationManager notifManager) {
361 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
362 }
363
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700364 void updatePowerSaveWhitelistLocked() {
365 try {
366 final int[] whitelist = mDeviceIdleController.getAppIdWhitelist();
367 mPowerSaveWhitelistAppIds.clear();
368 if (whitelist != null) {
369 for (int uid : whitelist) {
370 mPowerSaveWhitelistAppIds.put(uid, true);
371 }
372 }
373 } catch (RemoteException e) {
374 }
375 }
376
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700377 void updatePowerSaveTempWhitelistLocked() {
378 try {
379 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
380 mPowerSaveTempWhitelistAppIds.clear();
381 if (whitelist != null) {
382 for (int uid : whitelist) {
383 mPowerSaveTempWhitelistAppIds.put(uid, true);
384 }
385 }
386 } catch (RemoteException e) {
387 }
388 }
389
Jeff Sharkeya4620792011-05-20 15:29:23 -0700390 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700391 if (!isBandwidthControlEnabled()) {
392 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
393 return;
394 }
395
Amith Yamasani15e472352015-04-24 19:06:07 -0700396 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
397
398 final PackageManager pm = mContext.getPackageManager();
399
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700400 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700401 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700402 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
403 mPowerManagerInternal.registerLowPowerModeObserver(
404 new PowerManagerInternal.LowPowerModeListener() {
405 @Override
406 public void onLowPowerModeChanged(boolean enabled) {
407 synchronized (mRulesLock) {
408 if (mRestrictPower != enabled) {
409 mRestrictPower = enabled;
410 updateRulesForGlobalChangeLocked(true);
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700411 updateRulesForTempWhitelistChangeLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700412 }
413 }
414 }
415 });
416 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700417 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700418
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700419 // read policy from disk
420 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700421
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700422 if (mRestrictBackground || mRestrictPower || mDeviceIdleMode) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700423 updateRulesForGlobalChangeLocked(true);
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700424 updateRulesForTempWhitelistChangeLocked();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700425 updateNotificationsLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700426 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700427 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700428
Jeff Sharkeya4620792011-05-20 15:29:23 -0700429 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700430
Jeff Sharkeya4620792011-05-20 15:29:23 -0700431 try {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700432 mActivityManager.registerUidObserver(mUidObserver);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700433 mNetworkManager.registerObserver(mAlertObserver);
434 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700435 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700436 }
437
Jeff Sharkeya4620792011-05-20 15:29:23 -0700438 // TODO: traverse existing processes to know foreground state, or have
439 // activitymanager dispatch current state when new observer attached.
440
441 final IntentFilter screenFilter = new IntentFilter();
442 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
443 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700444 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700445
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700446 // listen for changes to power save whitelist
447 final IntentFilter whitelistFilter = new IntentFilter(
448 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700449 whitelistFilter.addAction(PowerManager.ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700450 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
451
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700452 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900453 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700454 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
455
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700456 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700457 final IntentFilter packageFilter = new IntentFilter();
458 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700459 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700460 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700461
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700462 // listen for UID changes to update policy
463 mContext.registerReceiver(
464 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
465
466 // listen for user changes to update policy
467 final IntentFilter userFilter = new IntentFilter();
468 userFilter.addAction(ACTION_USER_ADDED);
469 userFilter.addAction(ACTION_USER_REMOVED);
470 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
471
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700472 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700473 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
474 mContext.registerReceiver(
475 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
476
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700477 // listen for restrict background changes from notifications
478 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
479 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
480
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800481 // listen for snooze warning from notifications
482 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
483 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
484 MANAGE_NETWORK_POLICY, mHandler);
485
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700486 // listen for configured wifi networks to be removed
487 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700488 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700489
490 // listen for wifi state changes to catch metered hint
491 final IntentFilter wifiStateFilter = new IntentFilter(
492 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700493 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700494
Amith Yamasani15e472352015-04-24 19:06:07 -0700495 mUsageStats.addAppIdleStateChangeListener(this);
496
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700497 }
498
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700499 private IUidObserver mUidObserver = new IUidObserver.Stub() {
500 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700501 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700502 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700503 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700504 }
505
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700506 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700507 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700508 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700509 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700510 }
511 };
512
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700513 private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
514 @Override
515 public void onReceive(Context context, Intent intent) {
516 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
517 synchronized (mRulesLock) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700518 if (PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED.equals(intent.getAction())) {
519 updatePowerSaveWhitelistLocked();
520 updateRulesForGlobalChangeLocked(false);
521 } else {
522 updatePowerSaveTempWhitelistLocked();
523 updateRulesForTempWhitelistChangeLocked();
524 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700525 }
526 }
527 };
528
Jeff Sharkeya4620792011-05-20 15:29:23 -0700529 private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
530 @Override
531 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800532 // screen-related broadcasts are protected by system, no need
533 // for permissions check.
534 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700535 }
536 };
537
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700538 private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700539 @Override
540 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700541 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700542
543 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700544 final int uid = intent.getIntExtra(EXTRA_UID, -1);
545 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700546
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700547 if (ACTION_PACKAGE_ADDED.equals(action)) {
548 // update rules for UID, since it might be subject to
549 // global background data policy
550 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
551 synchronized (mRulesLock) {
552 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700553 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700554 }
555 }
556 };
557
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700558 private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
559 @Override
560 public void onReceive(Context context, Intent intent) {
561 // on background handler thread, and UID_REMOVED is protected
562
563 final int uid = intent.getIntExtra(EXTRA_UID, -1);
564 if (uid == -1) return;
565
566 // remove any policy and update rules to clean up
567 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
568 synchronized (mRulesLock) {
569 mUidPolicy.delete(uid);
570 updateRulesForUidLocked(uid);
571 writePolicyLocked();
572 }
573 }
574 };
575
576 private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
577 @Override
578 public void onReceive(Context context, Intent intent) {
579 // on background handler thread, and USER_ADDED and USER_REMOVED
580 // broadcasts are protected
581
582 final String action = intent.getAction();
583 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
584 if (userId == -1) return;
585
Amith Yamasani15e472352015-04-24 19:06:07 -0700586 switch (action) {
587 case ACTION_USER_REMOVED:
588 case ACTION_USER_ADDED:
589 synchronized (mRulesLock) {
590 // Remove any policies for given user; both cleaning up after a
591 // USER_REMOVED, and one last sanity check during USER_ADDED
592 removePoliciesForUserLocked(userId);
593 // Update global restrict for new user
594 updateRulesForGlobalChangeLocked(true);
595 }
596 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700597 }
598 }
599 };
600
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700601 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700602 * Receiver that watches for {@link INetworkStatsService} updates, which we
603 * use to check against {@link NetworkPolicy#warningBytes}.
604 */
605 private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
606 @Override
607 public void onReceive(Context context, Intent intent) {
608 // on background handler thread, and verified
609 // READ_NETWORK_USAGE_HISTORY permission above.
610
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800611 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700612 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700613 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700614 updateNotificationsLocked();
615 }
616 }
617 };
618
619 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700620 * Receiver that watches for {@link Notification} control of
621 * {@link #mRestrictBackground}.
622 */
623 private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
624 @Override
625 public void onReceive(Context context, Intent intent) {
626 // on background handler thread, and verified MANAGE_NETWORK_POLICY
627 // permission above.
628
629 setRestrictBackground(false);
630 }
631 };
632
633 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800634 * Receiver that watches for {@link Notification} control of
635 * {@link NetworkPolicy#lastWarningSnooze}.
636 */
637 private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
638 @Override
639 public void onReceive(Context context, Intent intent) {
640 // on background handler thread, and verified MANAGE_NETWORK_POLICY
641 // permission above.
642
643 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
644 performSnooze(template, TYPE_WARNING);
645 }
646 };
647
648 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700649 * Receiver that watches for {@link WifiConfiguration} to be changed.
650 */
651 private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
652 @Override
653 public void onReceive(Context context, Intent intent) {
654 // on background handler thread, and verified CONNECTIVITY_INTERNAL
655 // permission above.
656
657 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
658 if (reason == CHANGE_REASON_REMOVED) {
659 final WifiConfiguration config = intent.getParcelableExtra(
660 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700661 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800662 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700663 synchronized (mRulesLock) {
664 if (mNetworkPolicy.containsKey(template)) {
665 mNetworkPolicy.remove(template);
666 writePolicyLocked();
667 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700668 }
669 }
670 }
671 }
672 };
673
674 /**
675 * Receiver that watches {@link WifiInfo} state changes to infer metered
676 * state. Ignores hints when policy is user-defined.
677 */
678 private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
679 @Override
680 public void onReceive(Context context, Intent intent) {
681 // on background handler thread, and verified CONNECTIVITY_INTERNAL
682 // permission above.
683
684 // ignore when not connected
685 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
686 if (!netInfo.isConnected()) return;
687
688 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
689 final boolean meteredHint = info.getMeteredHint();
690
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800691 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700692 synchronized (mRulesLock) {
693 NetworkPolicy policy = mNetworkPolicy.get(template);
694 if (policy == null && meteredHint) {
695 // policy doesn't exist, and AP is hinting that it's
696 // metered: create an inferred policy.
697 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
698 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
699 meteredHint, true);
700 addNetworkPolicyLocked(policy);
701
702 } else if (policy != null && policy.inferred) {
703 // policy exists, and was inferred: update its current
704 // metered state.
705 policy.metered = meteredHint;
706
707 // since this is inferred for each wifi session, just update
708 // rules without persisting.
709 updateNetworkRulesLocked();
710 }
711 }
712 }
713 };
714
715 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700716 * Observer that watches for {@link INetworkManagementService} alerts.
717 */
Jeff Sharkey216c1812012-08-05 14:29:23 -0700718 private INetworkManagementEventObserver mAlertObserver = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700719 @Override
720 public void limitReached(String limitName, String iface) {
721 // only someone like NMS should be calling us
722 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
723
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800724 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
725 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700726 }
727 }
728 };
729
730 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700731 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
732 * to show visible notifications as needed.
733 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700734 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700735 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
736
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700737 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700738 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700739 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700740
741 // TODO: when switching to kernel notifications, compute next future
742 // cycle boundary to recompute notifications.
743
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700744 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800745 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700746 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
747 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700748 // ignore policies that aren't relevant to user
749 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700750 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700751
Jeff Sharkey497e4432011-06-14 17:27:29 -0700752 final long start = computeLastCycleBoundary(currentTime, policy);
753 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700754 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700755
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700756 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800757 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700758 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
759 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700760 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
761 notifyOverLimitLocked(policy.template);
762 }
763
Jeff Sharkey497e4432011-06-14 17:27:29 -0700764 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700765 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700766
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800767 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700768 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700769 }
770 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700771 }
772
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700773 // ongoing notification when restricting background data
774 if (mRestrictBackground) {
775 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700776 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700777
778 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700779 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
780 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700781 if (!mActiveNotifs.contains(tag)) {
782 cancelNotification(tag);
783 }
784 }
785 }
786
787 /**
788 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700789 * current device state, such as when
790 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
791 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700792 */
793 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800794 if (template.isMatchRuleMobile()) {
795 final TelephonyManager tele = TelephonyManager.from(mContext);
796 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700797
Jeff Sharkey32566012014-12-02 18:30:14 -0800798 // Mobile template is relevant when any active subscriber matches
799 final int[] subIds = sub.getActiveSubscriptionIdList();
800 for (int subId : subIds) {
801 final String subscriberId = tele.getSubscriberId(subId);
802 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
803 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
804 if (template.matches(probeIdent)) {
805 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700806 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800807 }
808 return false;
809 } else {
810 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700811 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700812 }
813
814 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700815 * Notify that given {@link NetworkTemplate} is over
816 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
817 */
818 private void notifyOverLimitLocked(NetworkTemplate template) {
819 if (!mOverLimitNotified.contains(template)) {
820 mContext.startActivity(buildNetworkOverLimitIntent(template));
821 mOverLimitNotified.add(template);
822 }
823 }
824
825 private void notifyUnderLimitLocked(NetworkTemplate template) {
826 mOverLimitNotified.remove(template);
827 }
828
829 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700830 * Build unique tag that identifies an active {@link NetworkPolicy}
831 * notification of a specific type, like {@link #TYPE_LIMIT}.
832 */
833 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700834 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700835 }
836
837 /**
838 * Show notification for combined {@link NetworkPolicy} and specific type,
839 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
840 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700841 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700842 final String tag = buildNotificationTag(policy, type);
843 final Notification.Builder builder = new Notification.Builder(mContext);
844 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800845 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700846 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200847 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700848
849 final Resources res = mContext.getResources();
850 switch (type) {
851 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700852 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700853 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700854
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700855 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700856 builder.setTicker(title);
857 builder.setContentTitle(title);
858 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700859
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800860 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
861 builder.setDeleteIntent(PendingIntent.getBroadcast(
862 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
863
864 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700865 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800866 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
867
Jeff Sharkey497e4432011-06-14 17:27:29 -0700868 break;
869 }
870 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700871 final CharSequence body = res.getText(R.string.data_usage_limit_body);
872
873 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -0400874 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700875 switch (policy.template.getMatchRule()) {
876 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700877 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700878 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700879 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700880 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700881 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700882 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700883 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700884 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700885 case MATCH_WIFI:
886 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -0400887 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700888 break;
889 default:
890 title = null;
891 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700892 }
893
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800894 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -0400895 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700896 builder.setTicker(title);
897 builder.setContentTitle(title);
898 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700899
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700900 final Intent intent = buildNetworkOverLimitIntent(policy.template);
901 builder.setContentIntent(PendingIntent.getActivity(
902 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
903 break;
904 }
905 case TYPE_LIMIT_SNOOZED: {
906 final long overBytes = totalBytes - policy.limitBytes;
907 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
908 Formatter.formatFileSize(mContext, overBytes));
909
910 final CharSequence title;
911 switch (policy.template.getMatchRule()) {
912 case MATCH_MOBILE_3G_LOWER:
913 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
914 break;
915 case MATCH_MOBILE_4G:
916 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
917 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700918 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700919 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
920 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700921 case MATCH_WIFI:
922 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
923 break;
924 default:
925 title = null;
926 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700927 }
928
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800929 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700930 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700931 builder.setTicker(title);
932 builder.setContentTitle(title);
933 builder.setContentText(body);
934
935 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700936 builder.setContentIntent(PendingIntent.getActivity(
937 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700938 break;
939 }
940 }
941
942 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700943 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700944 try {
945 final String packageName = mContext.getPackageName();
946 final int[] idReceived = new int[1];
947 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800948 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Dianne Hackborn41203752012-08-31 14:05:51 -0700949 UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700950 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700951 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700952 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -0700953 }
954 }
955
956 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700957 * Show ongoing notification to reflect that {@link #mRestrictBackground}
958 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -0700959 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700960 private void enqueueRestrictedNotification(String tag) {
961 final Resources res = mContext.getResources();
962 final Notification.Builder builder = new Notification.Builder(mContext);
963
964 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
965 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
966
967 builder.setOnlyAlertOnce(true);
968 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700969 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700970 builder.setTicker(title);
971 builder.setContentTitle(title);
972 builder.setContentText(body);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700973 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200974 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700975
976 final Intent intent = buildAllowBackgroundDataIntent();
977 builder.setContentIntent(
978 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700979
980 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700981 // XXX what to do about multi-user?
Jeff Sharkey497e4432011-06-14 17:27:29 -0700982 try {
983 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700984 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -0800985 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Dianne Hackborn41203752012-08-31 14:05:51 -0700986 0x0, builder.getNotification(), idReceived, UserHandle.USER_OWNER);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700987 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700988 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700989 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700990 }
991 }
992
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700993 private void cancelNotification(String tag) {
994 // TODO: move to NotificationManager once we can mock it
Dianne Hackborn41203752012-08-31 14:05:51 -0700995 // XXX what to do about multi-user?
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700996 try {
997 final String packageName = mContext.getPackageName();
998 mNotifManager.cancelNotificationWithTag(
Dianne Hackborn41203752012-08-31 14:05:51 -0700999 packageName, tag, 0x0, UserHandle.USER_OWNER);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001000 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001001 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001002 }
1003 }
1004
1005 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001006 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001007 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001008 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001009 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001010 @Override
1011 public void onReceive(Context context, Intent intent) {
1012 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1013 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001014
1015 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001016 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001017 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001018 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001019 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001020 updateNetworkRulesLocked();
1021 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001022 }
1023 }
1024 };
1025
1026 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001027 * Proactively control network data connections when they exceed
1028 * {@link NetworkPolicy#limitBytes}.
1029 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001030 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001031 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1032
1033 // TODO: reset any policy-disabled networks when any policy is removed
1034 // completely, which is currently rare case.
1035
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001036 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001037 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1038 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001039 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001040 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001041 setNetworkTemplateEnabled(policy.template, true);
1042 continue;
1043 }
1044
1045 final long start = computeLastCycleBoundary(currentTime, policy);
1046 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001047 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001048
1049 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001050 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1051 && policy.lastLimitSnooze < start;
1052 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001053
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001054 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001055 }
1056 }
1057
1058 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001059 * Proactively disable networks that match the given
1060 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001061 */
1062 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001063 // TODO: reach into ConnectivityManager to proactively disable bringing
1064 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001065 }
1066
1067 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001068 * Examine all connected {@link NetworkState}, looking for
1069 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1070 * remaining quota based on usage cycle and historical stats.
1071 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001072 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001073 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001074
1075 final NetworkState[] states;
1076 try {
1077 states = mConnManager.getAllNetworkState();
1078 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001079 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001080 return;
1081 }
1082
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001083 // If we are in restrict power mode, we want to treat all interfaces
1084 // as metered, to restrict access to the network by uid. However, we
1085 // will not have a bandwidth limit. Also only do this if restrict
1086 // background data use is *not* enabled, since that takes precendence
1087 // use over those networks can have a cost associated with it).
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001088 final boolean powerSave = (mRestrictPower || mDeviceIdleMode) && !mRestrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001089
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001090 // First, generate identities of all connected networks so we can
1091 // quickly compare them against all defined policies below.
1092 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001093 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001094 for (NetworkState state : states) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001095 if (state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001096 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001097
1098 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001099 if (baseIface != null) {
1100 connIdents.add(Pair.create(baseIface, ident));
1101 if (powerSave) {
1102 connIfaces.add(baseIface);
1103 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001104 }
1105
1106 // Stacked interfaces are considered to have same identity as
1107 // their parent network.
1108 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1109 for (LinkProperties stackedLink : stackedLinks) {
1110 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001111 if (stackedIface != null) {
1112 connIdents.add(Pair.create(stackedIface, ident));
1113 if (powerSave) {
1114 connIfaces.add(stackedIface);
1115 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001116 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001117 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001118 }
1119 }
1120
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001121 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001122 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001123 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001124 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001125 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001126
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001127 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001128 for (int j = connIdents.size() - 1; j >= 0; j--) {
1129 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1130 if (policy.template.matches(ident.second)) {
1131 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001132 }
1133 }
1134
1135 if (ifaceList.size() > 0) {
1136 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001137 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001138 }
1139 }
1140
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001141 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001142 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001143
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001144 // apply each policy that we found ifaces for; compute remaining data
1145 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001146 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001147 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1148 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1149 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001150
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001151 final long start;
1152 final long totalBytes;
1153 if (policy.hasCycle()) {
1154 start = computeLastCycleBoundary(currentTime, policy);
1155 totalBytes = getTotalBytes(policy.template, start, currentTime);
1156 } else {
1157 start = Long.MAX_VALUE;
1158 totalBytes = 0;
1159 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001160
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001161 if (LOGD) {
1162 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001163 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001164 }
1165
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001166 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001167 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001168 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001169 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001170 if (!hasLimit) {
1171 // metered network, but no policy limit; we still need to
1172 // restrict apps, so push really high quota.
1173 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001174 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001175 // snoozing past quota, but we still need to restrict apps,
1176 // so push really high quota.
1177 quotaBytes = Long.MAX_VALUE;
1178 } else {
1179 // remaining "quota" bytes are based on total usage in
1180 // current cycle. kernel doesn't like 0-byte rules, so we
1181 // set 1-byte quota and disable the radio later.
1182 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1183 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001184
1185 if (ifaces.length > 1) {
1186 // TODO: switch to shared quota once NMS supports
1187 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001188 }
1189
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001190 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001191 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001192 setInterfaceQuota(iface, quotaBytes);
1193 newMeteredIfaces.add(iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001194 if (powerSave) {
1195 connIfaces.remove(iface);
1196 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001197 }
1198 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001199
1200 // keep track of lowest warning or limit of active policies
1201 if (hasWarning && policy.warningBytes < lowestRule) {
1202 lowestRule = policy.warningBytes;
1203 }
1204 if (hasLimit && policy.limitBytes < lowestRule) {
1205 lowestRule = policy.limitBytes;
1206 }
1207 }
1208
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001209 for (int i = connIfaces.size()-1; i >= 0; i--) {
1210 String iface = connIfaces.valueAt(i);
1211 removeInterfaceQuota(iface);
1212 setInterfaceQuota(iface, Long.MAX_VALUE);
1213 newMeteredIfaces.add(iface);
1214 }
1215
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001216 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001217
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001218 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001219 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1220 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001221 if (!newMeteredIfaces.contains(iface)) {
1222 removeInterfaceQuota(iface);
1223 }
1224 }
1225 mMeteredIfaces = newMeteredIfaces;
1226
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001227 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001228 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001229 }
1230
1231 /**
1232 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1233 * have at least a default mobile policy defined.
1234 */
1235 private void ensureActiveMobilePolicyLocked() {
1236 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001237 if (mSuppressDefaultPolicy) return;
1238
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001239 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001240 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001241
Jeff Sharkey32566012014-12-02 18:30:14 -08001242 final int[] subIds = sub.getActiveSubscriptionIdList();
1243 for (int subId : subIds) {
1244 final String subscriberId = tele.getSubscriberId(subId);
1245 ensureActiveMobilePolicyLocked(subscriberId);
1246 }
1247 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001248
Jeff Sharkey32566012014-12-02 18:30:14 -08001249 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1250 // Poke around to see if we already have a policy
1251 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1252 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1253 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1254 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1255 if (template.matches(probeIdent)) {
1256 if (LOGD) {
1257 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1258 + NetworkIdentity.scrubSubscriberId(subscriberId));
1259 }
1260 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001261 }
1262 }
1263
Jeff Sharkey32566012014-12-02 18:30:14 -08001264 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1265 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001266
Jeff Sharkey32566012014-12-02 18:30:14 -08001267 // Build default mobile policy, and assume usage cycle starts today
1268 final long warningBytes = mContext.getResources().getInteger(
1269 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001270
Jeff Sharkey32566012014-12-02 18:30:14 -08001271 final Time time = new Time();
1272 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001273
Jeff Sharkey32566012014-12-02 18:30:14 -08001274 final int cycleDay = time.monthDay;
1275 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001276
Jeff Sharkey32566012014-12-02 18:30:14 -08001277 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1278 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1279 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1280 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001281 }
1282
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001283 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001284 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001285
1286 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001287 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001288 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001289
1290 FileInputStream fis = null;
1291 try {
1292 fis = mPolicyFile.openRead();
1293 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001294 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001295
1296 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001297 int version = VERSION_INIT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001298 while ((type = in.next()) != END_DOCUMENT) {
1299 final String tag = in.getName();
1300 if (type == START_TAG) {
1301 if (TAG_POLICY_LIST.equals(tag)) {
1302 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001303 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1304 mRestrictBackground = readBooleanAttribute(
1305 in, ATTR_RESTRICT_BACKGROUND);
1306 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001307 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001308 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001309
1310 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1311 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1312 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001313 final String networkId;
1314 if (version >= VERSION_ADDED_NETWORK_ID) {
1315 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1316 } else {
1317 networkId = null;
1318 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001319 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001320 final String cycleTimezone;
1321 if (version >= VERSION_ADDED_TIMEZONE) {
1322 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1323 } else {
1324 cycleTimezone = Time.TIMEZONE_UTC;
1325 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001326 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1327 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001328 final long lastLimitSnooze;
1329 if (version >= VERSION_SPLIT_SNOOZE) {
1330 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1331 } else if (version >= VERSION_ADDED_SNOOZE) {
1332 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001333 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001334 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001335 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001336 final boolean metered;
1337 if (version >= VERSION_ADDED_METERED) {
1338 metered = readBooleanAttribute(in, ATTR_METERED);
1339 } else {
1340 switch (networkTemplate) {
1341 case MATCH_MOBILE_3G_LOWER:
1342 case MATCH_MOBILE_4G:
1343 case MATCH_MOBILE_ALL:
1344 metered = true;
1345 break;
1346 default:
1347 metered = false;
1348 }
1349 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001350 final long lastWarningSnooze;
1351 if (version >= VERSION_SPLIT_SNOOZE) {
1352 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1353 } else {
1354 lastWarningSnooze = SNOOZE_NEVER;
1355 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001356 final boolean inferred;
1357 if (version >= VERSION_ADDED_INFERRED) {
1358 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1359 } else {
1360 inferred = false;
1361 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001362
Jeff Sharkey32566012014-12-02 18:30:14 -08001363 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1364 subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001365 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001366 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001367 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001368
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001369 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001370 final int uid = readIntAttribute(in, ATTR_UID);
1371 final int policy = readIntAttribute(in, ATTR_POLICY);
1372
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001373 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001374 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001375 } else {
1376 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1377 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001378 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001379 final int appId = readIntAttribute(in, ATTR_APP_ID);
1380 final int policy = readIntAttribute(in, ATTR_POLICY);
1381
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001382 // TODO: set for other users during upgrade
1383 final int uid = UserHandle.getUid(UserHandle.USER_OWNER, appId);
1384 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001385 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001386 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001387 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001388 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001389 }
1390 }
1391 }
1392
1393 } catch (FileNotFoundException e) {
1394 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001395 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001396 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001397 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001398 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001399 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001400 } finally {
1401 IoUtils.closeQuietly(fis);
1402 }
1403 }
1404
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001405 /**
1406 * Upgrade legacy background data flags, notifying listeners of one last
1407 * change to always-true.
1408 */
1409 private void upgradeLegacyBackgroundData() {
1410 mRestrictBackground = Settings.Secure.getInt(
1411 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1412
1413 // kick off one last broadcast if restricted
1414 if (mRestrictBackground) {
1415 final Intent broadcast = new Intent(
1416 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001417 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001418 }
1419 }
1420
Dianne Hackborn497175b2014-07-01 12:56:08 -07001421 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001422 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001423
1424 FileOutputStream fos = null;
1425 try {
1426 fos = mPolicyFile.startWrite();
1427
1428 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001429 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001430 out.startDocument(null, true);
1431
1432 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001433 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001434 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001435
1436 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001437 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1438 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001439 final NetworkTemplate template = policy.template;
1440
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001441 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001442 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1443 final String subscriberId = template.getSubscriberId();
1444 if (subscriberId != null) {
1445 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001446 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001447 final String networkId = template.getNetworkId();
1448 if (networkId != null) {
1449 out.attribute(null, ATTR_NETWORK_ID, networkId);
1450 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001451 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001452 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001453 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1454 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001455 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1456 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001457 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001458 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001459 out.endTag(null, TAG_NETWORK_POLICY);
1460 }
1461
1462 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001463 for (int i = 0; i < mUidPolicy.size(); i++) {
1464 final int uid = mUidPolicy.keyAt(i);
1465 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001466
Jeff Sharkey497e4432011-06-14 17:27:29 -07001467 // skip writing empty policies
1468 if (policy == POLICY_NONE) continue;
1469
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001470 out.startTag(null, TAG_UID_POLICY);
1471 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001472 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001473 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001474 }
1475
1476 out.endTag(null, TAG_POLICY_LIST);
1477 out.endDocument();
1478
1479 mPolicyFile.finishWrite(fos);
1480 } catch (IOException e) {
1481 if (fos != null) {
1482 mPolicyFile.failWrite(fos);
1483 }
1484 }
1485 }
1486
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001487 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001488 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001489 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001490
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001491 if (!UserHandle.isApp(uid)) {
1492 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001493 }
1494
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001495 synchronized (mRulesLock) {
1496 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1497 if (oldPolicy != policy) {
1498 setUidPolicyUncheckedLocked(uid, policy, true);
1499 }
1500 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001501 }
1502
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001503 @Override
1504 public void addUidPolicy(int uid, int policy) {
1505 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001506
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001507 if (!UserHandle.isApp(uid)) {
1508 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1509 }
1510
1511 synchronized (mRulesLock) {
1512 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1513 policy |= oldPolicy;
1514 if (oldPolicy != policy) {
1515 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001516 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001517 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001518 }
1519
1520 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001521 public void removeUidPolicy(int uid, int policy) {
1522 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1523
1524 if (!UserHandle.isApp(uid)) {
1525 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1526 }
1527
1528 synchronized (mRulesLock) {
1529 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1530 policy = oldPolicy & ~policy;
1531 if (oldPolicy != policy) {
1532 setUidPolicyUncheckedLocked(uid, policy, true);
1533 }
1534 }
1535 }
1536
1537 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1538 mUidPolicy.put(uid, policy);
1539
1540 // uid policy changed, recompute rules and persist policy.
1541 updateRulesForUidLocked(uid);
1542 if (persist) {
1543 writePolicyLocked();
1544 }
1545 }
1546
1547 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001548 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001549 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1550
Jeff Sharkeya4620792011-05-20 15:29:23 -07001551 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001552 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001553 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001554 }
1555
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001556 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001557 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001558 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1559
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001560 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001561 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001562 for (int i = 0; i < mUidPolicy.size(); i++) {
1563 final int uid = mUidPolicy.keyAt(i);
1564 final int uidPolicy = mUidPolicy.valueAt(i);
1565 if (uidPolicy == policy) {
1566 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001567 }
1568 }
1569 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001570 return uids;
1571 }
1572
1573 /**
1574 * Remove any policies associated with given {@link UserHandle}, persisting
1575 * if any changes are made.
1576 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001577 void removePoliciesForUserLocked(int userId) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001578 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1579
1580 int[] uids = new int[0];
1581 for (int i = 0; i < mUidPolicy.size(); i++) {
1582 final int uid = mUidPolicy.keyAt(i);
1583 if (UserHandle.getUserId(uid) == userId) {
1584 uids = appendInt(uids, uid);
1585 }
1586 }
1587
1588 if (uids.length > 0) {
1589 for (int uid : uids) {
1590 mUidPolicy.delete(uid);
1591 updateRulesForUidLocked(uid);
1592 }
1593 writePolicyLocked();
1594 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001595 }
1596
1597 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001598 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001599 // TODO: create permission for observing network policy
1600 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1601
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001602 mListeners.register(listener);
1603
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001604 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001605 }
1606
1607 @Override
1608 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001609 // TODO: create permission for observing network policy
1610 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1611
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001612 mListeners.unregister(listener);
1613 }
1614
Jeff Sharkey1b861272011-05-22 00:34:52 -07001615 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001616 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001617 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1618
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001619 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001620 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001621 normalizePoliciesLocked(policies);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001622 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001623 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001624 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001625 writePolicyLocked();
1626 }
1627 }
1628
Dianne Hackborn497175b2014-07-01 12:56:08 -07001629 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001630 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001631 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1632 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001633 }
1634
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001635 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001636 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001637 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001638 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001639
Svet Ganov16a16892015-04-16 10:32:04 -07001640 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1641 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1642 return new NetworkPolicy[0];
1643 }
1644
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001645 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001646 final int size = mNetworkPolicy.size();
1647 final NetworkPolicy[] policies = new NetworkPolicy[size];
1648 for (int i = 0; i < size; i++) {
1649 policies[i] = mNetworkPolicy.valueAt(i);
1650 }
1651 return policies;
1652 }
1653 }
1654
1655 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001656 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001657 }
1658
1659 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1660 final TelephonyManager tele = TelephonyManager.from(mContext);
1661 final String[] merged = tele.getMergedSubscriberIds();
1662
1663 mNetworkPolicy.clear();
1664 for (NetworkPolicy policy : policies) {
1665 // When two normalized templates conflict, prefer the most
1666 // restrictive policy
1667 policy.template = NetworkTemplate.normalize(policy.template, merged);
1668 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1669 if (existing == null || existing.compareTo(policy) > 0) {
1670 if (existing != null) {
1671 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1672 }
1673 mNetworkPolicy.put(policy.template, policy);
1674 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001675 }
1676 }
1677
1678 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001679 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001680 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001681
1682 final long token = Binder.clearCallingIdentity();
1683 try {
1684 performSnooze(template, TYPE_LIMIT);
1685 } finally {
1686 Binder.restoreCallingIdentity(token);
1687 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001688 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001689
Dianne Hackborn497175b2014-07-01 12:56:08 -07001690 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001691 maybeRefreshTrustedTime();
1692 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001693 synchronized (mRulesLock) {
1694 // find and snooze local policy that matches
1695 final NetworkPolicy policy = mNetworkPolicy.get(template);
1696 if (policy == null) {
1697 throw new IllegalArgumentException("unable to find policy for " + template);
1698 }
1699
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001700 switch (type) {
1701 case TYPE_WARNING:
1702 policy.lastWarningSnooze = currentTime;
1703 break;
1704 case TYPE_LIMIT:
1705 policy.lastLimitSnooze = currentTime;
1706 break;
1707 default:
1708 throw new IllegalArgumentException("unexpected type");
1709 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001710
Jeff Sharkey32566012014-12-02 18:30:14 -08001711 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001712 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001713 updateNetworkRulesLocked();
1714 updateNotificationsLocked();
1715 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001716 }
1717 }
1718
1719 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001720 public void setRestrictBackground(boolean restrictBackground) {
1721 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1722
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001723 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001724 synchronized (mRulesLock) {
1725 mRestrictBackground = restrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001726 updateRulesForGlobalChangeLocked(false);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001727 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001728 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001729 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001730
1731 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1732 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001733 }
1734
1735 @Override
1736 public boolean getRestrictBackground() {
1737 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1738
1739 synchronized (mRulesLock) {
1740 return mRestrictBackground;
1741 }
1742 }
1743
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001744 @Override
1745 public void setDeviceIdleMode(boolean enabled) {
1746 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1747
1748 synchronized (mRulesLock) {
1749 if (mDeviceIdleMode != enabled) {
1750 mDeviceIdleMode = enabled;
1751 if (mSystemReady) {
1752 updateRulesForGlobalChangeLocked(true);
1753 }
1754 }
1755 }
1756 }
1757
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001758 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001759 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1760 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001761 if (policy.template.matches(ident)) {
1762 return policy;
1763 }
1764 }
1765 return null;
1766 }
1767
1768 @Override
1769 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1770 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1771
1772 // only returns usage summary, so we don't require caller to have
1773 // READ_NETWORK_USAGE_HISTORY.
1774 final long token = Binder.clearCallingIdentity();
1775 try {
1776 return getNetworkQuotaInfoUnchecked(state);
1777 } finally {
1778 Binder.restoreCallingIdentity(token);
1779 }
1780 }
1781
1782 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1783 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1784
1785 final NetworkPolicy policy;
1786 synchronized (mRulesLock) {
1787 policy = findPolicyForNetworkLocked(ident);
1788 }
1789
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001790 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001791 // missing policy means we can't derive useful quota info
1792 return null;
1793 }
1794
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001795 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001796
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001797 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001798 final long start = computeLastCycleBoundary(currentTime, policy);
1799 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001800 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001801
1802 // report soft and hard limits under policy
1803 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1804 : NetworkQuotaInfo.NO_LIMIT;
1805 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1806 : NetworkQuotaInfo.NO_LIMIT;
1807
1808 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1809 }
1810
Jeff Sharkey46645002011-07-27 21:11:21 -07001811 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001812 public boolean isNetworkMetered(NetworkState state) {
1813 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1814
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001815 // roaming networks are always considered metered
1816 if (ident.getRoaming()) {
1817 return true;
1818 }
1819
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001820 final NetworkPolicy policy;
1821 synchronized (mRulesLock) {
1822 policy = findPolicyForNetworkLocked(ident);
1823 }
1824
1825 if (policy != null) {
1826 return policy.metered;
1827 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001828 final int type = state.networkInfo.getType();
1829 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
1830 return true;
1831 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001832 return false;
1833 }
1834 }
1835
1836 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001837 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07001838 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001839
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001840 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
1841
Dianne Hackborn497175b2014-07-01 12:56:08 -07001842 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001843 for (String arg : args) {
1844 argSet.add(arg);
1845 }
1846
Jeff Sharkey1b861272011-05-22 00:34:52 -07001847 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001848 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001849 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1850 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001851 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001852
Jeff Sharkey32566012014-12-02 18:30:14 -08001853 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001854 updateNetworkEnabledLocked();
1855 updateNetworkRulesLocked();
1856 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001857 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001858
1859 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001860 return;
1861 }
1862
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001863 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07001864 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001865 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001866 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001867 fout.print("Current foreground state: "); fout.println(mCurForegroundState);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001868 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001869 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001870 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1871 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001872 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001873 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001874
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001875 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
1876
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001877 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001878 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001879 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001880 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001881 final int uid = mUidPolicy.keyAt(i);
1882 final int policy = mUidPolicy.valueAt(i);
1883 fout.print("UID=");
1884 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001885 fout.print(" policy=");
1886 dumpPolicy(fout, policy);
1887 fout.println();
1888 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001889 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001890
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001891 size = mPowerSaveWhitelistAppIds.size();
1892 if (size > 0) {
1893 fout.println("Power save whitelist app ids:");
1894 fout.increaseIndent();
1895 for (int i = 0; i < size; i++) {
1896 fout.print("UID=");
1897 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
1898 fout.print(": ");
1899 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
1900 fout.println();
1901 }
1902 fout.decreaseIndent();
1903 }
1904
Jeff Sharkey1b861272011-05-22 00:34:52 -07001905 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07001906 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07001907 collectKeys(mUidRules, knownUids);
1908
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001909 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001910 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001911 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001912 for (int i = 0; i < size; i++) {
1913 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001914 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07001915 fout.print(uid);
1916
Dianne Hackborn497175b2014-07-01 12:56:08 -07001917 int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1918 fout.print(" state=");
1919 fout.print(state);
1920 fout.print(state <= mCurForegroundState ? " (fg)" : " (bg)");
1921
Jeff Sharkey1b861272011-05-22 00:34:52 -07001922 fout.print(" rules=");
1923 final int rulesIndex = mUidRules.indexOfKey(uid);
1924 if (rulesIndex < 0) {
1925 fout.print("UNKNOWN");
1926 } else {
1927 dumpRules(fout, mUidRules.valueAt(rulesIndex));
1928 }
1929
1930 fout.println();
1931 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001932 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07001933 }
1934 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001935
1936 @Override
1937 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001938 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1939
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001940 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001941 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07001942 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001943 }
1944
Dianne Hackborn497175b2014-07-01 12:56:08 -07001945 boolean isUidForegroundLocked(int uid) {
1946 // only really in foreground when screen is also on
1947 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
1948 <= mCurForegroundState;
1949 }
1950
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001951 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07001952 * Process state of UID changed; if needed, will trigger
1953 * {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001954 */
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07001955 void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07001956 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
1957 if (oldUidState != uidState) {
1958 // state changed, push updated rules
1959 mUidState.put(uid, uidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07001960 updateRulesForUidStateChangeLocked(uid, oldUidState, uidState);
1961 }
1962 }
1963
1964 void removeUidStateLocked(int uid) {
1965 final int index = mUidState.indexOfKey(uid);
1966 if (index >= 0) {
1967 final int oldUidState = mUidState.valueAt(index);
1968 mUidState.removeAt(index);
1969 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
1970 updateRulesForUidStateChangeLocked(uid, oldUidState,
1971 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001972 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001973 }
1974 }
1975
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07001976 void updateRulesForUidStateChangeLocked(int uid, int oldUidState, int newUidState) {
1977 final boolean oldForeground = oldUidState <= mCurForegroundState;
1978 final boolean newForeground = newUidState <= mCurForegroundState;
1979 if (oldForeground != newForeground) {
1980 updateRulesForUidLocked(uid);
1981 }
1982 }
1983
Jeff Sharkeya4620792011-05-20 15:29:23 -07001984 private void updateScreenOn() {
1985 synchronized (mRulesLock) {
1986 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07001987 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001988 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001989 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07001990 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001991 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07001992 }
1993 }
1994
1995 /**
1996 * Update rules that might be changed by {@link #mScreenOn} value.
1997 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001998 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07001999 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002000 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002001 for (int i = 0; i < size; i++) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002002 if (mUidState.valueAt(i) <= mCurForegroundState) {
2003 final int uid = mUidState.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002004 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002005 }
2006 }
2007 }
2008
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002009 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002010 * Update rules that might be changed by {@link #mRestrictBackground},
2011 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002012 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002013 void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002014 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002015
Dianne Hackborn497175b2014-07-01 12:56:08 -07002016 // If we are in restrict power mode, we allow all important apps
2017 // to have data access. Otherwise, we restrict data access to only
2018 // the top apps.
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002019 mCurForegroundState = (!mRestrictBackground && (mRestrictPower || mDeviceIdleMode))
Dianne Hackbornd69e4c12015-04-24 09:54:54 -07002020 ? ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
Dianne Hackborn497175b2014-07-01 12:56:08 -07002021 : ActivityManager.PROCESS_STATE_TOP;
2022
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002023 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002024 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002025 final List<ApplicationInfo> apps = pm.getInstalledApplications(
2026 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS);
2027
2028 for (UserInfo user : users) {
2029 for (ApplicationInfo app : apps) {
2030 final int uid = UserHandle.getUid(user.id, app.uid);
2031 updateRulesForUidLocked(uid);
2032 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002033 }
2034
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002035 // limit data usage for some internal system services
2036 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
2037 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002038
2039 // If the set of restricted networks may have changed, re-evaluate those.
2040 if (restrictedNetworksChanged) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002041 normalizePoliciesLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002042 updateNetworkRulesLocked();
2043 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002044 }
2045
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002046 void updateRulesForTempWhitelistChangeLocked() {
2047 final List<UserInfo> users = mUserManager.getUsers();
2048 for (UserInfo user : users) {
2049 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
2050 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2051 int uid = UserHandle.getUid(user.id, appId);
2052 updateRulesForUidLocked(uid);
2053 }
2054 }
2055 }
2056
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002057 private static boolean isUidValidForRules(int uid) {
2058 // allow rules on specific system services, and any apps
2059 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002060 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002061 return true;
2062 }
2063
2064 return false;
2065 }
2066
Amith Yamasani15e472352015-04-24 19:06:07 -07002067 private boolean isUidIdle(int uid) {
2068 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2069 final int userId = UserHandle.getUserId(uid);
2070
2071 for (String packageName : packages) {
2072 if (!mUsageStats.isAppIdle(packageName, userId)) {
2073 return false;
2074 }
2075 }
2076 return true;
2077 }
2078
2079 /**
2080 * Applies network rules to bandwidth and firewall controllers based on uid policy.
2081 * @param uid The uid for which to apply the latest policy
2082 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002083 void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002084 if (!isUidValidForRules(uid)) return;
2085
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002086 // quick check: if this uid doesn't have INTERNET permission, it doesn't have
2087 // network access anyway, so it is a waste to mess with it here.
2088 final IPackageManager ipm = AppGlobals.getPackageManager();
2089 try {
2090 if (ipm.checkUidPermission(Manifest.permission.INTERNET, uid)
2091 != PackageManager.PERMISSION_GRANTED) {
2092 return;
2093 }
2094 } catch (RemoteException e) {
2095 }
2096
Dianne Hackborn497175b2014-07-01 12:56:08 -07002097 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2098 final boolean uidForeground = isUidForegroundLocked(uid);
Amith Yamasani15e472352015-04-24 19:06:07 -07002099 final boolean uidIdle = isUidIdle(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002100
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002101 // derive active rules based on policy and active state
Amith Yamasani15e472352015-04-24 19:06:07 -07002102
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002103 int appId = UserHandle.getAppId(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002104 int uidRules = RULE_ALLOW_ALL;
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002105 if (uidIdle && !mPowerSaveWhitelistAppIds.get(appId)
2106 && !mPowerSaveTempWhitelistAppIds.get(appId)) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002107 uidRules = RULE_REJECT_ALL;
2108 } else if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002109 // uid in background, and policy says to block metered data
2110 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002111 } else if (mRestrictBackground) {
2112 if (!uidForeground) {
2113 // uid in background, and global background disabled
2114 uidRules = RULE_REJECT_METERED;
2115 }
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002116 } else if (mRestrictPower || mDeviceIdleMode) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002117 final boolean whitelisted = mPowerSaveWhitelistAppIds.get(appId)
2118 || mPowerSaveTempWhitelistAppIds.get(appId);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002119 if (!whitelisted && !uidForeground
2120 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
2121 // uid is in background, restrict power use mode is on (so we want to
2122 // restrict all background network access), and this uid is not on the
2123 // white list of those allowed background access.
2124 uidRules = RULE_REJECT_METERED;
2125 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002126 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002127
Amith Yamasani15e472352015-04-24 19:06:07 -07002128 final int oldRules = mUidRules.get(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002129
Jeff Sharkey350083e2011-06-29 10:45:16 -07002130 if (uidRules == RULE_ALLOW_ALL) {
2131 mUidRules.delete(uid);
2132 } else {
2133 mUidRules.put(uid, uidRules);
2134 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002135
Amith Yamasani15e472352015-04-24 19:06:07 -07002136 // Update bandwidth rules if necessary
2137 final boolean oldRejectMetered = (oldRules & RULE_REJECT_METERED) != 0;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002138 final boolean rejectMetered = (uidRules & RULE_REJECT_METERED) != 0;
Amith Yamasani15e472352015-04-24 19:06:07 -07002139 if (oldRejectMetered != rejectMetered) {
2140 setUidNetworkRules(uid, rejectMetered);
2141 }
2142
2143 // Update firewall rules if necessary
2144 final boolean oldFirewallReject = (oldRules & RULE_REJECT_ALL) != 0;
2145 final boolean firewallReject = (uidRules & RULE_REJECT_ALL) != 0;
2146 if (oldFirewallReject != firewallReject) {
2147 setUidFirewallRules(uid, firewallReject);
2148 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002149
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002150 // dispatch changed rule to existing listeners
Amith Yamasani15e472352015-04-24 19:06:07 -07002151 if (oldRules != uidRules) {
2152 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
2153 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002154
2155 try {
2156 // adjust stats accounting based on foreground status
2157 mNetworkStats.setUidForeground(uid, uidForeground);
2158 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002159 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002160 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002161 }
2162
Amith Yamasani15e472352015-04-24 19:06:07 -07002163 @Override
2164 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2165 try {
2166 int uid = mContext.getPackageManager().getPackageUid(packageName, userId);
2167 synchronized (mRulesLock) {
2168 updateRulesForUidLocked(uid);
2169 }
2170 } catch (NameNotFoundException nnfe) {
2171 return;
2172 }
2173 }
2174
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002175 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002176 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002177 public boolean handleMessage(Message msg) {
2178 switch (msg.what) {
2179 case MSG_RULES_CHANGED: {
2180 final int uid = msg.arg1;
2181 final int uidRules = msg.arg2;
2182 final int length = mListeners.beginBroadcast();
2183 for (int i = 0; i < length; i++) {
2184 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2185 if (listener != null) {
2186 try {
2187 listener.onUidRulesChanged(uid, uidRules);
2188 } catch (RemoteException e) {
2189 }
2190 }
2191 }
2192 mListeners.finishBroadcast();
2193 return true;
2194 }
2195 case MSG_METERED_IFACES_CHANGED: {
2196 final String[] meteredIfaces = (String[]) msg.obj;
2197 final int length = mListeners.beginBroadcast();
2198 for (int i = 0; i < length; i++) {
2199 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2200 if (listener != null) {
2201 try {
2202 listener.onMeteredIfacesChanged(meteredIfaces);
2203 } catch (RemoteException e) {
2204 }
2205 }
2206 }
2207 mListeners.finishBroadcast();
2208 return true;
2209 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002210 case MSG_LIMIT_REACHED: {
2211 final String iface = (String) msg.obj;
2212
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002213 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002214 synchronized (mRulesLock) {
2215 if (mMeteredIfaces.contains(iface)) {
2216 try {
2217 // force stats update to make sure we have
2218 // numbers that caused alert to trigger.
2219 mNetworkStats.forceUpdate();
2220 } catch (RemoteException e) {
2221 // ignored; service lives in system_server
2222 }
2223
2224 updateNetworkEnabledLocked();
2225 updateNotificationsLocked();
2226 }
2227 }
2228 return true;
2229 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002230 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2231 final boolean restrictBackground = msg.arg1 != 0;
2232 final int length = mListeners.beginBroadcast();
2233 for (int i = 0; i < length; i++) {
2234 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2235 if (listener != null) {
2236 try {
2237 listener.onRestrictBackgroundChanged(restrictBackground);
2238 } catch (RemoteException e) {
2239 }
2240 }
2241 }
2242 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002243 return true;
2244 }
2245 case MSG_ADVISE_PERSIST_THRESHOLD: {
2246 final long lowestRule = (Long) msg.obj;
2247 try {
2248 // make sure stats are recorded frequently enough; we aim
2249 // for 2MB threshold for 2GB/month rules.
2250 final long persistThreshold = lowestRule / 1000;
2251 mNetworkStats.advisePersistThreshold(persistThreshold);
2252 } catch (RemoteException e) {
2253 // ignored; service lives in system_server
2254 }
2255 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002256 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002257 case MSG_SCREEN_ON_CHANGED: {
2258 updateScreenOn();
2259 return true;
2260 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002261 default: {
2262 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002263 }
2264 }
2265 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002266 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002267
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002268 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002269 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002270 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002271 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002272 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002273 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002274 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002275 }
2276 }
2277
2278 private void removeInterfaceQuota(String iface) {
2279 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002280 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002281 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002282 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002283 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002284 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002285 }
2286 }
2287
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002288 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2289 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002290 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002291 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002292 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002293 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002294 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002295 }
2296 }
2297
Amith Yamasani15e472352015-04-24 19:06:07 -07002298 /**
2299 * Add or remove a uid to the firewall blacklist for all network ifaces.
2300 * @param uid
2301 * @param rejectOnAll
2302 */
2303 private void setUidFirewallRules(int uid, boolean rejectOnAll) {
2304 try {
2305 mNetworkManager.setFirewallUidRule(uid,
2306 rejectOnAll ? FIREWALL_RULE_DENY : FIREWALL_RULE_DEFAULT);
2307 } catch (IllegalStateException e) {
2308 Log.wtf(TAG, "problem setting firewall uid rules", e);
2309 } catch (RemoteException e) {
2310 // ignored; service lives in system_server
2311 }
2312 }
2313
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002314 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2315 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002316 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002317 } catch (RuntimeException e) {
2318 Slog.w(TAG, "problem reading network stats: " + e);
2319 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002320 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002321 // ignored; service lives in system_server
2322 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002323 }
2324 }
2325
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002326 private boolean isBandwidthControlEnabled() {
2327 final long token = Binder.clearCallingIdentity();
2328 try {
2329 return mNetworkManager.isBandwidthControlEnabled();
2330 } catch (RemoteException e) {
2331 // ignored; service lives in system_server
2332 return false;
2333 } finally {
2334 Binder.restoreCallingIdentity(token);
2335 }
2336 }
2337
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002338 /**
2339 * Try refreshing {@link #mTime} when stale.
2340 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002341 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002342 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002343 mTime.forceRefresh();
2344 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002345 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002346
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002347 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002348 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2349 }
2350
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002351 private static Intent buildAllowBackgroundDataIntent() {
2352 return new Intent(ACTION_ALLOW_BACKGROUND);
2353 }
2354
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002355 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2356 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2357 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2358 return intent;
2359 }
2360
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002361 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2362 final Intent intent = new Intent();
2363 intent.setComponent(new ComponentName(
2364 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2365 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2366 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2367 return intent;
2368 }
2369
2370 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2371 final Intent intent = new Intent();
2372 intent.setComponent(new ComponentName(
2373 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2374 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2375 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2376 return intent;
2377 }
2378
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002379 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002380 public void addIdleHandler(IdleHandler handler) {
2381 mHandler.getLooper().getQueue().addIdleHandler(handler);
2382 }
2383
Jeff Sharkey1b861272011-05-22 00:34:52 -07002384 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2385 final int size = source.size();
2386 for (int i = 0; i < size; i++) {
2387 target.put(source.keyAt(i), true);
2388 }
2389 }
2390
Stuart Scottf1fb3972015-04-02 18:00:02 -07002391 @Override
2392 public void factoryReset(String subscriber) {
2393 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2394
Stuart Scotte3e314d2015-04-20 14:07:45 -07002395 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
2396 return;
2397 }
2398
Stuart Scottf1fb3972015-04-02 18:00:02 -07002399 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07002400 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07002401 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
2402 for (NetworkPolicy policy : policies) {
2403 if (policy.template.equals(template)) {
2404 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2405 policy.inferred = false;
2406 policy.clearSnooze();
2407 }
2408 }
2409 setNetworkPolicies(policies);
2410
2411 // Turn restrict background data off
2412 setRestrictBackground(false);
2413
Stuart Scotte3e314d2015-04-20 14:07:45 -07002414 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
2415 // Remove app's "restrict background data" flag
2416 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
2417 setUidPolicy(uid, POLICY_NONE);
2418 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07002419 }
2420 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002421}