blob: 0bb7429884a41a780df1b52915960e156840e4e8 [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;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Felipe Lemea9505cc2016-02-26 10:28:41 -080031
Erik Klinef851d6d2015-04-20 16:03:48 +090032import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070033import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070034import static android.net.ConnectivityManager.TYPE_WIMAX;
Felipe Leme1b103232016-01-22 09:44:57 -080035import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
36import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
37import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070038import static android.net.ConnectivityManager.isNetworkTypeMobile;
39import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070040import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070041import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070042import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070043import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070044import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080045import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070046import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
47import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070048import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070049import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -070050import static android.net.NetworkPolicyManager.POLICY_ALLOW_BACKGROUND_BATTERY_SAVE;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070051import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070052import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070053import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeydc988062015-09-14 10:09:47 -070054import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070055import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeydc988062015-09-14 10:09:47 -070056import static android.net.NetworkPolicyManager.RULE_UNKNOWN;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070057import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070058import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
59import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070060import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
61import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070062import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080063import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070064import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
65import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
66import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
67import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
68import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
69import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
70import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070071import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080072
Jeff Sharkey854b2b12012-04-13 16:03:40 -070073import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070074import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070075import static com.android.internal.util.XmlUtils.readBooleanAttribute;
76import static com.android.internal.util.XmlUtils.readIntAttribute;
77import static com.android.internal.util.XmlUtils.readLongAttribute;
78import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
79import static com.android.internal.util.XmlUtils.writeIntAttribute;
80import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070081import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070082import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070083import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080084import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070085import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070086
Dianne Hackborn88e98df2015-03-23 13:29:14 -070087import android.Manifest;
Dianne Hackborn497175b2014-07-01 12:56:08 -070088import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070089import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070090import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070091import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070092import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070093import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070094import android.app.Notification;
95import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -070096import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -070097import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070098import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070099import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700100import android.content.Intent;
101import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700102import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700103import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700104import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700105import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700106import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700107import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700108import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700109import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700110import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700111import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700112import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700113import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700114import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700115import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700116import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700117import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700118import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700119import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700120import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700121import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700122import android.net.wifi.WifiConfiguration;
123import android.net.wifi.WifiInfo;
124import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700125import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700126import android.os.Environment;
127import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700128import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700129import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700130import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700131import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700132import android.os.Message;
Felipe Leme50a235e2016-01-15 18:37:06 -0800133import android.os.ResultReceiver;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700134import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700135import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700136import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700137import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700138import android.os.RemoteException;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700139import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700140import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700141import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700142import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800143import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700144import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700145import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700146import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700147import android.util.ArrayMap;
148import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700149import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700150import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700151import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700152import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700153import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700154import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700155import android.util.SparseBooleanArray;
156import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700157import android.util.TrustedTime;
158import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700159
Jeff Sharkey32566012014-12-02 18:30:14 -0800160import libcore.io.IoUtils;
161
Jeff Sharkey497e4432011-06-14 17:27:29 -0700162import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800163import com.android.internal.annotations.VisibleForTesting;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800164import com.android.internal.content.PackageMonitor;
Jeff Sharkey32566012014-12-02 18:30:14 -0800165import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700166import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700167import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700168import com.android.server.DeviceIdleController;
169import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700170import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800171import com.android.server.SystemConfig;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700172import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700173
174import org.xmlpull.v1.XmlPullParser;
175import org.xmlpull.v1.XmlPullParserException;
176import org.xmlpull.v1.XmlSerializer;
177
178import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700179import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700180import java.io.FileInputStream;
181import java.io.FileNotFoundException;
182import java.io.FileOutputStream;
183import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700184import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100185import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700186import java.util.ArrayList;
187import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700188import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700189
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700190/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700191 * Service that maintains low-level network policy rules, using
192 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700193 * <p>
194 * Derives active rules by combining a given policy with other system status,
195 * and delivers to listeners, such as {@link ConnectivityManager}, for
196 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700197 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700198public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800199 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700200 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700201 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700202
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700203 private static final int VERSION_INIT = 1;
204 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700205 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800206 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800207 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800208 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700209 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700210 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700211 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700212 private static final int VERSION_SWITCH_UID = 10;
213 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700214
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800215 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700216 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800217 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700218 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800219 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700220 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700221
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700222 private static final String TAG_POLICY_LIST = "policy-list";
223 private static final String TAG_NETWORK_POLICY = "network-policy";
224 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700225 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800226 private static final String TAG_WHITELIST = "whitelist";
227 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800228 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700229
230 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700231 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700232 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
233 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700234 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700235 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800236 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700237 private static final String ATTR_WARNING_BYTES = "warningBytes";
238 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700239 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800240 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
241 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800242 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700243 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700244 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700245 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700246 private static final String ATTR_POLICY = "policy";
247
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800248 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800249 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800250 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800251 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700252
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700253 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
254
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700255 private static final int MSG_RULES_CHANGED = 1;
256 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800257 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800258 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700259 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700260 private static final int MSG_SCREEN_ON_CHANGED = 8;
Felipe Leme9778f762016-01-27 14:46:39 -0800261 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700262
Jeff Sharkey75279902011-05-24 18:39:45 -0700263 private final Context mContext;
264 private final IActivityManager mActivityManager;
265 private final IPowerManager mPowerManager;
266 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700267 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700268 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700269 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700270 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700271
272 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700273 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700274 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700275 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700276
Dianne Hackborn497175b2014-07-01 12:56:08 -0700277 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700278
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700279 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700280 volatile boolean mScreenOn;
281 volatile boolean mRestrictBackground;
282 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700283 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700284
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700285 private final boolean mSuppressDefaultPolicy;
286
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700287 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800288 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700289 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800290 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700291
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700292 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700293 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700294 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800295 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700296
Jeff Sharkeydc988062015-09-14 10:09:47 -0700297 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
298 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800299 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700300
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700301 /** Set of states for the child firewall chains. True if the chain is active. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700302 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
303
Jeff Sharkey32566012014-12-02 18:30:14 -0800304 /**
305 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700306 * in power save mode, except device idle (doze) still applies.
307 * TODO: An int array might be sufficient
308 */
309 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
310
311 /**
312 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800313 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700314 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800315 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700316 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700317
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700318 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
319
Felipe Lemeb85a6372016-01-14 16:16:16 -0800320 /**
321 * UIDs that have been white-listed to avoid restricted background.
322 */
323 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
324
Felipe Lemea9505cc2016-02-26 10:28:41 -0800325 /**
326 * UIDs that have been initially white-listed by system to avoid restricted background.
327 */
328 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
329 new SparseBooleanArray();
330
331 /**
332 * UIDs that have been initially white-listed by system to avoid restricted background,
333 * but later revoked by user.
334 */
335 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
336 new SparseBooleanArray();
337
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700338 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800339 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700340 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800341 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700342
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700343 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700344 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700345
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700346 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800347 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700348
Jeff Sharkey32566012014-12-02 18:30:14 -0800349 private final RemoteCallbackList<INetworkPolicyListener>
350 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700351
Dianne Hackborn497175b2014-07-01 12:56:08 -0700352 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700353
354 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700355
Svet Ganov16a16892015-04-16 10:32:04 -0700356 private final AppOpsManager mAppOps;
357
Felipe Lemeb85a6372016-01-14 16:16:16 -0800358 private final MyPackageMonitor mPackageMonitor;
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800359 private final IPackageManager mIPm;
360
Felipe Lemeb85a6372016-01-14 16:16:16 -0800361
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700362 // TODO: keep whitelist of system-critical services that should never have
363 // rules enforced, such as system, phone, and radio UIDs.
364
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700365 // TODO: migrate notifications to SystemUI
366
Jeff Sharkey75279902011-05-24 18:39:45 -0700367 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700368 IPowerManager powerManager, INetworkStatsService networkStats,
369 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700370 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700371 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700372 }
373
374 private static File getSystemDir() {
375 return new File(Environment.getDataDirectory(), "system");
376 }
377
378 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700379 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700380 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
381 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700382 mContext = checkNotNull(context, "missing context");
383 mActivityManager = checkNotNull(activityManager, "missing activityManager");
384 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700385 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700386 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700387 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700388 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700389 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700390 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800391 mIPm = AppGlobals.getPackageManager();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700392
Amith Yamasani450a16b2013-09-18 16:28:50 -0700393 HandlerThread thread = new HandlerThread(TAG);
394 thread.start();
395 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700396
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700397 mSuppressDefaultPolicy = suppressDefaultPolicy;
398
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700399 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700400
401 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800402
403 mPackageMonitor = new MyPackageMonitor();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700404 }
405
406 public void bindConnectivityManager(IConnectivityManager connManager) {
407 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700408 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700409
Jeff Sharkey497e4432011-06-14 17:27:29 -0700410 public void bindNotificationManager(INotificationManager notifManager) {
411 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
412 }
413
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700414 void updatePowerSaveWhitelistLocked() {
415 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700416 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
417 mPowerSaveWhitelistExceptIdleAppIds.clear();
418 if (whitelist != null) {
419 for (int uid : whitelist) {
420 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
421 }
422 }
423 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700424 mPowerSaveWhitelistAppIds.clear();
425 if (whitelist != null) {
426 for (int uid : whitelist) {
427 mPowerSaveWhitelistAppIds.put(uid, true);
428 }
429 }
430 } catch (RemoteException e) {
431 }
432 }
433
Felipe Lemea9505cc2016-02-26 10:28:41 -0800434 /**
435 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
436 * revoke the whitelist.
437 *
438 * @return whether any uid has been added to {@link #mRestrictBackgroundWhitelistUids}.
439 */
440 boolean addDefaultRestrictBackgroundWhitelistUids() {
441 final SystemConfig sysConfig = SystemConfig.getInstance();
442 final PackageManager pm = mContext.getPackageManager();
443 final List<UserInfo> users = mUserManager.getUsers();
444 final int numberUsers = users.size();
445
446 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
447 boolean changed = false;
448 for (int i = 0; i < allowDataUsage.size(); i++) {
449 final String pkg = allowDataUsage.valueAt(i);
450 if (LOGD)
451 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg);
452 final ApplicationInfo app;
453 try {
454 app = pm.getApplicationInfo(pkg, PackageManager.MATCH_SYSTEM_ONLY);
455 } catch (PackageManager.NameNotFoundException e) {
456 // Should not happen
457 Slog.wtf(TAG, "No ApplicationInfo for package " + pkg);
458 continue;
459 }
460 if (!app.isPrivilegedApp()) {
461 Slog.w(TAG, "getAllowInDataUsageSave() returned non-privileged app: " + pkg);
462 continue;
463 }
464 for (int j = 0; j < numberUsers; j++) {
465 final UserInfo user = users.get(i);
466 final int uid = UserHandle.getUid(user.id, app.uid);
467 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
468 if (LOGD) Slog.d(TAG, "revoked whistelist status for uid " + uid + ": "
469 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
470 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
471 Slog.i(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
472 + user.id + ") to restrict background whitelist");
473 mRestrictBackgroundWhitelistUids.append(uid, true);
474 changed = true;
475 }
476 }
477 }
478 return changed;
479 }
480
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700481 void updatePowerSaveTempWhitelistLocked() {
482 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700483 // Clear the states of the current whitelist
484 final int N = mPowerSaveTempWhitelistAppIds.size();
485 for (int i = 0; i < N; i++) {
486 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
487 }
488 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700489 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700490 if (whitelist != null) {
491 for (int uid : whitelist) {
492 mPowerSaveTempWhitelistAppIds.put(uid, true);
493 }
494 }
495 } catch (RemoteException e) {
496 }
497 }
498
Amith Yamasani06f08062015-06-12 13:23:33 -0700499 /**
500 * Remove unnecessary entries in the temp whitelist
501 */
502 void purgePowerSaveTempWhitelistLocked() {
503 final int N = mPowerSaveTempWhitelistAppIds.size();
504 for (int i = N - 1; i >= 0; i--) {
505 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
506 mPowerSaveTempWhitelistAppIds.removeAt(i);
507 }
508 }
509 }
510
Jeff Sharkeya4620792011-05-20 15:29:23 -0700511 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700512 if (!isBandwidthControlEnabled()) {
513 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
514 return;
515 }
516
Amith Yamasani15e472352015-04-24 19:06:07 -0700517 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
518
Felipe Lemeb85a6372016-01-14 16:16:16 -0800519 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
520
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700521 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700522 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700523 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
524 mPowerManagerInternal.registerLowPowerModeObserver(
525 new PowerManagerInternal.LowPowerModeListener() {
526 @Override
527 public void onLowPowerModeChanged(boolean enabled) {
Felipe Leme011b98f2016-02-10 17:28:31 -0800528 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700529 synchronized (mRulesLock) {
530 if (mRestrictPower != enabled) {
531 mRestrictPower = enabled;
Felipe Leme011b98f2016-02-10 17:28:31 -0800532 updateRulesForRestrictPowerLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700533 updateRulesForGlobalChangeLocked(true);
534 }
535 }
536 }
537 });
538 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700539 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700540
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700541 // read policy from disk
542 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700543
Felipe Lemea9505cc2016-02-26 10:28:41 -0800544 if (addDefaultRestrictBackgroundWhitelistUids()) {
545 writePolicyLocked();
546 }
547
Jeff Sharkeydc988062015-09-14 10:09:47 -0700548 updateRulesForGlobalChangeLocked(false);
549 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700550 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700551
Jeff Sharkeya4620792011-05-20 15:29:23 -0700552 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700553
Jeff Sharkeya4620792011-05-20 15:29:23 -0700554 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700555 mActivityManager.registerUidObserver(mUidObserver,
556 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700557 mNetworkManager.registerObserver(mAlertObserver);
558 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700559 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700560 }
561
Jeff Sharkeya4620792011-05-20 15:29:23 -0700562 // TODO: traverse existing processes to know foreground state, or have
563 // activitymanager dispatch current state when new observer attached.
564
565 final IntentFilter screenFilter = new IntentFilter();
566 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
567 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700568 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700569
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700570 // listen for changes to power save whitelist
571 final IntentFilter whitelistFilter = new IntentFilter(
572 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
573 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
574
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700575 DeviceIdleController.LocalService deviceIdleService
576 = LocalServices.getService(DeviceIdleController.LocalService.class);
577 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
578
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700579 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900580 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700581 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
582
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700583 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700584 final IntentFilter packageFilter = new IntentFilter();
585 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700586 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700587 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700588
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700589 // listen for UID changes to update policy
590 mContext.registerReceiver(
591 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
592
593 // listen for user changes to update policy
594 final IntentFilter userFilter = new IntentFilter();
595 userFilter.addAction(ACTION_USER_ADDED);
596 userFilter.addAction(ACTION_USER_REMOVED);
597 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
598
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700599 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700600 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
601 mContext.registerReceiver(
602 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
603
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700604 // listen for restrict background changes from notifications
605 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
606 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
607
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800608 // listen for snooze warning from notifications
609 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
610 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
611 MANAGE_NETWORK_POLICY, mHandler);
612
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700613 // listen for configured wifi networks to be removed
614 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700615 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700616
617 // listen for wifi state changes to catch metered hint
618 final IntentFilter wifiStateFilter = new IntentFilter(
619 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700620 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700621
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700622 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700623
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700624 }
625
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700626 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700627 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700628 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700629 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700630 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700631 }
632
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700633 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700634 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700635 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700636 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700637 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700638
639 @Override public void onUidActive(int uid) throws RemoteException {
640 }
641
642 @Override public void onUidIdle(int uid) throws RemoteException {
643 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700644 };
645
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700646 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700647 @Override
648 public void onReceive(Context context, Intent intent) {
649 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
650 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700651 updatePowerSaveWhitelistLocked();
652 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700653 }
654 }
655 };
656
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700657 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
658 @Override
659 public void run() {
660 synchronized (mRulesLock) {
661 updatePowerSaveTempWhitelistLocked();
662 updateRulesForTempWhitelistChangeLocked();
663 purgePowerSaveTempWhitelistLocked();
664 }
665 }
666 };
667
668 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700669 @Override
670 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800671 // screen-related broadcasts are protected by system, no need
672 // for permissions check.
673 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700674 }
675 };
676
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700677 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700678 @Override
679 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700680 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700681
682 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700683 final int uid = intent.getIntExtra(EXTRA_UID, -1);
684 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700685
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700686 if (ACTION_PACKAGE_ADDED.equals(action)) {
687 // update rules for UID, since it might be subject to
688 // global background data policy
689 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
690 synchronized (mRulesLock) {
Felipe Leme76010a32016-03-17 13:03:11 -0700691 updateRestrictDataRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700692 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700693 }
694 }
695 };
696
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700697 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700698 @Override
699 public void onReceive(Context context, Intent intent) {
700 // on background handler thread, and UID_REMOVED is protected
701
702 final int uid = intent.getIntExtra(EXTRA_UID, -1);
703 if (uid == -1) return;
704
705 // remove any policy and update rules to clean up
706 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
707 synchronized (mRulesLock) {
708 mUidPolicy.delete(uid);
Felipe Leme76010a32016-03-17 13:03:11 -0700709 updateRestrictDataRulesForUidLocked(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700710 writePolicyLocked();
711 }
712 }
713 };
714
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700715 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700716 @Override
717 public void onReceive(Context context, Intent intent) {
718 // on background handler thread, and USER_ADDED and USER_REMOVED
719 // broadcasts are protected
720
721 final String action = intent.getAction();
722 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
723 if (userId == -1) return;
724
Amith Yamasani15e472352015-04-24 19:06:07 -0700725 switch (action) {
726 case ACTION_USER_REMOVED:
727 case ACTION_USER_ADDED:
728 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800729 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700730 // USER_REMOVED, and one last sanity check during USER_ADDED
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800731 removeUserStateLocked(userId);
Amith Yamasani15e472352015-04-24 19:06:07 -0700732 // Update global restrict for new user
733 updateRulesForGlobalChangeLocked(true);
734 }
735 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700736 }
737 }
738 };
739
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700740 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700741 * Receiver that watches for {@link INetworkStatsService} updates, which we
742 * use to check against {@link NetworkPolicy#warningBytes}.
743 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700744 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700745 @Override
746 public void onReceive(Context context, Intent intent) {
747 // on background handler thread, and verified
748 // READ_NETWORK_USAGE_HISTORY permission above.
749
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800750 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700751 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700752 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700753 updateNotificationsLocked();
754 }
755 }
756 };
757
758 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700759 * Receiver that watches for {@link Notification} control of
760 * {@link #mRestrictBackground}.
761 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700762 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700763 @Override
764 public void onReceive(Context context, Intent intent) {
765 // on background handler thread, and verified MANAGE_NETWORK_POLICY
766 // permission above.
767
768 setRestrictBackground(false);
769 }
770 };
771
772 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800773 * Receiver that watches for {@link Notification} control of
774 * {@link NetworkPolicy#lastWarningSnooze}.
775 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700776 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800777 @Override
778 public void onReceive(Context context, Intent intent) {
779 // on background handler thread, and verified MANAGE_NETWORK_POLICY
780 // permission above.
781
782 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
783 performSnooze(template, TYPE_WARNING);
784 }
785 };
786
787 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700788 * Receiver that watches for {@link WifiConfiguration} to be changed.
789 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700790 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700791 @Override
792 public void onReceive(Context context, Intent intent) {
793 // on background handler thread, and verified CONNECTIVITY_INTERNAL
794 // permission above.
795
796 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
797 if (reason == CHANGE_REASON_REMOVED) {
798 final WifiConfiguration config = intent.getParcelableExtra(
799 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700800 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800801 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700802 synchronized (mRulesLock) {
803 if (mNetworkPolicy.containsKey(template)) {
804 mNetworkPolicy.remove(template);
805 writePolicyLocked();
806 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700807 }
808 }
809 }
810 }
811 };
812
813 /**
814 * Receiver that watches {@link WifiInfo} state changes to infer metered
815 * state. Ignores hints when policy is user-defined.
816 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700817 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700818 @Override
819 public void onReceive(Context context, Intent intent) {
820 // on background handler thread, and verified CONNECTIVITY_INTERNAL
821 // permission above.
822
823 // ignore when not connected
824 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
825 if (!netInfo.isConnected()) return;
826
827 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
828 final boolean meteredHint = info.getMeteredHint();
829
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800830 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700831 synchronized (mRulesLock) {
832 NetworkPolicy policy = mNetworkPolicy.get(template);
833 if (policy == null && meteredHint) {
834 // policy doesn't exist, and AP is hinting that it's
835 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800836 policy = newWifiPolicy(template, meteredHint);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700837 addNetworkPolicyLocked(policy);
838
839 } else if (policy != null && policy.inferred) {
840 // policy exists, and was inferred: update its current
841 // metered state.
842 policy.metered = meteredHint;
843
844 // since this is inferred for each wifi session, just update
845 // rules without persisting.
846 updateNetworkRulesLocked();
847 }
848 }
849 }
850 };
851
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800852 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
853 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
854 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
855 metered, true);
856 }
857
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700858 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700859 * Observer that watches for {@link INetworkManagementService} alerts.
860 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700861 final private INetworkManagementEventObserver mAlertObserver
862 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700863 @Override
864 public void limitReached(String limitName, String iface) {
865 // only someone like NMS should be calling us
866 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
867
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800868 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
869 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700870 }
871 }
872 };
873
874 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700875 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
876 * to show visible notifications as needed.
877 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700878 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700879 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
880
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700881 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700882 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700883 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700884
885 // TODO: when switching to kernel notifications, compute next future
886 // cycle boundary to recompute notifications.
887
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700888 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800889 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700890 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
891 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700892 // ignore policies that aren't relevant to user
893 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700894 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700895
Jeff Sharkey497e4432011-06-14 17:27:29 -0700896 final long start = computeLastCycleBoundary(currentTime, policy);
897 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700898 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700899
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700900 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800901 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700902 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
903 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700904 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
905 notifyOverLimitLocked(policy.template);
906 }
907
Jeff Sharkey497e4432011-06-14 17:27:29 -0700908 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700909 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700910
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800911 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700912 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700913 }
914 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700915 }
916
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700917 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700918 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
919 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700920 if (!mActiveNotifs.contains(tag)) {
921 cancelNotification(tag);
922 }
923 }
924 }
925
926 /**
927 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700928 * current device state, such as when
929 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
930 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700931 */
932 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800933 if (template.isMatchRuleMobile()) {
934 final TelephonyManager tele = TelephonyManager.from(mContext);
935 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700936
Jeff Sharkey32566012014-12-02 18:30:14 -0800937 // Mobile template is relevant when any active subscriber matches
938 final int[] subIds = sub.getActiveSubscriptionIdList();
939 for (int subId : subIds) {
940 final String subscriberId = tele.getSubscriberId(subId);
941 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
942 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
943 if (template.matches(probeIdent)) {
944 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700945 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800946 }
947 return false;
948 } else {
949 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700950 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700951 }
952
953 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700954 * Notify that given {@link NetworkTemplate} is over
955 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
956 */
957 private void notifyOverLimitLocked(NetworkTemplate template) {
958 if (!mOverLimitNotified.contains(template)) {
959 mContext.startActivity(buildNetworkOverLimitIntent(template));
960 mOverLimitNotified.add(template);
961 }
962 }
963
964 private void notifyUnderLimitLocked(NetworkTemplate template) {
965 mOverLimitNotified.remove(template);
966 }
967
968 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700969 * Build unique tag that identifies an active {@link NetworkPolicy}
970 * notification of a specific type, like {@link #TYPE_LIMIT}.
971 */
972 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700973 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700974 }
975
976 /**
977 * Show notification for combined {@link NetworkPolicy} and specific type,
978 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
979 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700980 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700981 final String tag = buildNotificationTag(policy, type);
982 final Notification.Builder builder = new Notification.Builder(mContext);
983 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800984 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700985 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200986 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700987
988 final Resources res = mContext.getResources();
989 switch (type) {
990 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700991 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700992 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700993
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700994 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700995 builder.setTicker(title);
996 builder.setContentTitle(title);
997 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700998
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800999 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1000 builder.setDeleteIntent(PendingIntent.getBroadcast(
1001 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1002
1003 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001004 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001005 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1006
Jeff Sharkey497e4432011-06-14 17:27:29 -07001007 break;
1008 }
1009 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001010 final CharSequence body = res.getText(R.string.data_usage_limit_body);
1011
1012 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001013 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001014 switch (policy.template.getMatchRule()) {
1015 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001016 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001017 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001018 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001019 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001020 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001021 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001022 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001023 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001024 case MATCH_WIFI:
1025 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001026 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001027 break;
1028 default:
1029 title = null;
1030 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001031 }
1032
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001033 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001034 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001035 builder.setTicker(title);
1036 builder.setContentTitle(title);
1037 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001038
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001039 final Intent intent = buildNetworkOverLimitIntent(policy.template);
1040 builder.setContentIntent(PendingIntent.getActivity(
1041 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1042 break;
1043 }
1044 case TYPE_LIMIT_SNOOZED: {
1045 final long overBytes = totalBytes - policy.limitBytes;
1046 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
1047 Formatter.formatFileSize(mContext, overBytes));
1048
1049 final CharSequence title;
1050 switch (policy.template.getMatchRule()) {
1051 case MATCH_MOBILE_3G_LOWER:
1052 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1053 break;
1054 case MATCH_MOBILE_4G:
1055 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1056 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001057 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001058 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1059 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001060 case MATCH_WIFI:
1061 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1062 break;
1063 default:
1064 title = null;
1065 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001066 }
1067
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001068 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001069 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001070 builder.setTicker(title);
1071 builder.setContentTitle(title);
1072 builder.setContentText(body);
1073
1074 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001075 builder.setContentIntent(PendingIntent.getActivity(
1076 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001077 break;
1078 }
1079 }
1080
1081 // TODO: move to NotificationManager once we can mock it
1082 try {
1083 final String packageName = mContext.getPackageName();
1084 final int[] idReceived = new int[1];
1085 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001086 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001087 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001088 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001089 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001090 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001091 }
1092 }
1093
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001094 private void cancelNotification(String tag) {
1095 // TODO: move to NotificationManager once we can mock it
1096 try {
1097 final String packageName = mContext.getPackageName();
1098 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001099 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001100 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001101 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001102 }
1103 }
1104
1105 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001106 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001107 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001108 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001109 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001110 @Override
1111 public void onReceive(Context context, Intent intent) {
1112 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1113 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001114
1115 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001116 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001117 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001118 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001119 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001120 updateNetworkRulesLocked();
1121 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001122 }
1123 }
1124 };
1125
1126 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001127 * Proactively control network data connections when they exceed
1128 * {@link NetworkPolicy#limitBytes}.
1129 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001130 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001131 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1132
1133 // TODO: reset any policy-disabled networks when any policy is removed
1134 // completely, which is currently rare case.
1135
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001136 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001137 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1138 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001139 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001140 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001141 setNetworkTemplateEnabled(policy.template, true);
1142 continue;
1143 }
1144
1145 final long start = computeLastCycleBoundary(currentTime, policy);
1146 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001147 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001148
1149 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001150 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1151 && policy.lastLimitSnooze < start;
1152 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001153
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001154 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001155 }
1156 }
1157
1158 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001159 * Proactively disable networks that match the given
1160 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001161 */
1162 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001163 // TODO: reach into ConnectivityManager to proactively disable bringing
1164 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001165 }
1166
1167 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001168 * Examine all connected {@link NetworkState}, looking for
1169 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1170 * remaining quota based on usage cycle and historical stats.
1171 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001172 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001173 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001174
1175 final NetworkState[] states;
1176 try {
1177 states = mConnManager.getAllNetworkState();
1178 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001179 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001180 return;
1181 }
1182
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001183 // First, generate identities of all connected networks so we can
1184 // quickly compare them against all defined policies below.
1185 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001186 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001187 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001188 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001189 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001190
1191 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001192 if (baseIface != null) {
1193 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001194 }
1195
1196 // Stacked interfaces are considered to have same identity as
1197 // their parent network.
1198 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1199 for (LinkProperties stackedLink : stackedLinks) {
1200 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001201 if (stackedIface != null) {
1202 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001203 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001204 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001205 }
1206 }
1207
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001208 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001209 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001210 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001211 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001212 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001213
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001214 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001215 for (int j = connIdents.size() - 1; j >= 0; j--) {
1216 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1217 if (policy.template.matches(ident.second)) {
1218 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001219 }
1220 }
1221
1222 if (ifaceList.size() > 0) {
1223 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001224 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001225 }
1226 }
1227
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001228 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001229 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001230
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001231 // apply each policy that we found ifaces for; compute remaining data
1232 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001233 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001234 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1235 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1236 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001237
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001238 final long start;
1239 final long totalBytes;
1240 if (policy.hasCycle()) {
1241 start = computeLastCycleBoundary(currentTime, policy);
1242 totalBytes = getTotalBytes(policy.template, start, currentTime);
1243 } else {
1244 start = Long.MAX_VALUE;
1245 totalBytes = 0;
1246 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001247
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001248 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001249 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001250 }
1251
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001252 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001253 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001254 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001255 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001256 if (!hasLimit) {
1257 // metered network, but no policy limit; we still need to
1258 // restrict apps, so push really high quota.
1259 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001260 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001261 // snoozing past quota, but we still need to restrict apps,
1262 // so push really high quota.
1263 quotaBytes = Long.MAX_VALUE;
1264 } else {
1265 // remaining "quota" bytes are based on total usage in
1266 // current cycle. kernel doesn't like 0-byte rules, so we
1267 // set 1-byte quota and disable the radio later.
1268 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1269 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001270
1271 if (ifaces.length > 1) {
1272 // TODO: switch to shared quota once NMS supports
1273 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001274 }
1275
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001276 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001277 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001278 setInterfaceQuota(iface, quotaBytes);
1279 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001280 }
1281 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001282
1283 // keep track of lowest warning or limit of active policies
1284 if (hasWarning && policy.warningBytes < lowestRule) {
1285 lowestRule = policy.warningBytes;
1286 }
1287 if (hasLimit && policy.limitBytes < lowestRule) {
1288 lowestRule = policy.limitBytes;
1289 }
1290 }
1291
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001292 for (int i = connIfaces.size()-1; i >= 0; i--) {
1293 String iface = connIfaces.valueAt(i);
1294 removeInterfaceQuota(iface);
1295 setInterfaceQuota(iface, Long.MAX_VALUE);
1296 newMeteredIfaces.add(iface);
1297 }
1298
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001299 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001300
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001301 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001302 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1303 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001304 if (!newMeteredIfaces.contains(iface)) {
1305 removeInterfaceQuota(iface);
1306 }
1307 }
1308 mMeteredIfaces = newMeteredIfaces;
1309
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001310 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001311 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001312 }
1313
1314 /**
1315 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1316 * have at least a default mobile policy defined.
1317 */
1318 private void ensureActiveMobilePolicyLocked() {
1319 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001320 if (mSuppressDefaultPolicy) return;
1321
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001322 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001323 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001324
Jeff Sharkey32566012014-12-02 18:30:14 -08001325 final int[] subIds = sub.getActiveSubscriptionIdList();
1326 for (int subId : subIds) {
1327 final String subscriberId = tele.getSubscriberId(subId);
1328 ensureActiveMobilePolicyLocked(subscriberId);
1329 }
1330 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001331
Jeff Sharkey32566012014-12-02 18:30:14 -08001332 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1333 // Poke around to see if we already have a policy
1334 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1335 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1336 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1337 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1338 if (template.matches(probeIdent)) {
1339 if (LOGD) {
1340 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1341 + NetworkIdentity.scrubSubscriberId(subscriberId));
1342 }
1343 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001344 }
1345 }
1346
Jeff Sharkey32566012014-12-02 18:30:14 -08001347 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1348 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001349
Jeff Sharkey32566012014-12-02 18:30:14 -08001350 // Build default mobile policy, and assume usage cycle starts today
1351 final long warningBytes = mContext.getResources().getInteger(
1352 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001353
Jeff Sharkey32566012014-12-02 18:30:14 -08001354 final Time time = new Time();
1355 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001356
Jeff Sharkey32566012014-12-02 18:30:14 -08001357 final int cycleDay = time.monthDay;
1358 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001359
Jeff Sharkey32566012014-12-02 18:30:14 -08001360 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1361 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1362 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1363 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001364 }
1365
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001366 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001367 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001368
1369 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001370 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001371 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001372
1373 FileInputStream fis = null;
1374 try {
1375 fis = mPolicyFile.openRead();
1376 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001377 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001378
1379 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001380 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001381 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001382 while ((type = in.next()) != END_DOCUMENT) {
1383 final String tag = in.getName();
1384 if (type == START_TAG) {
1385 if (TAG_POLICY_LIST.equals(tag)) {
1386 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001387 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1388 mRestrictBackground = readBooleanAttribute(
1389 in, ATTR_RESTRICT_BACKGROUND);
1390 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001391 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001392 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001393
1394 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1395 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1396 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001397 final String networkId;
1398 if (version >= VERSION_ADDED_NETWORK_ID) {
1399 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1400 } else {
1401 networkId = null;
1402 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001403 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001404 final String cycleTimezone;
1405 if (version >= VERSION_ADDED_TIMEZONE) {
1406 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1407 } else {
1408 cycleTimezone = Time.TIMEZONE_UTC;
1409 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001410 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1411 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001412 final long lastLimitSnooze;
1413 if (version >= VERSION_SPLIT_SNOOZE) {
1414 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1415 } else if (version >= VERSION_ADDED_SNOOZE) {
1416 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001417 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001418 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001419 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001420 final boolean metered;
1421 if (version >= VERSION_ADDED_METERED) {
1422 metered = readBooleanAttribute(in, ATTR_METERED);
1423 } else {
1424 switch (networkTemplate) {
1425 case MATCH_MOBILE_3G_LOWER:
1426 case MATCH_MOBILE_4G:
1427 case MATCH_MOBILE_ALL:
1428 metered = true;
1429 break;
1430 default:
1431 metered = false;
1432 }
1433 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001434 final long lastWarningSnooze;
1435 if (version >= VERSION_SPLIT_SNOOZE) {
1436 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1437 } else {
1438 lastWarningSnooze = SNOOZE_NEVER;
1439 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001440 final boolean inferred;
1441 if (version >= VERSION_ADDED_INFERRED) {
1442 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1443 } else {
1444 inferred = false;
1445 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001446
Jeff Sharkey32566012014-12-02 18:30:14 -08001447 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1448 subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001449 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001450 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001451 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001452
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001453 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001454 final int uid = readIntAttribute(in, ATTR_UID);
1455 final int policy = readIntAttribute(in, ATTR_POLICY);
1456
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001457 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001458 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001459 } else {
1460 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1461 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001462 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001463 final int appId = readIntAttribute(in, ATTR_APP_ID);
1464 final int policy = readIntAttribute(in, ATTR_POLICY);
1465
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001466 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001467 // app policy is deprecated so this is only used in pre system user split.
1468 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001469 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001470 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001471 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001472 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001473 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001474 } else if (TAG_WHITELIST.equals(tag)) {
1475 insideWhitelist = true;
1476 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1477 final int uid = readIntAttribute(in, ATTR_UID);
1478 mRestrictBackgroundWhitelistUids.put(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001479 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1480 final int uid = readIntAttribute(in, ATTR_UID);
1481 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001482 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001483 } else if (type == END_TAG) {
1484 if (TAG_WHITELIST.equals(tag)) {
1485 insideWhitelist = false;
1486 }
1487
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001488 }
1489 }
1490
1491 } catch (FileNotFoundException e) {
1492 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001493 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001494 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001495 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001496 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001497 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001498 } finally {
1499 IoUtils.closeQuietly(fis);
1500 }
1501 }
1502
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001503 /**
1504 * Upgrade legacy background data flags, notifying listeners of one last
1505 * change to always-true.
1506 */
1507 private void upgradeLegacyBackgroundData() {
1508 mRestrictBackground = Settings.Secure.getInt(
1509 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1510
1511 // kick off one last broadcast if restricted
1512 if (mRestrictBackground) {
1513 final Intent broadcast = new Intent(
1514 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001515 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001516 }
1517 }
1518
Dianne Hackborn497175b2014-07-01 12:56:08 -07001519 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001520 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001521
1522 FileOutputStream fos = null;
1523 try {
1524 fos = mPolicyFile.startWrite();
1525
1526 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001527 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001528 out.startDocument(null, true);
1529
1530 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001531 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001532 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001533
1534 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001535 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1536 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001537 final NetworkTemplate template = policy.template;
1538
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001539 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001540 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1541 final String subscriberId = template.getSubscriberId();
1542 if (subscriberId != null) {
1543 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001544 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001545 final String networkId = template.getNetworkId();
1546 if (networkId != null) {
1547 out.attribute(null, ATTR_NETWORK_ID, networkId);
1548 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001549 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001550 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001551 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1552 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001553 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1554 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001555 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001556 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001557 out.endTag(null, TAG_NETWORK_POLICY);
1558 }
1559
1560 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001561 for (int i = 0; i < mUidPolicy.size(); i++) {
1562 final int uid = mUidPolicy.keyAt(i);
1563 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001564
Jeff Sharkey497e4432011-06-14 17:27:29 -07001565 // skip writing empty policies
1566 if (policy == POLICY_NONE) continue;
1567
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001568 out.startTag(null, TAG_UID_POLICY);
1569 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001570 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001571 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001572 }
1573
1574 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001575
1576 // write all whitelists
1577 out.startTag(null, TAG_WHITELIST);
1578
1579 // restrict background whitelist
Felipe Lemea9505cc2016-02-26 10:28:41 -08001580 int size = mRestrictBackgroundWhitelistUids.size();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001581 for (int i = 0; i < size; i++) {
1582 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1583 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1584 writeIntAttribute(out, ATTR_UID, uid);
1585 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1586 }
1587
Felipe Lemea9505cc2016-02-26 10:28:41 -08001588 // revoked restrict background whitelist
1589 size = mRestrictBackgroundWhitelistRevokedUids.size();
1590 for (int i = 0; i < size; i++) {
1591 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1592 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1593 writeIntAttribute(out, ATTR_UID, uid);
1594 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1595 }
1596
Felipe Lemeb85a6372016-01-14 16:16:16 -08001597 out.endTag(null, TAG_WHITELIST);
1598
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001599 out.endDocument();
1600
1601 mPolicyFile.finishWrite(fos);
1602 } catch (IOException e) {
1603 if (fos != null) {
1604 mPolicyFile.failWrite(fos);
1605 }
1606 }
1607 }
1608
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001609 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001610 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001611 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001612
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001613 if (!UserHandle.isApp(uid)) {
1614 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001615 }
1616
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001617 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001618 final long token = Binder.clearCallingIdentity();
1619 try {
1620 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1621 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001622 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001623 }
1624 } finally {
1625 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001626 }
1627 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001628 }
1629
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001630 @Override
1631 public void addUidPolicy(int uid, int policy) {
1632 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001633
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001634 if (!UserHandle.isApp(uid)) {
1635 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1636 }
1637
1638 synchronized (mRulesLock) {
1639 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1640 policy |= oldPolicy;
1641 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001642 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001643 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001644 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001645 }
1646
1647 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001648 public void removeUidPolicy(int uid, int policy) {
1649 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1650
1651 if (!UserHandle.isApp(uid)) {
1652 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1653 }
1654
1655 synchronized (mRulesLock) {
1656 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1657 policy = oldPolicy & ~policy;
1658 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001659 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001660 }
1661 }
1662 }
1663
Felipe Leme923845f2016-03-02 13:42:48 -08001664 private void setUidPolicyUncheckedLocked(int uid, int oldPolicy, int policy, boolean persist) {
1665 setUidPolicyUncheckedLocked(uid, policy, persist);
1666
1667 // Checks if app was added or removed to the blacklist.
1668 if ((oldPolicy == POLICY_NONE && policy == POLICY_REJECT_METERED_BACKGROUND)
1669 || (oldPolicy == POLICY_REJECT_METERED_BACKGROUND && policy == POLICY_NONE)) {
1670 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 0)
1671 .sendToTarget();
1672 }
1673 }
1674
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001675 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1676 mUidPolicy.put(uid, policy);
1677
1678 // uid policy changed, recompute rules and persist policy.
Felipe Leme76010a32016-03-17 13:03:11 -07001679 updateRestrictDataRulesForUidLocked(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001680 if (persist) {
1681 writePolicyLocked();
1682 }
1683 }
1684
1685 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001686 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001687 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1688
Jeff Sharkeya4620792011-05-20 15:29:23 -07001689 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001690 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001691 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001692 }
1693
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001694 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001695 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001696 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1697
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001698 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001699 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001700 for (int i = 0; i < mUidPolicy.size(); i++) {
1701 final int uid = mUidPolicy.keyAt(i);
1702 final int uidPolicy = mUidPolicy.valueAt(i);
1703 if (uidPolicy == policy) {
1704 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001705 }
1706 }
1707 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001708 return uids;
1709 }
1710
1711 /**
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001712 * Remove any persistable state associated with given {@link UserHandle}, persisting
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001713 * if any changes are made.
1714 */
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001715 void removeUserStateLocked(int userId) {
1716 if (LOGV) Slog.v(TAG, "removeUserStateLocked()");
1717 boolean writePolicy = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001718
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001719 // Remove entries from restricted background UID whitelist
1720 int[] wlUids = new int[0];
1721 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1722 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1723 if (UserHandle.getUserId(uid) == userId) {
1724 wlUids = appendInt(wlUids, uid);
1725 }
1726 }
1727
1728 if (wlUids.length > 0) {
1729 for (int uid : wlUids) {
1730 removeRestrictBackgroundWhitelistedUidLocked(uid, false);
1731 }
1732 writePolicy = true;
1733 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001734 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001735 int[] uids = new int[0];
1736 for (int i = 0; i < mUidPolicy.size(); i++) {
1737 final int uid = mUidPolicy.keyAt(i);
1738 if (UserHandle.getUserId(uid) == userId) {
1739 uids = appendInt(uids, uid);
1740 }
1741 }
1742
1743 if (uids.length > 0) {
1744 for (int uid : uids) {
1745 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001746 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001747 writePolicy = true;
1748 }
1749
Felipe Leme76010a32016-03-17 13:03:11 -07001750 updateRulesForGlobalChangeLocked(true);
1751
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001752 if (writePolicy) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001753 writePolicyLocked();
1754 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001755 }
1756
1757 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001758 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001759 // TODO: create permission for observing network policy
1760 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1761
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001762 mListeners.register(listener);
1763
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001764 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001765 }
1766
1767 @Override
1768 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001769 // TODO: create permission for observing network policy
1770 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1771
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001772 mListeners.unregister(listener);
1773 }
1774
Jeff Sharkey1b861272011-05-22 00:34:52 -07001775 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001776 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001777 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1778
Felipe Leme6a05eee2016-02-19 14:43:51 -08001779 final long token = Binder.clearCallingIdentity();
1780 try {
1781 maybeRefreshTrustedTime();
1782 synchronized (mRulesLock) {
1783 normalizePoliciesLocked(policies);
1784 updateNetworkEnabledLocked();
1785 updateNetworkRulesLocked();
1786 updateNotificationsLocked();
1787 writePolicyLocked();
1788 }
1789 } finally {
1790 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001791 }
1792 }
1793
Dianne Hackborn497175b2014-07-01 12:56:08 -07001794 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001795 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001796 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1797 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001798 }
1799
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001800 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001801 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001802 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001803 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001804 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1805 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1806 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001807 } catch (SecurityException e) {
1808 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001809
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001810 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1811 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1812 return new NetworkPolicy[0];
1813 }
Svet Ganov16a16892015-04-16 10:32:04 -07001814 }
1815
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001816 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001817 final int size = mNetworkPolicy.size();
1818 final NetworkPolicy[] policies = new NetworkPolicy[size];
1819 for (int i = 0; i < size; i++) {
1820 policies[i] = mNetworkPolicy.valueAt(i);
1821 }
1822 return policies;
1823 }
1824 }
1825
1826 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001827 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001828 }
1829
1830 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1831 final TelephonyManager tele = TelephonyManager.from(mContext);
1832 final String[] merged = tele.getMergedSubscriberIds();
1833
1834 mNetworkPolicy.clear();
1835 for (NetworkPolicy policy : policies) {
1836 // When two normalized templates conflict, prefer the most
1837 // restrictive policy
1838 policy.template = NetworkTemplate.normalize(policy.template, merged);
1839 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1840 if (existing == null || existing.compareTo(policy) > 0) {
1841 if (existing != null) {
1842 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1843 }
1844 mNetworkPolicy.put(policy.template, policy);
1845 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001846 }
1847 }
1848
1849 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001850 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001851 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001852
1853 final long token = Binder.clearCallingIdentity();
1854 try {
1855 performSnooze(template, TYPE_LIMIT);
1856 } finally {
1857 Binder.restoreCallingIdentity(token);
1858 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001859 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001860
Dianne Hackborn497175b2014-07-01 12:56:08 -07001861 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001862 maybeRefreshTrustedTime();
1863 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001864 synchronized (mRulesLock) {
1865 // find and snooze local policy that matches
1866 final NetworkPolicy policy = mNetworkPolicy.get(template);
1867 if (policy == null) {
1868 throw new IllegalArgumentException("unable to find policy for " + template);
1869 }
1870
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001871 switch (type) {
1872 case TYPE_WARNING:
1873 policy.lastWarningSnooze = currentTime;
1874 break;
1875 case TYPE_LIMIT:
1876 policy.lastLimitSnooze = currentTime;
1877 break;
1878 default:
1879 throw new IllegalArgumentException("unexpected type");
1880 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001881
Jeff Sharkey32566012014-12-02 18:30:14 -08001882 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001883 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001884 updateNetworkRulesLocked();
1885 updateNotificationsLocked();
1886 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001887 }
1888 }
1889
1890 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001891 public void setRestrictBackground(boolean restrictBackground) {
1892 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08001893 final long token = Binder.clearCallingIdentity();
1894 try {
1895 maybeRefreshTrustedTime();
1896 synchronized (mRulesLock) {
1897 mRestrictBackground = restrictBackground;
Felipe Leme76010a32016-03-17 13:03:11 -07001898 updateRulesForRestrictDataLocked();
Felipe Leme6a05eee2016-02-19 14:43:51 -08001899 updateNotificationsLocked();
1900 writePolicyLocked();
1901 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001902
Felipe Leme6a05eee2016-02-19 14:43:51 -08001903 } finally {
1904 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07001905 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001906
1907 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1908 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001909 }
1910
1911 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08001912 public void addRestrictBackgroundWhitelistedUid(int uid) {
1913 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08001914 if (!isUidValidForRules(uid)) return;
1915 final boolean changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001916 synchronized (mRulesLock) {
Felipe Leme47585ba2016-02-09 16:56:32 -08001917 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
1918 if (oldStatus) {
1919 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
1920 return;
1921 }
1922 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08001923 mRestrictBackgroundWhitelistUids.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001924 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
1925 && mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
1926 if (LOGD) Slog.d(TAG, "Removing uid " + uid
1927 + " from revoked restrict background whitelist");
1928 mRestrictBackgroundWhitelistRevokedUids.delete(uid);
1929 }
Felipe Leme47585ba2016-02-09 16:56:32 -08001930 changed = mRestrictBackground && !oldStatus;
1931 if (changed && hasInternetPermissions(uid)) {
1932 setUidNetworkRules(uid, false);
1933 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001934 writePolicyLocked();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001935 }
Felipe Leme47585ba2016-02-09 16:56:32 -08001936 if (changed) {
1937 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 0)
1938 .sendToTarget();
1939 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001940 }
1941
1942 @Override
1943 public void removeRestrictBackgroundWhitelistedUid(int uid) {
1944 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08001945 if (!isUidValidForRules(uid)) return;
1946 final boolean changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001947 synchronized (mRulesLock) {
Felipe Leme47585ba2016-02-09 16:56:32 -08001948 changed = removeRestrictBackgroundWhitelistedUidLocked(uid, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001949 }
Felipe Leme47585ba2016-02-09 16:56:32 -08001950 if (changed) {
1951 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 0)
1952 .sendToTarget();
1953 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001954 }
1955
Felipe Leme47585ba2016-02-09 16:56:32 -08001956 private boolean removeRestrictBackgroundWhitelistedUidLocked(int uid, boolean updateNow) {
1957 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
1958 if (!oldStatus) {
1959 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
1960 return false;
1961 }
1962 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
1963 final boolean changed = mRestrictBackground && oldStatus;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001964 mRestrictBackgroundWhitelistUids.delete(uid);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001965 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
1966 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
1967 if (LOGD) Slog.d(TAG, "Adding uid " + uid
1968 + " to revoked restrict background whitelist");
1969 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
1970 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08001971 if (updateNow) {
Felipe Leme47585ba2016-02-09 16:56:32 -08001972 if (changed && hasInternetPermissions(uid)) {
1973 setUidNetworkRules(uid, true);
1974 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001975 writePolicyLocked();
1976 }
Felipe Leme47585ba2016-02-09 16:56:32 -08001977 return changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001978 }
1979
1980 @Override
1981 public int[] getRestrictBackgroundWhitelistedUids() {
1982 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1983 synchronized (mRulesLock) {
1984 final int size = mRestrictBackgroundWhitelistUids.size();
1985 final int[] whitelist = new int[size];
1986 for (int i = 0; i < size; i++) {
1987 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
1988 }
1989 if (LOGV) {
1990 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
1991 + mRestrictBackgroundWhitelistUids);
1992 }
1993 return whitelist;
1994 }
1995 }
1996
1997 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08001998 public int getRestrictBackgroundByCaller() {
1999 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2000 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002001
Felipe Leme1b103232016-01-22 09:44:57 -08002002 synchronized (mRulesLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002003 // Must clear identity because getUidPolicy() is restricted to system.
2004 final long token = Binder.clearCallingIdentity();
2005 final int policy;
2006 try {
2007 policy = getUidPolicy(uid);
2008 } finally {
2009 Binder.restoreCallingIdentity(token);
2010 }
2011 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2012 // App is blacklisted.
2013 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2014 }
Felipe Leme1b103232016-01-22 09:44:57 -08002015 if (!mRestrictBackground) {
2016 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2017 }
2018 return mRestrictBackgroundWhitelistUids.get(uid)
2019 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2020 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2021 }
2022 }
2023
2024 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002025 public boolean getRestrictBackground() {
2026 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2027
2028 synchronized (mRulesLock) {
2029 return mRestrictBackground;
2030 }
2031 }
2032
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002033 @Override
2034 public void setDeviceIdleMode(boolean enabled) {
2035 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2036
2037 synchronized (mRulesLock) {
2038 if (mDeviceIdleMode != enabled) {
2039 mDeviceIdleMode = enabled;
2040 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002041 // Device idle change means we need to rebuild rules for all
2042 // known apps, so do a global refresh.
2043 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002044 }
2045 if (enabled) {
2046 EventLogTags.writeDeviceIdleOnPhase("net");
2047 } else {
2048 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002049 }
2050 }
2051 }
2052 }
2053
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002054 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002055 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2056 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002057 if (policy.template.matches(ident)) {
2058 return policy;
2059 }
2060 }
2061 return null;
2062 }
2063
2064 @Override
2065 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2066 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2067
2068 // only returns usage summary, so we don't require caller to have
2069 // READ_NETWORK_USAGE_HISTORY.
2070 final long token = Binder.clearCallingIdentity();
2071 try {
2072 return getNetworkQuotaInfoUnchecked(state);
2073 } finally {
2074 Binder.restoreCallingIdentity(token);
2075 }
2076 }
2077
2078 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2079 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2080
2081 final NetworkPolicy policy;
2082 synchronized (mRulesLock) {
2083 policy = findPolicyForNetworkLocked(ident);
2084 }
2085
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002086 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002087 // missing policy means we can't derive useful quota info
2088 return null;
2089 }
2090
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002091 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002092
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002093 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002094 final long start = computeLastCycleBoundary(currentTime, policy);
2095 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002096 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002097
2098 // report soft and hard limits under policy
2099 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2100 : NetworkQuotaInfo.NO_LIMIT;
2101 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2102 : NetworkQuotaInfo.NO_LIMIT;
2103
2104 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2105 }
2106
Jeff Sharkey46645002011-07-27 21:11:21 -07002107 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002108 public boolean isNetworkMetered(NetworkState state) {
2109 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2110
Jeff Sharkeyf166f482012-04-30 15:59:21 -07002111 // roaming networks are always considered metered
2112 if (ident.getRoaming()) {
2113 return true;
2114 }
2115
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002116 final NetworkPolicy policy;
2117 synchronized (mRulesLock) {
2118 policy = findPolicyForNetworkLocked(ident);
2119 }
2120
2121 if (policy != null) {
2122 return policy.metered;
2123 } else {
Wei Liub8eaf452016-01-25 10:32:27 -08002124 if (state.networkInfo == null) {
2125 return false;
2126 }
2127
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002128 final int type = state.networkInfo.getType();
2129 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
2130 return true;
2131 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002132 return false;
2133 }
2134 }
2135
2136 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002137 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002138 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002139
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002140 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2141
Dianne Hackborn497175b2014-07-01 12:56:08 -07002142 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002143 for (String arg : args) {
2144 argSet.add(arg);
2145 }
2146
Jeff Sharkey1b861272011-05-22 00:34:52 -07002147 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002148 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002149 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2150 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002151 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002152
Jeff Sharkey32566012014-12-02 18:30:14 -08002153 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002154 updateNetworkEnabledLocked();
2155 updateNetworkRulesLocked();
2156 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002157 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002158
2159 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002160 return;
2161 }
2162
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002163 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07002164 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002165 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002166 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002167 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002168 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002169 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2170 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002171 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002172 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002173
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07002174 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2175
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002176 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002177 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002178 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002179 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002180 final int uid = mUidPolicy.keyAt(i);
2181 final int policy = mUidPolicy.valueAt(i);
2182 fout.print("UID=");
2183 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002184 fout.print(" policy=");
Jeff Sharkeydc988062015-09-14 10:09:47 -07002185 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002186 fout.println();
2187 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002188 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002189
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002190 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2191 if (size > 0) {
2192 fout.println("Power save whitelist (except idle) app ids:");
2193 fout.increaseIndent();
2194 for (int i = 0; i < size; i++) {
2195 fout.print("UID=");
2196 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2197 fout.print(": ");
2198 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2199 fout.println();
2200 }
2201 fout.decreaseIndent();
2202 }
2203
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002204 size = mPowerSaveWhitelistAppIds.size();
2205 if (size > 0) {
2206 fout.println("Power save whitelist app ids:");
2207 fout.increaseIndent();
2208 for (int i = 0; i < size; i++) {
2209 fout.print("UID=");
2210 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2211 fout.print(": ");
2212 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2213 fout.println();
2214 }
2215 fout.decreaseIndent();
2216 }
2217
Felipe Lemeb85a6372016-01-14 16:16:16 -08002218 size = mRestrictBackgroundWhitelistUids.size();
2219 if (size > 0) {
2220 fout.println("Restrict background whitelist uids:");
2221 fout.increaseIndent();
2222 for (int i = 0; i < size; i++) {
2223 fout.print("UID=");
2224 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2225 fout.println();
2226 }
2227 fout.decreaseIndent();
2228 }
2229
Felipe Lemea9505cc2016-02-26 10:28:41 -08002230 size = mDefaultRestrictBackgroundWhitelistUids.size();
2231 if (size > 0) {
2232 fout.println("Default restrict background whitelist uids:");
2233 fout.increaseIndent();
2234 for (int i = 0; i < size; i++) {
2235 fout.print("UID=");
2236 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2237 fout.println();
2238 }
2239 fout.decreaseIndent();
2240 }
2241
2242 size = mRestrictBackgroundWhitelistRevokedUids.size();
2243 if (size > 0) {
2244 fout.println("Default restrict background whitelist uids revoked by users:");
2245 fout.increaseIndent();
2246 for (int i = 0; i < size; i++) {
2247 fout.print("UID=");
2248 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2249 fout.println();
2250 }
2251 fout.decreaseIndent();
2252 }
2253
Jeff Sharkey1b861272011-05-22 00:34:52 -07002254 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07002255 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002256 collectKeys(mUidRules, knownUids);
2257
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002258 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002259 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002260 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002261 for (int i = 0; i < size; i++) {
2262 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002263 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07002264 fout.print(uid);
2265
Jeff Sharkeydc988062015-09-14 10:09:47 -07002266 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002267 fout.print(" state=");
2268 fout.print(state);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002269 fout.print(state <= ActivityManager.PROCESS_STATE_TOP ? " (fg)" : " (bg)");
Dianne Hackborn497175b2014-07-01 12:56:08 -07002270
Jeff Sharkeydc988062015-09-14 10:09:47 -07002271 final int rule = mUidRules.get(uid, RULE_UNKNOWN);
2272 fout.print(" rule=");
2273 fout.print(DebugUtils.valueToString(NetworkPolicyManager.class, "RULE_", rule));
Jeff Sharkey1b861272011-05-22 00:34:52 -07002274
2275 fout.println();
2276 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002277 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002278 }
2279 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002280
2281 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002282 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2283 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002284 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002285 this, in, out, err, args, resultReceiver);
2286 }
2287
2288 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002289 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002290 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2291
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002292 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002293 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002294 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002295 }
2296
Dianne Hackborn497175b2014-07-01 12:56:08 -07002297 boolean isUidForegroundLocked(int uid) {
2298 // only really in foreground when screen is also on
2299 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002300 <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002301 }
2302
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002303 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002304 * Process state of UID changed; if needed, will trigger
Felipe Leme76010a32016-03-17 13:03:11 -07002305 * {@link #updateRestrictDataRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002306 */
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002307 void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002308 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2309 if (oldUidState != uidState) {
2310 // state changed, push updated rules
2311 mUidState.put(uid, uidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002312 updateRulesForUidStateChangeLocked(uid, oldUidState, uidState);
Felipe Leme011b98f2016-02-10 17:28:31 -08002313 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2314 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2315 if (mDeviceIdleMode) {
2316 updateRuleForDeviceIdleLocked(uid);
2317 }
2318 if (mRestrictPower) {
2319 updateRulesForRestrictPowerLocked(uid);
2320 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002321 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002322 }
2323 }
2324
2325 void removeUidStateLocked(int uid) {
2326 final int index = mUidState.indexOfKey(uid);
2327 if (index >= 0) {
2328 final int oldUidState = mUidState.valueAt(index);
2329 mUidState.removeAt(index);
2330 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
2331 updateRulesForUidStateChangeLocked(uid, oldUidState,
2332 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002333 if (mDeviceIdleMode) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002334 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002335 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002336 if (mRestrictPower) {
2337 updateRulesForRestrictPowerLocked(uid);
2338 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002339 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002340 }
2341 }
2342
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002343 void updateRulesForUidStateChangeLocked(int uid, int oldUidState, int newUidState) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002344 final boolean oldForeground = oldUidState <= ActivityManager.PROCESS_STATE_TOP;
2345 final boolean newForeground = newUidState <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002346 if (oldForeground != newForeground) {
Felipe Leme76010a32016-03-17 13:03:11 -07002347 updateRestrictDataRulesForUidLocked(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002348 }
2349 }
2350
Jeff Sharkeya4620792011-05-20 15:29:23 -07002351 private void updateScreenOn() {
2352 synchronized (mRulesLock) {
2353 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002354 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002355 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002356 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002357 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002358 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002359 }
2360 }
2361
2362 /**
2363 * Update rules that might be changed by {@link #mScreenOn} value.
2364 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002365 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002366 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002367 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002368 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002369 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002370 final int uid = mUidState.keyAt(i);
Felipe Leme76010a32016-03-17 13:03:11 -07002371 updateRestrictDataRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002372 }
2373 }
2374 }
2375
Felipe Leme011b98f2016-02-10 17:28:31 -08002376 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002377 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2378 }
2379
Felipe Leme011b98f2016-02-10 17:28:31 -08002380 void updateRulesForRestrictPowerLocked() {
2381 updateRulesForWhitelistedPowerSaveLocked(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2382 mUidFirewallPowerSaveRules);
2383 }
2384
2385 void updateRulesForRestrictPowerLocked(int uid) {
2386 updateRulesForWhitelistedPowerSaveLocked(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
2387 }
2388
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002389 void updateRulesForDeviceIdleLocked() {
Felipe Leme011b98f2016-02-10 17:28:31 -08002390 updateRulesForWhitelistedPowerSaveLocked(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2391 mUidFirewallDozableRules);
2392 }
2393
2394 void updateRuleForDeviceIdleLocked(int uid) {
2395 updateRulesForWhitelistedPowerSaveLocked(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
2396 }
2397
2398 // NOTE: since both fw_dozable and fw_powersave uses the same map (mPowerSaveTempWhitelistAppIds)
2399 // for whitelisting, we can reuse their logic in this method.
2400 private void updateRulesForWhitelistedPowerSaveLocked(boolean enabled, int chain,
2401 SparseIntArray rules) {
2402 if (enabled) {
2403 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002404 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002405 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002406 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002407 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002408 for (int ui = users.size() - 1; ui >= 0; ui--) {
2409 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002410 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002411 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2412 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2413 int uid = UserHandle.getUid(user.id, appId);
2414 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2415 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002416 }
2417 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2418 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2419 int uid = UserHandle.getUid(user.id, appId);
2420 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2421 }
2422 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002423 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002424 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002425 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2426 }
2427 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002428 setUidFirewallRules(chain, uidRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002429 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002430
Felipe Leme011b98f2016-02-10 17:28:31 -08002431 enableFirewallChainLocked(chain, enabled);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002432 }
2433
Felipe Leme011b98f2016-02-10 17:28:31 -08002434 // NOTE: since both fw_dozable and fw_powersave uses the same map (mPowerSaveTempWhitelistAppIds)
2435 // for whitelisting, we can reuse their logic in this method.
2436 private void updateRulesForWhitelistedPowerSaveLocked(int uid, boolean enabled, int chain) {
2437 if (enabled) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002438 int appId = UserHandle.getAppId(uid);
2439 if (mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId)
Felipe Leme011b98f2016-02-10 17:28:31 -08002440 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2441 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002442 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002443 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002444 }
2445 }
2446 }
2447
2448 void updateRulesForAppIdleLocked() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002449 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2450 uidRules.clear();
2451
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002452 // Fully update the app idle firewall chain.
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002453 final IPackageManager ipm = AppGlobals.getPackageManager();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002454 final List<UserInfo> users = mUserManager.getUsers();
2455 for (int ui = users.size() - 1; ui >= 0; ui--) {
2456 UserInfo user = users.get(ui);
2457 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2458 for (int uid : idleUids) {
2459 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002460 // quick check: if this uid doesn't have INTERNET permission, it
2461 // doesn't have network access anyway, so it is a waste to mess
2462 // with it here.
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002463 if (hasInternetPermissions(uid)) {
2464 uidRules.put(uid, FIREWALL_RULE_DENY);
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002465 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002466 }
2467 }
2468 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002469
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002470 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2471 }
2472
2473 void updateRuleForAppIdleLocked(int uid) {
2474 if (!isUidValidForRules(uid)) return;
2475
2476 int appId = UserHandle.getAppId(uid);
2477 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)) {
2478 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2479 } else {
2480 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2481 }
2482 }
2483
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002484 void updateRulesForAppIdleParoleLocked() {
2485 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2486 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002487 }
2488
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002489 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002490 * Update rules that might be changed by {@link #mRestrictBackground},
2491 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002492 */
Felipe Leme76010a32016-03-17 13:03:11 -07002493 private void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002494 long start;
2495 if (LOGD) start = System.currentTimeMillis();
2496
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002497 updateRulesForDeviceIdleLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002498 updateRulesForAppIdleLocked();
Felipe Leme011b98f2016-02-10 17:28:31 -08002499 updateRulesForRestrictPowerLocked();
Felipe Leme76010a32016-03-17 13:03:11 -07002500 updateRulesForRestrictDataLocked();
2501
2502 // If the set of restricted networks may have changed, re-evaluate those.
2503 if (restrictedNetworksChanged) {
2504 normalizePoliciesLocked();
2505 updateNetworkRulesLocked();
2506 }
2507 if (LOGD) {
2508 final long delta = System.currentTimeMillis() - start;
2509 Slog.d(TAG, "updateRulesForGlobalChangeLocked(" + restrictedNetworksChanged + ") took "
2510 + delta + "ms");
2511 }
2512 }
2513
2514 private void updateRulesForRestrictDataLocked() {
2515 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002516
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002517 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002518 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002519 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey2a9e3f82015-12-18 10:57:58 -07002520 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS
2521 | PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002522
Felipe Leme03e689d2016-03-02 16:17:38 -08002523 final int usersSize = users.size();
2524 final int appsSize = apps.size();
2525 for (int i = 0; i < usersSize; i++) {
2526 final UserInfo user = users.get(i);
2527 for (int j = 0; j < appsSize; j++) {
2528 final ApplicationInfo app = apps.get(j);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002529 final int uid = UserHandle.getUid(user.id, app.uid);
Felipe Leme76010a32016-03-17 13:03:11 -07002530 updateRestrictDataRulesForUidLocked(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002531 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002532 }
2533
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002534 // limit data usage for some internal system services
Felipe Leme76010a32016-03-17 13:03:11 -07002535 updateRestrictDataRulesForUidLocked(android.os.Process.MEDIA_UID);
2536 updateRestrictDataRulesForUidLocked(android.os.Process.DRM_UID);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002537 }
2538
Felipe Leme76010a32016-03-17 13:03:11 -07002539 private void updateRulesForTempWhitelistChangeLocked() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002540 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002541 for (int i = 0; i < users.size(); i++) {
2542 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002543 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002544 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002545 int uid = UserHandle.getUid(user.id, appId);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002546 updateRuleForAppIdleLocked(uid);
2547 updateRuleForDeviceIdleLocked(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002548 updateRulesForRestrictPowerLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002549 }
2550 }
2551 }
2552
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002553 private static boolean isUidValidForRules(int uid) {
2554 // allow rules on specific system services, and any apps
2555 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002556 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002557 return true;
2558 }
2559
2560 return false;
2561 }
2562
Amith Yamasani15e472352015-04-24 19:06:07 -07002563 private boolean isUidIdle(int uid) {
2564 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2565 final int userId = UserHandle.getUserId(uid);
2566
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002567 if (!ArrayUtils.isEmpty(packages)) {
2568 for (String packageName : packages) {
2569 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2570 return false;
2571 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002572 }
2573 }
2574 return true;
2575 }
2576
2577 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002578 * Checks if an uid has INTERNET permissions.
2579 * <p>
2580 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002581 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002582 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002583 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002584 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002585 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002586 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002587 }
2588 } catch (RemoteException e) {
2589 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002590 return true;
2591 }
2592
2593 /**
Felipe Leme76010a32016-03-17 13:03:11 -07002594 * Applies network rules to bandwidth controllers based on uid policy.
2595 *
Felipe Leme47585ba2016-02-09 16:56:32 -08002596 * @param uid The uid for which to apply the latest policy
2597 */
Felipe Leme76010a32016-03-17 13:03:11 -07002598 private void updateRestrictDataRulesForUidLocked(int uid) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002599 if (!isUidValidForRules(uid) || !hasInternetPermissions(uid)) return;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002600
Dianne Hackborn497175b2014-07-01 12:56:08 -07002601 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2602 final boolean uidForeground = isUidForegroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002603
Jeff Sharkeydc988062015-09-14 10:09:47 -07002604 // Derive active rules based on policy and active state
Felipe Leme76010a32016-03-17 13:03:11 -07002605 int newRule = RULE_ALLOW_ALL;
2606
2607 if (!uidForeground) {
2608 // If the app is not in foreground, reject access if:
2609 // - app is blacklisted by policy or
2610 // - data saver mode is and app is not whitelisted
2611 if (((uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0)
2612 || (mRestrictBackground && !mRestrictBackgroundWhitelistUids.get(uid))) {
2613 newRule = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002614 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002615 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002616
Felipe Leme76010a32016-03-17 13:03:11 -07002617 final int oldRule = mUidRules.get(uid);
2618 if (LOGV) Log.v(TAG, "updateBandwithControllerRulesForUidLocked(" + uid + "): oldRule = "
2619 + oldRule + ", newRule = " + newRule);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002620
Felipe Leme76010a32016-03-17 13:03:11 -07002621 if (newRule == RULE_ALLOW_ALL) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002622 mUidRules.delete(uid);
2623 } else {
Felipe Leme76010a32016-03-17 13:03:11 -07002624 mUidRules.put(uid, newRule);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002625 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002626
Felipe Leme76010a32016-03-17 13:03:11 -07002627 final boolean rejectMetered = (newRule == RULE_REJECT_METERED);
Jeff Sharkeydc988062015-09-14 10:09:47 -07002628 setUidNetworkRules(uid, rejectMetered);
Amith Yamasani15e472352015-04-24 19:06:07 -07002629
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002630 // dispatch changed rule to existing listeners
Felipe Leme76010a32016-03-17 13:03:11 -07002631 if (oldRule != newRule) {
2632 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newRule).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07002633 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002634
2635 try {
2636 // adjust stats accounting based on foreground status
2637 mNetworkStats.setUidForeground(uid, uidForeground);
2638 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002639 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002640 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002641 }
2642
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002643 private class AppIdleStateChangeListener
2644 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2645
2646 @Override
2647 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2648 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002649 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
2650 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002651 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002652 updateRuleForAppIdleLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002653 }
2654 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002655 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002656 }
2657
2658 @Override
2659 public void onParoleStateChanged(boolean isParoleOn) {
2660 synchronized (mRulesLock) {
2661 updateRulesForAppIdleParoleLocked();
2662 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002663 }
2664 }
2665
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002666 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002667 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002668 public boolean handleMessage(Message msg) {
2669 switch (msg.what) {
2670 case MSG_RULES_CHANGED: {
2671 final int uid = msg.arg1;
2672 final int uidRules = msg.arg2;
2673 final int length = mListeners.beginBroadcast();
2674 for (int i = 0; i < length; i++) {
2675 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2676 if (listener != null) {
2677 try {
2678 listener.onUidRulesChanged(uid, uidRules);
2679 } catch (RemoteException e) {
2680 }
2681 }
2682 }
2683 mListeners.finishBroadcast();
2684 return true;
2685 }
2686 case MSG_METERED_IFACES_CHANGED: {
2687 final String[] meteredIfaces = (String[]) msg.obj;
2688 final int length = mListeners.beginBroadcast();
2689 for (int i = 0; i < length; i++) {
2690 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2691 if (listener != null) {
2692 try {
2693 listener.onMeteredIfacesChanged(meteredIfaces);
2694 } catch (RemoteException e) {
2695 }
2696 }
2697 }
2698 mListeners.finishBroadcast();
2699 return true;
2700 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002701 case MSG_LIMIT_REACHED: {
2702 final String iface = (String) msg.obj;
2703
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002704 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002705 synchronized (mRulesLock) {
2706 if (mMeteredIfaces.contains(iface)) {
2707 try {
2708 // force stats update to make sure we have
2709 // numbers that caused alert to trigger.
2710 mNetworkStats.forceUpdate();
2711 } catch (RemoteException e) {
2712 // ignored; service lives in system_server
2713 }
2714
2715 updateNetworkEnabledLocked();
2716 updateNotificationsLocked();
2717 }
2718 }
2719 return true;
2720 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002721 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2722 final boolean restrictBackground = msg.arg1 != 0;
2723 final int length = mListeners.beginBroadcast();
2724 for (int i = 0; i < length; i++) {
2725 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2726 if (listener != null) {
2727 try {
2728 listener.onRestrictBackgroundChanged(restrictBackground);
2729 } catch (RemoteException e) {
2730 }
2731 }
2732 }
2733 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08002734 final Intent intent =
2735 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
2736 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2737 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2738 return true;
2739 }
2740 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
2741 final int uid = msg.arg1;
2742 final PackageManager pm = mContext.getPackageManager();
2743 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme86e5a012016-02-16 16:26:05 -08002744 if (packages != null) {
2745 final int userId = UserHandle.getUserId(uid);
2746 for (String packageName : packages) {
2747 final Intent intent = new Intent(
2748 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
2749 intent.setPackage(packageName);
2750 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2751 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
2752 }
2753 } else {
2754 Slog.w(TAG, "no packages for uid " + uid);
Felipe Leme9778f762016-01-27 14:46:39 -08002755 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002756 return true;
2757 }
2758 case MSG_ADVISE_PERSIST_THRESHOLD: {
2759 final long lowestRule = (Long) msg.obj;
2760 try {
2761 // make sure stats are recorded frequently enough; we aim
2762 // for 2MB threshold for 2GB/month rules.
2763 final long persistThreshold = lowestRule / 1000;
2764 mNetworkStats.advisePersistThreshold(persistThreshold);
2765 } catch (RemoteException e) {
2766 // ignored; service lives in system_server
2767 }
2768 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002769 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002770 case MSG_SCREEN_ON_CHANGED: {
2771 updateScreenOn();
2772 return true;
2773 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002774 default: {
2775 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002776 }
2777 }
2778 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002779 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002780
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002781 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002782 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002783 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002784 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002785 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002786 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002787 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002788 }
2789 }
2790
2791 private void removeInterfaceQuota(String iface) {
2792 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002793 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002794 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002795 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002796 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002797 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002798 }
2799 }
2800
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002801 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2802 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002803 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002804 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002805 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002806 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002807 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002808 }
2809 }
2810
Amith Yamasani15e472352015-04-24 19:06:07 -07002811 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002812 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
2813 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
2814 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07002815 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002816 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002817 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002818 int size = uidRules.size();
2819 int[] uids = new int[size];
2820 int[] rules = new int[size];
2821 for(int index = size - 1; index >= 0; --index) {
2822 uids[index] = uidRules.keyAt(index);
2823 rules[index] = uidRules.valueAt(index);
2824 }
2825 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002826 } catch (IllegalStateException e) {
2827 Log.wtf(TAG, "problem setting firewall uid rules", e);
2828 } catch (RemoteException e) {
2829 // ignored; service lives in system_server
2830 }
2831 }
2832
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002833 /**
2834 * Add or remove a uid to the firewall blacklist for all network ifaces.
2835 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002836 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002837 if (chain == FIREWALL_CHAIN_DOZABLE) {
2838 mUidFirewallDozableRules.put(uid, rule);
2839 } else if (chain == FIREWALL_CHAIN_STANDBY) {
2840 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08002841 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
2842 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07002843 }
2844
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002845 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002846 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002847 } catch (IllegalStateException e) {
2848 Log.wtf(TAG, "problem setting firewall uid rules", e);
2849 } catch (RemoteException e) {
2850 // ignored; service lives in system_server
2851 }
2852 }
2853
2854 /**
2855 * Add or remove a uid to the firewall blacklist for all network ifaces.
2856 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002857 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002858 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
2859 mFirewallChainStates.get(chain) == enable) {
2860 // All is the same, nothing to do.
2861 return;
2862 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002863 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002864 try {
2865 mNetworkManager.setFirewallChainEnabled(chain, enable);
2866 } catch (IllegalStateException e) {
2867 Log.wtf(TAG, "problem enable firewall chain", e);
2868 } catch (RemoteException e) {
2869 // ignored; service lives in system_server
2870 }
2871 }
2872
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002873 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2874 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002875 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002876 } catch (RuntimeException e) {
2877 Slog.w(TAG, "problem reading network stats: " + e);
2878 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002879 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002880 // ignored; service lives in system_server
2881 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002882 }
2883 }
2884
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002885 private boolean isBandwidthControlEnabled() {
2886 final long token = Binder.clearCallingIdentity();
2887 try {
2888 return mNetworkManager.isBandwidthControlEnabled();
2889 } catch (RemoteException e) {
2890 // ignored; service lives in system_server
2891 return false;
2892 } finally {
2893 Binder.restoreCallingIdentity(token);
2894 }
2895 }
2896
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002897 /**
2898 * Try refreshing {@link #mTime} when stale.
2899 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002900 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002901 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002902 mTime.forceRefresh();
2903 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002904 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002905
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002906 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002907 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2908 }
2909
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002910 private static Intent buildAllowBackgroundDataIntent() {
2911 return new Intent(ACTION_ALLOW_BACKGROUND);
2912 }
2913
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002914 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2915 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2916 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2917 return intent;
2918 }
2919
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002920 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2921 final Intent intent = new Intent();
2922 intent.setComponent(new ComponentName(
2923 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2924 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2925 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2926 return intent;
2927 }
2928
2929 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2930 final Intent intent = new Intent();
2931 intent.setComponent(new ComponentName(
2932 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2933 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2934 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2935 return intent;
2936 }
2937
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002938 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002939 public void addIdleHandler(IdleHandler handler) {
2940 mHandler.getLooper().getQueue().addIdleHandler(handler);
2941 }
2942
Jeff Sharkey1b861272011-05-22 00:34:52 -07002943 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2944 final int size = source.size();
2945 for (int i = 0; i < size; i++) {
2946 target.put(source.keyAt(i), true);
2947 }
2948 }
2949
Stuart Scottf1fb3972015-04-02 18:00:02 -07002950 @Override
2951 public void factoryReset(String subscriber) {
2952 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2953
Stuart Scotte3e314d2015-04-20 14:07:45 -07002954 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
2955 return;
2956 }
2957
Stuart Scottf1fb3972015-04-02 18:00:02 -07002958 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07002959 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07002960 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
2961 for (NetworkPolicy policy : policies) {
2962 if (policy.template.equals(template)) {
2963 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2964 policy.inferred = false;
2965 policy.clearSnooze();
2966 }
2967 }
2968 setNetworkPolicies(policies);
2969
2970 // Turn restrict background data off
2971 setRestrictBackground(false);
2972
Stuart Scotte3e314d2015-04-20 14:07:45 -07002973 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
2974 // Remove app's "restrict background data" flag
2975 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
2976 setUidPolicy(uid, POLICY_NONE);
2977 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07002978 }
2979 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002980
2981 private class MyPackageMonitor extends PackageMonitor {
2982
2983 @Override
2984 public void onPackageRemoved(String packageName, int uid) {
2985 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
2986 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002987 removeRestrictBackgroundWhitelistedUidLocked(uid, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002988 }
2989 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002990 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002991}