blob: fc1e1f016c4d61be4a4922cf2dc75830b0a00900 [file] [log] [blame]
San Mehat873f2142010-01-14 10:25:07 -08001/*
2 * Copyright (C) 2007 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;
18
Jeff Sharkey4529bb62011-12-14 10:31:54 -080019import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey47eb1022011-08-25 17:48:52 -070020import static android.Manifest.permission.DUMP;
Sehee Parka9139bc2017-12-22 13:54:05 +090021import static android.Manifest.permission.NETWORK_SETTINGS;
Lorenzo Colitti07f13042017-07-10 19:06:57 +090022import static android.Manifest.permission.NETWORK_STACK;
Jeff Sharkeyaf75c332011-11-18 12:41:12 -080023import static android.Manifest.permission.SHUTDOWN;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070024import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
25import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_DOZABLE;
26import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_NONE;
Felipe Leme011b98f2016-02-10 17:28:31 -080027import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070028import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_STANDBY;
29import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NONE;
Felipe Leme011b98f2016-02-10 17:28:31 -080030import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070031import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
Sudheer Shanka62f5c172017-03-17 16:25:55 -070032import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070033import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Sudheer Shanka62f5c172017-03-17 16:25:55 -070034import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070035import static android.net.NetworkPolicyManager.FIREWALL_TYPE_BLACKLIST;
36import static android.net.NetworkPolicyManager.FIREWALL_TYPE_WHITELIST;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -070037import static android.net.NetworkStats.SET_DEFAULT;
Lorenzo Colittif1912ca2017-08-17 19:23:08 +090038import static android.net.NetworkStats.STATS_PER_UID;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080039import static android.net.NetworkStats.TAG_ALL;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070040import static android.net.NetworkStats.TAG_NONE;
41import static android.net.NetworkStats.UID_ALL;
Jeff Sharkeyae2c1812011-10-04 13:11:40 -070042import static android.net.TrafficStats.UID_TETHERING;
Lorenzo Colitti79751842013-02-28 16:16:03 +090043import static com.android.server.NetworkManagementService.NetdResponseCode.ClatdStatusResult;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -080044import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceGetCfgResult;
45import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceListResult;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -080046import static com.android.server.NetworkManagementService.NetdResponseCode.IpFwdStatusResult;
47import static com.android.server.NetworkManagementService.NetdResponseCode.TetherDnsFwdTgtListResult;
48import static com.android.server.NetworkManagementService.NetdResponseCode.TetherInterfaceListResult;
49import static com.android.server.NetworkManagementService.NetdResponseCode.TetherStatusResult;
Jeff Sharkeye4984be2013-09-10 21:03:27 -070050import static com.android.server.NetworkManagementService.NetdResponseCode.TetheringStatsListResult;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -080051import static com.android.server.NetworkManagementService.NetdResponseCode.TtyListResult;
Jeff Sharkeya63ba592011-07-19 23:47:12 -070052import static com.android.server.NetworkManagementSocketTagger.PROP_QTAGUID_ENABLED;
Erik Klineb2cfdfb2017-01-18 20:54:14 +090053
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070054import android.annotation.NonNull;
Sudheer Shankadc589ac2016-11-10 15:30:17 -080055import android.app.ActivityManager;
Pierre Imai8e48e672016-04-21 13:30:43 +090056import android.content.ContentResolver;
San Mehat873f2142010-01-14 10:25:07 -080057import android.content.Context;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080058import android.net.ConnectivityManager;
Lorenzo Colitti58967ba2016-02-02 17:21:21 +090059import android.net.INetd;
Luke Huang13b79e82018-09-26 14:53:42 +080060import android.net.TetherStatsParcel;
San Mehat4d02d002010-01-22 16:07:46 -080061import android.net.INetworkManagementEventObserver;
Lorenzo Colitti07f13042017-07-10 19:06:57 +090062import android.net.ITetheringStatsProvider;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070063import android.net.InterfaceConfiguration;
Luke Huang14f75442018-08-15 19:22:54 +080064import android.net.InterfaceConfigurationParcel;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +090065import android.net.IpPrefix;
Robert Greenwalted126402011-01-28 15:34:55 -080066import android.net.LinkAddress;
Lorenzo Colittib57edc52014-08-22 17:10:50 -070067import android.net.Network;
Amith Yamasani15e472352015-04-24 19:06:07 -070068import android.net.NetworkPolicyManager;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070069import android.net.NetworkStats;
Robert Greenwalted126402011-01-28 15:34:55 -080070import android.net.NetworkUtils;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070071import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040072import android.net.UidRange;
Luke Huang77017912018-10-19 15:57:05 +090073import android.net.UidRangeParcel;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +090074import android.net.util.NetdService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080075import android.net.wifi.WifiConfiguration;
76import android.net.wifi.WifiConfiguration.KeyMgmt;
Dianne Hackborn91268cf2013-06-13 19:06:50 -070077import android.os.BatteryStats;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070078import android.os.Binder;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -070079import android.os.Handler;
Lorenzo Colittia0868002017-07-11 02:29:28 +090080import android.os.IBinder;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080081import android.os.INetworkActivityListener;
San Mehat873f2142010-01-14 10:25:07 -080082import android.os.INetworkManagementService;
Lorenzo Colitti563dc452017-09-01 17:12:34 +090083import android.os.PersistableBundle;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080084import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070085import android.os.Process;
Jeff Sharkey3df273e2011-12-15 15:47:12 -080086import android.os.RemoteCallbackList;
87import android.os.RemoteException;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070088import android.os.ServiceManager;
Lorenzo Colitti4cb42402016-04-24 12:52:00 +090089import android.os.ServiceSpecificException;
Jeff Sharkey605eb792014-11-04 13:34:06 -080090import android.os.StrictMode;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070091import android.os.SystemClock;
Marco Nelissen62dbb222010-02-18 10:56:30 -080092import android.os.SystemProperties;
Felipe Leme29e72ea2016-09-08 13:26:55 -070093import android.os.Trace;
Pierre Imai8e48e672016-04-21 13:30:43 +090094import android.provider.Settings;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070095import android.telephony.DataConnectionRealTimeInfo;
96import android.telephony.PhoneStateListener;
Wink Savillefb40dd42014-06-12 17:02:31 -070097import android.telephony.SubscriptionManager;
Wink Saville67e07892014-06-18 16:43:14 -070098import android.telephony.TelephonyManager;
Erik Kline4d092232017-10-30 15:29:44 +090099import android.text.TextUtils;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800100import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800101import android.util.Slog;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700102import android.util.SparseBooleanArray;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800103import android.util.SparseIntArray;
San Mehat873f2142010-01-14 10:25:07 -0800104
Jeff Sharkey605eb792014-11-04 13:34:06 -0800105import com.android.internal.annotations.GuardedBy;
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700106import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700107import com.android.internal.app.IBatteryStats;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700108import com.android.internal.net.NetworkStatsFactory;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600109import com.android.internal.util.DumpUtils;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800110import com.android.internal.util.HexDump;
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700111import com.android.internal.util.Preconditions;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800112import com.android.server.NativeDaemonConnector.Command;
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700113import com.android.server.NativeDaemonConnector.SensitiveArg;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700114import com.google.android.collect.Maps;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700115
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700116import java.io.BufferedReader;
117import java.io.DataInputStream;
San Mehat873f2142010-01-14 10:25:07 -0800118import java.io.File;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700119import java.io.FileDescriptor;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700120import java.io.FileInputStream;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700121import java.io.IOException;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700122import java.io.InputStreamReader;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700123import java.io.PrintWriter;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700124import java.net.InetAddress;
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700125import java.net.InterfaceAddress;
126import java.net.NetworkInterface;
127import java.net.SocketException;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700128import java.util.ArrayList;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400129import java.util.Arrays;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700130import java.util.HashMap;
jiaguo1da35f72014-01-09 16:39:59 +0800131import java.util.List;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700132import java.util.Map;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700133import java.util.NoSuchElementException;
134import java.util.StringTokenizer;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700135import java.util.concurrent.CountDownLatch;
San Mehat873f2142010-01-14 10:25:07 -0800136
137/**
138 * @hide
139 */
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700140public class NetworkManagementService extends INetworkManagementService.Stub
141 implements Watchdog.Monitor {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900142
143 /**
144 * Helper class that encapsulates NetworkManagementService dependencies and makes them
145 * easier to mock in unit tests.
146 */
147 static class SystemServices {
148 public IBinder getService(String name) {
149 return ServiceManager.getService(name);
150 }
151 public void registerLocalService(NetworkManagementInternal nmi) {
152 LocalServices.addService(NetworkManagementInternal.class, nmi);
153 }
154 public INetd getNetd() {
155 return NetdService.get();
156 }
157 }
158
Amith Yamasani15e472352015-04-24 19:06:07 -0700159 private static final String TAG = "NetworkManagement";
160 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Kenny Root305bcbf2010-09-03 07:56:38 -0700161 private static final String NETD_TAG = "NetdConnector";
Lorenzo Colittia0868002017-07-11 02:29:28 +0900162 static final String NETD_SERVICE_NAME = "netd";
Kenny Root305bcbf2010-09-03 07:56:38 -0700163
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400164 private static final int MAX_UID_RANGES_PER_COMMAND = 10;
165
Luke Huang4a32bf42018-08-21 19:09:45 +0800166 private static final String[] EMPTY_STRING_ARRAY = new String[0];
167
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700168 /**
169 * Name representing {@link #setGlobalAlert(long)} limit when delivered to
170 * {@link INetworkManagementEventObserver#limitReached(String, String)}.
171 */
172 public static final String LIMIT_GLOBAL_ALERT = "globalAlert";
173
Andrew Scull45f533c2017-05-19 15:37:20 +0100174 static class NetdResponseCode {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -0700175 /* Keep in sync with system/netd/server/ResponseCode.h */
San Mehat873f2142010-01-14 10:25:07 -0800176 public static final int InterfaceListResult = 110;
177 public static final int TetherInterfaceListResult = 111;
178 public static final int TetherDnsFwdTgtListResult = 112;
San Mehat72759df2010-01-19 13:50:37 -0800179 public static final int TtyListResult = 113;
Jeff Sharkeye4984be2013-09-10 21:03:27 -0700180 public static final int TetheringStatsListResult = 114;
San Mehat873f2142010-01-14 10:25:07 -0800181
182 public static final int TetherStatusResult = 210;
183 public static final int IpFwdStatusResult = 211;
San Mehated4fc8a2010-01-22 12:28:36 -0800184 public static final int InterfaceGetCfgResult = 213;
Robert Greenwalte3253922010-02-18 09:23:25 -0800185 public static final int SoftapStatusResult = 214;
San Mehat91cac642010-03-31 14:31:36 -0700186 public static final int InterfaceRxCounterResult = 216;
187 public static final int InterfaceTxCounterResult = 217;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700188 public static final int QuotaCounterResult = 220;
189 public static final int TetheringStatsResult = 221;
Selim Gurun84c00c62012-02-27 15:42:38 -0800190 public static final int DnsProxyQueryResult = 222;
Lorenzo Colitti79751842013-02-28 16:16:03 +0900191 public static final int ClatdStatusResult = 223;
Robert Greenwalte3253922010-02-18 09:23:25 -0800192
193 public static final int InterfaceChange = 600;
JP Abgrall12b933d2011-07-14 18:09:22 -0700194 public static final int BandwidthControl = 601;
Haoyu Bai6b7358d2012-07-17 16:36:50 -0700195 public static final int InterfaceClassActivity = 613;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900196 public static final int InterfaceAddressChange = 614;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900197 public static final int InterfaceDnsServerInfo = 615;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900198 public static final int RouteChange = 616;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800199 public static final int StrictCleartext = 617;
San Mehat873f2142010-01-14 10:25:07 -0800200 }
201
Rebecca Silbersteine2ec94f2016-03-24 13:29:00 -0700202 /**
203 * String indicating a softap command.
204 */
205 static final String SOFT_AP_COMMAND = "softap";
206
207 /**
208 * String passed back to netd connector indicating softap command success.
209 */
210 static final String SOFT_AP_COMMAND_SUCCESS = "Ok";
211
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700212 static final int DAEMON_MSG_MOBILE_CONN_REAL_TIME_INFO = 1;
213
Luke Huang8a462ec2018-08-24 20:33:16 +0800214 static final boolean MODIFY_OPERATION_ADD = true;
215 static final boolean MODIFY_OPERATION_REMOVE = false;
216
San Mehat873f2142010-01-14 10:25:07 -0800217 /**
218 * Binder context for this service
219 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700220 private final Context mContext;
San Mehat873f2142010-01-14 10:25:07 -0800221
222 /**
223 * connector object for communicating with netd
224 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700225 private final NativeDaemonConnector mConnector;
San Mehat873f2142010-01-14 10:25:07 -0800226
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700227 private final Handler mFgHandler;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700228 private final Handler mDaemonHandler;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700229
Lorenzo Colittia0868002017-07-11 02:29:28 +0900230 private final SystemServices mServices;
231
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900232 private INetd mNetdService;
233
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800234 private IBatteryStats mBatteryStats;
235
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700236 private final Thread mThread;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700237 private CountDownLatch mConnectedSignal = new CountDownLatch(1);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700238
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800239 private final RemoteCallbackList<INetworkManagementEventObserver> mObservers =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700240 new RemoteCallbackList<>();
San Mehat4d02d002010-01-22 16:07:46 -0800241
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700242 private final NetworkStatsFactory mStatsFactory = new NetworkStatsFactory();
243
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900244 @GuardedBy("mTetheringStatsProviders")
245 private final HashMap<ITetheringStatsProvider, String>
246 mTetheringStatsProviders = Maps.newHashMap();
247
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700248 /**
249 * If both locks need to be held, then they should be obtained in the order:
250 * first {@link #mQuotaLock} and then {@link #mRulesLock}.
251 */
Andrew Scull45f533c2017-05-19 15:37:20 +0100252 private final Object mQuotaLock = new Object();
Andrew Scull519291f2017-05-23 13:11:03 +0100253 private final Object mRulesLock = new Object();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800254
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700255 /** Set of interfaces with active quotas. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800256 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700257 private HashMap<String, Long> mActiveQuotas = Maps.newHashMap();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700258 /** Set of interfaces with active alerts. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800259 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700260 private HashMap<String, Long> mActiveAlerts = Maps.newHashMap();
Felipe Leme65be3022016-03-22 14:53:13 -0700261 /** Set of UIDs blacklisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700262 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700263 private SparseBooleanArray mUidRejectOnMetered = new SparseBooleanArray();
264 /** Set of UIDs whitelisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700265 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700266 private SparseBooleanArray mUidAllowOnMetered = new SparseBooleanArray();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800267 /** Set of UIDs with cleartext penalties. */
268 @GuardedBy("mQuotaLock")
269 private SparseIntArray mUidCleartextPolicy = new SparseIntArray();
Amith Yamasani15e472352015-04-24 19:06:07 -0700270 /** Set of UIDs that are to be blocked/allowed by firewall controller. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700271 @GuardedBy("mRulesLock")
Amith Yamasani15e472352015-04-24 19:06:07 -0700272 private SparseIntArray mUidFirewallRules = new SparseIntArray();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700273 /**
274 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
275 * to application idles.
276 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700277 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700278 private SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
279 /**
280 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
281 * to device idles.
282 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700283 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700284 private SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800285 /**
286 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
287 * to device on power-save mode.
288 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700289 @GuardedBy("mRulesLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800290 private SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700291 /** Set of states for the child firewall chains. True if the chain is active. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700292 @GuardedBy("mRulesLock")
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700293 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700294
Felipe Leme65be3022016-03-22 14:53:13 -0700295 @GuardedBy("mQuotaLock")
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700296 private volatile boolean mDataSaverMode;
Felipe Leme65be3022016-03-22 14:53:13 -0700297
Andrew Scull45f533c2017-05-19 15:37:20 +0100298 private final Object mIdleTimerLock = new Object();
Haoyu Bai04124232012-06-28 15:26:19 -0700299 /** Set of interfaces with active idle timers. */
300 private static class IdleTimerParams {
301 public final int timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800302 public final int type;
Haoyu Bai04124232012-06-28 15:26:19 -0700303 public int networkCount;
304
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800305 IdleTimerParams(int timeout, int type) {
Haoyu Bai04124232012-06-28 15:26:19 -0700306 this.timeout = timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800307 this.type = type;
Haoyu Bai04124232012-06-28 15:26:19 -0700308 this.networkCount = 1;
309 }
310 }
311 private HashMap<String, IdleTimerParams> mActiveIdleTimers = Maps.newHashMap();
312
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700313 private volatile boolean mFirewallEnabled;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800314 private volatile boolean mStrictEnabled;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700315
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700316 private boolean mMobileActivityFromRadio = false;
317 private int mLastPowerStateFromRadio = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Adam Lesinskie08af192015-03-25 16:42:59 -0700318 private int mLastPowerStateFromWifi = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700319
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800320 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700321 new RemoteCallbackList<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800322 private boolean mNetworkActive;
323
San Mehat873f2142010-01-14 10:25:07 -0800324 /**
325 * Constructs a new NetworkManagementService instance
326 *
327 * @param context Binder context for this service
328 */
Lorenzo Colittia0868002017-07-11 02:29:28 +0900329 private NetworkManagementService(
330 Context context, String socket, SystemServices services) {
San Mehat873f2142010-01-14 10:25:07 -0800331 mContext = context;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900332 mServices = services;
San Mehat4d02d002010-01-22 16:07:46 -0800333
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700334 // make sure this is on the same looper as our NativeDaemonConnector for sync purposes
335 mFgHandler = new Handler(FgThread.get().getLooper());
336
Dianne Hackborn4590e522014-03-24 13:36:46 -0700337 // Don't need this wake lock, since we now have a time stamp for when
338 // the network actually went inactive. (It might be nice to still do this,
339 // but I don't want to do it through the power manager because that pollutes the
340 // battery stats history with pointless noise.)
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700341 //PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
Dianne Hackborn4590e522014-03-24 13:36:46 -0700342 PowerManager.WakeLock wl = null; //pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NETD_TAG);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800343
San Mehat873f2142010-01-14 10:25:07 -0800344 mConnector = new NativeDaemonConnector(
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700345 new NetdCallbackReceiver(), socket, 10, NETD_TAG, 160, wl,
346 FgThread.get().getLooper());
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700347 mThread = new Thread(mConnector, NETD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700348
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700349 mDaemonHandler = new Handler(FgThread.get().getLooper());
Wink Saville67e07892014-06-18 16:43:14 -0700350
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700351 // Add ourself to the Watchdog monitors.
352 Watchdog.getInstance().addMonitor(this);
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700353
Lorenzo Colittia0868002017-07-11 02:29:28 +0900354 mServices.registerLocalService(new LocalService());
Lorenzo Colitti8228eb32017-07-19 06:17:33 +0900355
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900356 synchronized (mTetheringStatsProviders) {
357 mTetheringStatsProviders.put(new NetdTetheringStatsProvider(), "netd");
358 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700359 }
360
361 @VisibleForTesting
362 NetworkManagementService() {
363 mConnector = null;
364 mContext = null;
365 mDaemonHandler = null;
366 mFgHandler = null;
367 mThread = null;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900368 mServices = null;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700369 }
370
Lorenzo Colittia0868002017-07-11 02:29:28 +0900371 static NetworkManagementService create(Context context, String socket, SystemServices services)
Felipe Leme03e689d2016-03-02 16:17:38 -0800372 throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900373 final NetworkManagementService service =
374 new NetworkManagementService(context, socket, services);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700375 final CountDownLatch connectedSignal = service.mConnectedSignal;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700376 if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
377 service.mThread.start();
378 if (DBG) Slog.d(TAG, "Awaiting socket connection");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700379 connectedSignal.await();
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700380 if (DBG) Slog.d(TAG, "Connected");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900381 if (DBG) Slog.d(TAG, "Connecting native netd service");
bohu07cc3bb2016-05-03 15:58:01 -0700382 service.connectNativeNetdService();
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900383 if (DBG) Slog.d(TAG, "Connected");
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700384 return service;
San Mehat873f2142010-01-14 10:25:07 -0800385 }
386
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900387 public static NetworkManagementService create(Context context) throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900388 return create(context, NETD_SERVICE_NAME, new SystemServices());
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900389 }
390
Jeff Sharkey350083e2011-06-29 10:45:16 -0700391 public void systemReady() {
Felipe Leme03e689d2016-03-02 16:17:38 -0800392 if (DBG) {
393 final long start = System.currentTimeMillis();
394 prepareNativeDaemon();
395 final long delta = System.currentTimeMillis() - start;
396 Slog.d(TAG, "Prepared in " + delta + "ms");
397 return;
398 } else {
399 prepareNativeDaemon();
400 }
Jeff Sharkey350083e2011-06-29 10:45:16 -0700401 }
402
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800403 private IBatteryStats getBatteryStats() {
404 synchronized (this) {
405 if (mBatteryStats != null) {
406 return mBatteryStats;
407 }
Lorenzo Colittia0868002017-07-11 02:29:28 +0900408 mBatteryStats =
409 IBatteryStats.Stub.asInterface(mServices.getService(BatteryStats.SERVICE_NAME));
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800410 return mBatteryStats;
411 }
412 }
413
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800414 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800415 public void registerObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800416 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800417 mObservers.register(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800418 }
419
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800420 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800421 public void unregisterObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800422 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800423 mObservers.unregister(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800424 }
425
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900426 @FunctionalInterface
427 private interface NetworkManagementEventCallback {
428 public void sendCallback(INetworkManagementEventObserver o) throws RemoteException;
429 }
430
431 private void invokeForAllObservers(NetworkManagementEventCallback eventCallback) {
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800432 final int length = mObservers.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700433 try {
434 for (int i = 0; i < length; i++) {
435 try {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900436 eventCallback.sendCallback(mObservers.getBroadcastItem(i));
Felipe Leme03e689d2016-03-02 16:17:38 -0800437 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700438 }
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700439 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700440 } finally {
441 mObservers.finishBroadcast();
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700442 }
443 }
444
445 /**
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900446 * Notify our observers of an interface status change
447 */
448 private void notifyInterfaceStatusChanged(String iface, boolean up) {
449 invokeForAllObservers(o -> o.interfaceStatusChanged(iface, up));
450 }
451
452 /**
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700453 * Notify our observers of an interface link state change
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700454 * (typically, an Ethernet cable has been plugged-in or unplugged).
455 */
456 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900457 invokeForAllObservers(o -> o.interfaceLinkStateChanged(iface, up));
San Mehat4d02d002010-01-22 16:07:46 -0800458 }
459
460 /**
461 * Notify our observers of an interface addition.
462 */
463 private void notifyInterfaceAdded(String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900464 invokeForAllObservers(o -> o.interfaceAdded(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800465 }
466
467 /**
468 * Notify our observers of an interface removal.
469 */
470 private void notifyInterfaceRemoved(String iface) {
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700471 // netd already clears out quota and alerts for removed ifaces; update
472 // our sanity-checking state.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700473 mActiveAlerts.remove(iface);
474 mActiveQuotas.remove(iface);
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700475
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900476 invokeForAllObservers(o -> o.interfaceRemoved(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800477 }
478
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700479 /**
JP Abgrall12b933d2011-07-14 18:09:22 -0700480 * Notify our observers of a limit reached.
481 */
482 private void notifyLimitReached(String limitName, String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900483 invokeForAllObservers(o -> o.limitReached(limitName, iface));
JP Abgrall12b933d2011-07-14 18:09:22 -0700484 }
485
486 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700487 * Notify our observers of a change in the data activity state of the interface
488 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700489 private void notifyInterfaceClassActivity(int type, int powerState, long tsNanos,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700490 int uid, boolean fromRadio) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700491 final boolean isMobile = ConnectivityManager.isNetworkTypeMobile(type);
492 if (isMobile) {
493 if (!fromRadio) {
494 if (mMobileActivityFromRadio) {
495 // If this call is not coming from a report from the radio itself, but we
496 // have previously received reports from the radio, then we will take the
497 // power state to just be whatever the radio last reported.
498 powerState = mLastPowerStateFromRadio;
499 }
500 } else {
501 mMobileActivityFromRadio = true;
502 }
503 if (mLastPowerStateFromRadio != powerState) {
504 mLastPowerStateFromRadio = powerState;
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700505 try {
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700506 getBatteryStats().noteMobileRadioPowerState(powerState, tsNanos, uid);
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700507 } catch (RemoteException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700508 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700509 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700510 }
511
Adam Lesinskie08af192015-03-25 16:42:59 -0700512 if (ConnectivityManager.isNetworkTypeWifi(type)) {
513 if (mLastPowerStateFromWifi != powerState) {
514 mLastPowerStateFromWifi = powerState;
515 try {
Adam Lesinski5f056f62016-07-14 16:56:08 -0700516 getBatteryStats().noteWifiRadioPowerState(powerState, tsNanos, uid);
Adam Lesinskie08af192015-03-25 16:42:59 -0700517 } catch (RemoteException e) {
518 }
519 }
520 }
521
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700522 boolean isActive = powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
523 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
524
525 if (!isMobile || fromRadio || !mMobileActivityFromRadio) {
526 // Report the change in data activity. We don't do this if this is a change
527 // on the mobile network, that is not coming from the radio itself, and we
528 // have previously seen change reports from the radio. In that case only
529 // the radio is the authority for the current state.
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900530 final boolean active = isActive;
531 invokeForAllObservers(o -> o.interfaceClassDataActivityChanged(
532 Integer.toString(type), active, tsNanos));
Haoyu Baidb3c8672012-06-20 14:29:57 -0700533 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800534
535 boolean report = false;
536 synchronized (mIdleTimerLock) {
537 if (mActiveIdleTimers.isEmpty()) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700538 // If there are no idle timers, we are not monitoring activity, so we
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800539 // are always considered active.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700540 isActive = true;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800541 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700542 if (mNetworkActive != isActive) {
543 mNetworkActive = isActive;
544 report = isActive;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800545 }
546 }
547 if (report) {
548 reportNetworkActive();
549 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700550 }
551
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900552 @Override
553 public void registerTetheringStatsProvider(ITetheringStatsProvider provider, String name) {
554 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
555 Preconditions.checkNotNull(provider);
556 synchronized(mTetheringStatsProviders) {
557 mTetheringStatsProviders.put(provider, name);
558 }
559 }
560
561 @Override
562 public void unregisterTetheringStatsProvider(ITetheringStatsProvider provider) {
563 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
564 synchronized(mTetheringStatsProviders) {
565 mTetheringStatsProviders.remove(provider);
566 }
567 }
568
Lorenzo Colitti9f0baa92017-08-15 19:25:51 +0900569 @Override
570 public void tetherLimitReached(ITetheringStatsProvider provider) {
571 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
572 synchronized(mTetheringStatsProviders) {
573 if (!mTetheringStatsProviders.containsKey(provider)) {
574 return;
575 }
576 // No current code examines the interface parameter in a global alert. Just pass null.
577 notifyLimitReached(LIMIT_GLOBAL_ALERT, null);
578 }
579 }
580
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900581 // Sync the state of the given chain with the native daemon.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700582 private void syncFirewallChainLocked(int chain, String name) {
583 SparseIntArray rules;
584 synchronized (mRulesLock) {
585 final SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900586 // Make a copy of the current rules, and then clear them. This is because
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700587 // setFirewallUidRuleInternal only pushes down rules to the native daemon if they
588 // are different from the current rules stored in the mUidFirewall*Rules array for
589 // the specified chain. If we don't clear the rules, setFirewallUidRuleInternal
590 // will do nothing.
591 rules = uidFirewallRules.clone();
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900592 uidFirewallRules.clear();
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700593 }
594 if (rules.size() > 0) {
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900595 // Now push the rules. setFirewallUidRuleInternal will push each of these down to the
596 // native daemon, and also add them to the mUidFirewall*Rules array for the specified
597 // chain.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700598 if (DBG) Slog.d(TAG, "Pushing " + rules.size() + " active firewall "
599 + name + "UID rules");
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900600 for (int i = 0; i < rules.size(); i++) {
Felipe Lemea701cad2016-05-12 09:58:14 -0700601 setFirewallUidRuleLocked(chain, rules.keyAt(i), rules.valueAt(i));
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900602 }
603 }
604 }
605
bohu07cc3bb2016-05-03 15:58:01 -0700606 private void connectNativeNetdService() {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900607 mNetdService = mServices.getNetd();
bohu07cc3bb2016-05-03 15:58:01 -0700608 }
609
610 /**
611 * Prepare native daemon once connected, enabling modules and pushing any
612 * existing in-memory rules.
613 */
614 private void prepareNativeDaemon() {
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900615
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700616 // push any existing quota or UID rules
617 synchronized (mQuotaLock) {
Felipe Leme65be3022016-03-22 14:53:13 -0700618
Luke Huang56a03a02018-09-07 12:02:16 +0800619 // Netd unconditionally enable bandwidth control
620 SystemProperties.set(PROP_QTAGUID_ENABLED, "1");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900621
Luke Huang473eb872018-07-26 17:33:14 +0800622 mStrictEnabled = true;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900623
Felipe Leme65be3022016-03-22 14:53:13 -0700624 setDataSaverModeEnabled(mDataSaverMode);
625
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700626 int size = mActiveQuotas.size();
627 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800628 if (DBG) Slog.d(TAG, "Pushing " + size + " active quota rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700629 final HashMap<String, Long> activeQuotas = mActiveQuotas;
630 mActiveQuotas = Maps.newHashMap();
631 for (Map.Entry<String, Long> entry : activeQuotas.entrySet()) {
632 setInterfaceQuota(entry.getKey(), entry.getValue());
633 }
634 }
635
636 size = mActiveAlerts.size();
637 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800638 if (DBG) Slog.d(TAG, "Pushing " + size + " active alert rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700639 final HashMap<String, Long> activeAlerts = mActiveAlerts;
640 mActiveAlerts = Maps.newHashMap();
641 for (Map.Entry<String, Long> entry : activeAlerts.entrySet()) {
642 setInterfaceAlert(entry.getKey(), entry.getValue());
643 }
644 }
645
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700646 SparseBooleanArray uidRejectOnQuota = null;
647 SparseBooleanArray uidAcceptOnQuota = null;
648 synchronized (mRulesLock) {
649 size = mUidRejectOnMetered.size();
650 if (size > 0) {
651 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered blacklist rules");
652 uidRejectOnQuota = mUidRejectOnMetered;
653 mUidRejectOnMetered = new SparseBooleanArray();
654 }
655
656 size = mUidAllowOnMetered.size();
657 if (size > 0) {
658 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered whitelist rules");
659 uidAcceptOnQuota = mUidAllowOnMetered;
660 mUidAllowOnMetered = new SparseBooleanArray();
661 }
662 }
663 if (uidRejectOnQuota != null) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700664 for (int i = 0; i < uidRejectOnQuota.size(); i++) {
Felipe Leme65be3022016-03-22 14:53:13 -0700665 setUidMeteredNetworkBlacklist(uidRejectOnQuota.keyAt(i),
666 uidRejectOnQuota.valueAt(i));
667 }
668 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700669 if (uidAcceptOnQuota != null) {
Felipe Leme65be3022016-03-22 14:53:13 -0700670 for (int i = 0; i < uidAcceptOnQuota.size(); i++) {
671 setUidMeteredNetworkWhitelist(uidAcceptOnQuota.keyAt(i),
672 uidAcceptOnQuota.valueAt(i));
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700673 }
674 }
Jeff Sharkey605eb792014-11-04 13:34:06 -0800675
676 size = mUidCleartextPolicy.size();
677 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800678 if (DBG) Slog.d(TAG, "Pushing " + size + " active UID cleartext policies");
Jeff Sharkey605eb792014-11-04 13:34:06 -0800679 final SparseIntArray local = mUidCleartextPolicy;
680 mUidCleartextPolicy = new SparseIntArray();
681 for (int i = 0; i < local.size(); i++) {
682 setUidCleartextNetworkPolicy(local.keyAt(i), local.valueAt(i));
683 }
684 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700685
Robin Leec3736bc2017-03-10 16:19:54 +0000686 setFirewallEnabled(mFirewallEnabled);
Amith Yamasani15e472352015-04-24 19:06:07 -0700687
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700688 syncFirewallChainLocked(FIREWALL_CHAIN_NONE, "");
689 syncFirewallChainLocked(FIREWALL_CHAIN_STANDBY, "standby ");
690 syncFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, "dozable ");
691 syncFirewallChainLocked(FIREWALL_CHAIN_POWERSAVE, "powersave ");
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700692
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700693 final int[] chains =
694 {FIREWALL_CHAIN_STANDBY, FIREWALL_CHAIN_DOZABLE, FIREWALL_CHAIN_POWERSAVE};
695 for (int chain : chains) {
696 if (getFirewallChainState(chain)) {
697 setFirewallChainEnabled(chain, true);
698 }
Felipe Leme011b98f2016-02-10 17:28:31 -0800699 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700700 }
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900701
Luke Huang56a03a02018-09-07 12:02:16 +0800702
703 try {
704 getBatteryStats().noteNetworkStatsEnabled();
705 } catch (RemoteException e) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900706 }
707
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700708 }
San Mehat4d02d002010-01-22 16:07:46 -0800709
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900710 /**
711 * Notify our observers of a new or updated interface address.
712 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900713 private void notifyAddressUpdated(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900714 invokeForAllObservers(o -> o.addressUpdated(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900715 }
716
717 /**
718 * Notify our observers of a deleted interface address.
719 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900720 private void notifyAddressRemoved(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900721 invokeForAllObservers(o -> o.addressRemoved(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900722 }
723
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900724 /**
725 * Notify our observers of DNS server information received.
726 */
727 private void notifyInterfaceDnsServerInfo(String iface, long lifetime, String[] addresses) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900728 invokeForAllObservers(o -> o.interfaceDnsServerInfo(iface, lifetime, addresses));
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900729 }
730
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900731 /**
732 * Notify our observers of a route change.
733 */
734 private void notifyRouteChange(String action, RouteInfo route) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900735 if (action.equals("updated")) {
736 invokeForAllObservers(o -> o.routeUpdated(route));
737 } else {
738 invokeForAllObservers(o -> o.routeRemoved(route));
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900739 }
740 }
741
San Mehat873f2142010-01-14 10:25:07 -0800742 //
743 // Netd Callback handling
744 //
745
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700746 private class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
747 @Override
San Mehat873f2142010-01-14 10:25:07 -0800748 public void onDaemonConnected() {
Felipe Leme65be3022016-03-22 14:53:13 -0700749 Slog.i(TAG, "onDaemonConnected()");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700750 // event is dispatched from internal NDC thread, so we prepare the
751 // daemon back on main thread.
752 if (mConnectedSignal != null) {
bohu07cc3bb2016-05-03 15:58:01 -0700753 // The system is booting and we're connecting to netd for the first time.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700754 mConnectedSignal.countDown();
755 mConnectedSignal = null;
756 } else {
bohu07cc3bb2016-05-03 15:58:01 -0700757 // We're reconnecting to netd after the socket connection
758 // was interrupted (e.g., if it crashed).
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700759 mFgHandler.post(new Runnable() {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700760 @Override
761 public void run() {
bohu07cc3bb2016-05-03 15:58:01 -0700762 connectNativeNetdService();
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700763 prepareNativeDaemon();
764 }
765 });
766 }
San Mehat873f2142010-01-14 10:25:07 -0800767 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700768
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700769 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800770 public boolean onCheckHoldWakeLock(int code) {
771 return code == NetdResponseCode.InterfaceClassActivity;
772 }
773
774 @Override
San Mehat873f2142010-01-14 10:25:07 -0800775 public boolean onEvent(int code, String raw, String[] cooked) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900776 String errorMessage = String.format("Invalid event from daemon (%s)", raw);
JP Abgrall12b933d2011-07-14 18:09:22 -0700777 switch (code) {
778 case NetdResponseCode.InterfaceChange:
779 /*
780 * a network interface change occured
781 * Format: "NNN Iface added <name>"
782 * "NNN Iface removed <name>"
783 * "NNN Iface changed <name> <up/down>"
784 * "NNN Iface linkstatus <name> <up/down>"
785 */
786 if (cooked.length < 4 || !cooked[1].equals("Iface")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900787 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700788 }
789 if (cooked[2].equals("added")) {
790 notifyInterfaceAdded(cooked[3]);
791 return true;
792 } else if (cooked[2].equals("removed")) {
793 notifyInterfaceRemoved(cooked[3]);
794 return true;
795 } else if (cooked[2].equals("changed") && cooked.length == 5) {
796 notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
797 return true;
798 } else if (cooked[2].equals("linkstate") && cooked.length == 5) {
799 notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
800 return true;
801 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900802 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700803 // break;
804 case NetdResponseCode.BandwidthControl:
805 /*
806 * Bandwidth control needs some attention
807 * Format: "NNN limit alert <alertName> <ifaceName>"
808 */
809 if (cooked.length < 5 || !cooked[1].equals("limit")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900810 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700811 }
812 if (cooked[2].equals("alert")) {
813 notifyLimitReached(cooked[3], cooked[4]);
814 return true;
815 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900816 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700817 // break;
Haoyu Baidb3c8672012-06-20 14:29:57 -0700818 case NetdResponseCode.InterfaceClassActivity:
819 /*
820 * An network interface class state changed (active/idle)
821 * Format: "NNN IfaceClass <active/idle> <label>"
822 */
823 if (cooked.length < 4 || !cooked[1].equals("IfaceClass")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900824 throw new IllegalStateException(errorMessage);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700825 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700826 long timestampNanos = 0;
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700827 int processUid = -1;
828 if (cooked.length >= 5) {
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700829 try {
830 timestampNanos = Long.parseLong(cooked[4]);
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700831 if (cooked.length == 6) {
832 processUid = Integer.parseInt(cooked[5]);
833 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700834 } catch(NumberFormatException ne) {}
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700835 } else {
836 timestampNanos = SystemClock.elapsedRealtimeNanos();
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700837 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700838 boolean isActive = cooked[2].equals("active");
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700839 notifyInterfaceClassActivity(Integer.parseInt(cooked[3]),
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700840 isActive ? DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700841 : DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
842 timestampNanos, processUid, false);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700843 return true;
844 // break;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900845 case NetdResponseCode.InterfaceAddressChange:
846 /*
847 * A network address change occurred
848 * Format: "NNN Address updated <addr> <iface> <flags> <scope>"
849 * "NNN Address removed <addr> <iface> <flags> <scope>"
850 */
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900851 if (cooked.length < 7 || !cooked[1].equals("Address")) {
852 throw new IllegalStateException(errorMessage);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900853 }
854
Lorenzo Colitti64483942013-11-15 18:43:52 +0900855 String iface = cooked[4];
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900856 LinkAddress address;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900857 try {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900858 int flags = Integer.parseInt(cooked[5]);
859 int scope = Integer.parseInt(cooked[6]);
860 address = new LinkAddress(cooked[3], flags, scope);
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900861 } catch(NumberFormatException e) { // Non-numeric lifetime or scope.
862 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti64483942013-11-15 18:43:52 +0900863 } catch(IllegalArgumentException e) { // Malformed/invalid IP address.
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900864 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900865 }
866
867 if (cooked[2].equals("updated")) {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900868 notifyAddressUpdated(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900869 } else {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900870 notifyAddressRemoved(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900871 }
872 return true;
873 // break;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900874 case NetdResponseCode.InterfaceDnsServerInfo:
875 /*
876 * Information about available DNS servers has been received.
877 * Format: "NNN DnsInfo servers <interface> <lifetime> <servers>"
878 */
879 long lifetime; // Actually a 32-bit unsigned integer.
880
881 if (cooked.length == 6 &&
882 cooked[1].equals("DnsInfo") &&
883 cooked[2].equals("servers")) {
884 try {
885 lifetime = Long.parseLong(cooked[4]);
886 } catch (NumberFormatException e) {
887 throw new IllegalStateException(errorMessage);
888 }
889 String[] servers = cooked[5].split(",");
890 notifyInterfaceDnsServerInfo(cooked[3], lifetime, servers);
891 }
892 return true;
893 // break;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900894 case NetdResponseCode.RouteChange:
895 /*
896 * A route has been updated or removed.
897 * Format: "NNN Route <updated|removed> <dst> [via <gateway] [dev <iface>]"
898 */
899 if (!cooked[1].equals("Route") || cooked.length < 6) {
900 throw new IllegalStateException(errorMessage);
901 }
902
903 String via = null;
904 String dev = null;
905 boolean valid = true;
906 for (int i = 4; (i + 1) < cooked.length && valid; i += 2) {
907 if (cooked[i].equals("dev")) {
908 if (dev == null) {
909 dev = cooked[i+1];
910 } else {
911 valid = false; // Duplicate interface.
912 }
913 } else if (cooked[i].equals("via")) {
914 if (via == null) {
915 via = cooked[i+1];
916 } else {
917 valid = false; // Duplicate gateway.
918 }
919 } else {
920 valid = false; // Unknown syntax.
921 }
922 }
923 if (valid) {
924 try {
925 // InetAddress.parseNumericAddress(null) inexplicably returns ::1.
926 InetAddress gateway = null;
927 if (via != null) gateway = InetAddress.parseNumericAddress(via);
928 RouteInfo route = new RouteInfo(new IpPrefix(cooked[3]), gateway, dev);
929 notifyRouteChange(cooked[2], route);
930 return true;
931 } catch (IllegalArgumentException e) {}
932 }
933 throw new IllegalStateException(errorMessage);
934 // break;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800935 case NetdResponseCode.StrictCleartext:
936 final int uid = Integer.parseInt(cooked[1]);
937 final byte[] firstPacket = HexDump.hexStringToByteArray(cooked[2]);
938 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800939 ActivityManager.getService().notifyCleartextNetwork(uid, firstPacket);
Jeff Sharkey605eb792014-11-04 13:34:06 -0800940 } catch (RemoteException ignored) {
941 }
942 break;
JP Abgrall12b933d2011-07-14 18:09:22 -0700943 default: break;
Robert Greenwalte3253922010-02-18 09:23:25 -0800944 }
945 return false;
San Mehat873f2142010-01-14 10:25:07 -0800946 }
947 }
948
San Mehated4fc8a2010-01-22 12:28:36 -0800949
San Mehat873f2142010-01-14 10:25:07 -0800950 //
951 // INetworkManagementService members
952 //
Erik Kline4e37b702016-07-05 11:34:21 +0900953 @Override
954 public INetd getNetdService() throws RemoteException {
955 final CountDownLatch connectedSignal = mConnectedSignal;
956 if (connectedSignal != null) {
957 try {
958 connectedSignal.await();
959 } catch (InterruptedException ignored) {}
960 }
961
962 return mNetdService;
963 }
San Mehat873f2142010-01-14 10:25:07 -0800964
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800965 @Override
966 public String[] listInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800967 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700968 try {
Luke Huang14f75442018-08-15 19:22:54 +0800969 final List<String> result = mNetdService.interfaceGetList();
970 return result.toArray(EMPTY_STRING_ARRAY);
971 } catch (RemoteException | ServiceSpecificException e) {
972 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700973 }
San Mehated4fc8a2010-01-22 12:28:36 -0800974 }
975
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800976 @Override
977 public InterfaceConfiguration getInterfaceConfig(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800978 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang14f75442018-08-15 19:22:54 +0800979 final InterfaceConfigurationParcel result;
Kenny Roota80ce062010-06-01 13:23:53 -0700980 try {
Luke Huang14f75442018-08-15 19:22:54 +0800981 result = mNetdService.interfaceGetCfg(iface);
982 } catch (RemoteException | ServiceSpecificException e) {
983 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700984 }
San Mehated4fc8a2010-01-22 12:28:36 -0800985
San Mehated4fc8a2010-01-22 12:28:36 -0800986 try {
Luke Huang14f75442018-08-15 19:22:54 +0800987 final InterfaceConfiguration cfg = InterfaceConfiguration.fromParcel(result);
988 return cfg;
989 } catch (IllegalArgumentException iae) {
990 throw new IllegalStateException("Invalid InterfaceConfigurationParcel", iae);
San Mehated4fc8a2010-01-22 12:28:36 -0800991 }
San Mehated4fc8a2010-01-22 12:28:36 -0800992 }
993
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800994 @Override
995 public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800996 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800997 LinkAddress linkAddr = cfg.getLinkAddress();
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800998 if (linkAddr == null || linkAddr.getAddress() == null) {
999 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -08001000 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001001
Luke Huang14f75442018-08-15 19:22:54 +08001002 final InterfaceConfigurationParcel cfgParcel = cfg.toParcel(iface);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001003
Kenny Roota80ce062010-06-01 13:23:53 -07001004 try {
Luke Huang14f75442018-08-15 19:22:54 +08001005 mNetdService.interfaceSetCfg(cfgParcel);
1006 } catch (RemoteException | ServiceSpecificException e) {
1007 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001008 }
San Mehat873f2142010-01-14 10:25:07 -08001009 }
1010
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001011 @Override
1012 public void setInterfaceDown(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001013 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001014 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001015 ifcg.setInterfaceDown();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001016 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001017 }
1018
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001019 @Override
1020 public void setInterfaceUp(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001021 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001022 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001023 ifcg.setInterfaceUp();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001024 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001025 }
1026
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001027 @Override
1028 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001029 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sheriff73293612011-09-14 12:31:56 -07001030 try {
Luke Huang14f75442018-08-15 19:22:54 +08001031 mNetdService.interfaceSetIPv6PrivacyExtensions(iface, enable);
1032 } catch (RemoteException | ServiceSpecificException e) {
1033 throw new IllegalStateException(e);
Irfan Sheriff73293612011-09-14 12:31:56 -07001034 }
1035 }
1036
Irfan Sherifff5600612011-06-16 10:26:28 -07001037 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
1038 IPv6 addresses on interface down, but we need to do full clean up here */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001039 @Override
1040 public void clearInterfaceAddresses(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001041 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sherifff5600612011-06-16 10:26:28 -07001042 try {
Luke Huang14f75442018-08-15 19:22:54 +08001043 mNetdService.interfaceClearAddrs(iface);
1044 } catch (RemoteException | ServiceSpecificException e) {
1045 throw new IllegalStateException(e);
Irfan Sherifff5600612011-06-16 10:26:28 -07001046 }
1047 }
1048
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001049 @Override
1050 public void enableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001051 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001052 try {
Luke Huang14f75442018-08-15 19:22:54 +08001053 mNetdService.interfaceSetEnableIPv6(iface, true);
1054 } catch (RemoteException | ServiceSpecificException e) {
1055 throw new IllegalStateException(e);
repo sync7960d9f2011-09-29 12:40:02 -07001056 }
1057 }
1058
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001059 @Override
Joel Scherpelz2db10742017-06-07 15:38:38 +09001060 public void setIPv6AddrGenMode(String iface, int mode) throws ServiceSpecificException {
1061 try {
1062 mNetdService.setIPv6AddrGenMode(iface, mode);
1063 } catch (RemoteException e) {
1064 throw e.rethrowAsRuntimeException();
1065 }
1066 }
1067
1068 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001069 public void disableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001070 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001071 try {
Luke Huang14f75442018-08-15 19:22:54 +08001072 mNetdService.interfaceSetEnableIPv6(iface, false);
1073 } catch (RemoteException | ServiceSpecificException e) {
1074 throw new IllegalStateException(e);
repo sync7960d9f2011-09-29 12:40:02 -07001075 }
1076 }
1077
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001078 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001079 public void addRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001080 modifyRoute(MODIFY_OPERATION_ADD, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001081 }
1082
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001083 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001084 public void removeRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001085 modifyRoute(MODIFY_OPERATION_REMOVE, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001086 }
1087
Luke Huang8a462ec2018-08-24 20:33:16 +08001088 private void modifyRoute(boolean add, int netId, RouteInfo route) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001089 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001090
Luke Huang8a462ec2018-08-24 20:33:16 +08001091 final String ifName = route.getInterface();
1092 final String dst = route.getDestination().toString();
1093 final String nextHop;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001094
1095 switch (route.getType()) {
1096 case RouteInfo.RTN_UNICAST:
1097 if (route.hasGateway()) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001098 nextHop = route.getGateway().getHostAddress();
1099 } else {
1100 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001101 }
1102 break;
1103 case RouteInfo.RTN_UNREACHABLE:
Luke Huang8a462ec2018-08-24 20:33:16 +08001104 nextHop = INetd.NEXTHOP_UNREACHABLE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001105 break;
1106 case RouteInfo.RTN_THROW:
Luke Huang8a462ec2018-08-24 20:33:16 +08001107 nextHop = INetd.NEXTHOP_THROW;
1108 break;
1109 default:
1110 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001111 break;
Sreeram Ramachandran1fbcb272014-05-22 16:30:48 -07001112 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001113 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08001114 if (add) {
1115 mNetdService.networkAddRoute(netId, ifName, dst, nextHop);
1116 } else {
1117 mNetdService.networkRemoveRoute(netId, ifName, dst, nextHop);
1118 }
1119 } catch (RemoteException | ServiceSpecificException e) {
1120 throw new IllegalStateException(e);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001121 }
1122 }
1123
1124 private ArrayList<String> readRouteList(String filename) {
1125 FileInputStream fstream = null;
Christopher Wiley212b95f2016-08-02 11:38:57 -07001126 ArrayList<String> list = new ArrayList<>();
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001127
1128 try {
1129 fstream = new FileInputStream(filename);
1130 DataInputStream in = new DataInputStream(fstream);
1131 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1132 String s;
1133
1134 // throw away the title line
1135
1136 while (((s = br.readLine()) != null) && (s.length() != 0)) {
1137 list.add(s);
1138 }
1139 } catch (IOException ex) {
1140 // return current list, possibly empty
1141 } finally {
1142 if (fstream != null) {
1143 try {
1144 fstream.close();
1145 } catch (IOException ex) {}
1146 }
1147 }
1148
1149 return list;
1150 }
1151
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001152 @Override
sy.yun9d9b74a2013-09-02 05:24:09 +09001153 public void setMtu(String iface, int mtu) {
1154 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1155
sy.yun9d9b74a2013-09-02 05:24:09 +09001156 try {
Luke Huang14f75442018-08-15 19:22:54 +08001157 mNetdService.interfaceSetMtu(iface, mtu);
1158 } catch (RemoteException | ServiceSpecificException e) {
1159 throw new IllegalStateException(e);
sy.yun9d9b74a2013-09-02 05:24:09 +09001160 }
1161 }
1162
1163 @Override
San Mehat873f2142010-01-14 10:25:07 -08001164 public void shutdown() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001165 // TODO: remove from aidl if nobody calls externally
1166 mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001167
Felipe Leme03e689d2016-03-02 16:17:38 -08001168 Slog.i(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -08001169 }
1170
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001171 @Override
San Mehat873f2142010-01-14 10:25:07 -08001172 public boolean getIpForwardingEnabled() throws IllegalStateException{
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001173 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001174
Kenny Roota80ce062010-06-01 13:23:53 -07001175 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001176 final boolean isEnabled = mNetdService.ipfwdEnabled();
1177 return isEnabled;
1178 } catch (RemoteException | ServiceSpecificException e) {
1179 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001180 }
San Mehat873f2142010-01-14 10:25:07 -08001181 }
1182
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001183 @Override
1184 public void setIpForwardingEnabled(boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001185 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001186 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001187 if (enable) {
1188 mNetdService.ipfwdEnableForwarding("tethering");
1189 } else {
1190 mNetdService.ipfwdDisableForwarding("tethering");
1191 }
1192 } catch (RemoteException | ServiceSpecificException e) {
1193 throw new IllegalStateException(e);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001194 }
San Mehat873f2142010-01-14 10:25:07 -08001195 }
1196
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001197 @Override
1198 public void startTethering(String[] dhcpRange) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001199 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -07001200 // an odd number of addrs will fail
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001201
Kenny Roota80ce062010-06-01 13:23:53 -07001202 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001203 mNetdService.tetherStart(dhcpRange);
1204 } catch (RemoteException | ServiceSpecificException e) {
1205 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001206 }
San Mehat873f2142010-01-14 10:25:07 -08001207 }
1208
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001209 @Override
1210 public void stopTethering() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001211 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001212 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001213 mNetdService.tetherStop();
1214 } catch (RemoteException | ServiceSpecificException e) {
1215 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001216 }
San Mehat873f2142010-01-14 10:25:07 -08001217 }
1218
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001219 @Override
1220 public boolean isTetheringStarted() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001221 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001222
Kenny Roota80ce062010-06-01 13:23:53 -07001223 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001224 final boolean isEnabled = mNetdService.tetherIsEnabled();
1225 return isEnabled;
1226 } catch (RemoteException | ServiceSpecificException e) {
1227 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001228 }
San Mehat873f2142010-01-14 10:25:07 -08001229 }
Matthew Xiefe19f122012-07-12 16:03:32 -07001230
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001231 @Override
1232 public void tetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001233 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001234 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001235 mNetdService.tetherInterfaceAdd(iface);
1236 } catch (RemoteException | ServiceSpecificException e) {
1237 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001238 }
Christopher Wiley212b95f2016-08-02 11:38:57 -07001239 List<RouteInfo> routes = new ArrayList<>();
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07001240 // The RouteInfo constructor truncates the LinkAddress to a network prefix, thus making it
1241 // suitable to use as a route destination.
1242 routes.add(new RouteInfo(getInterfaceConfig(iface).getLinkAddress(), null, iface));
1243 addInterfaceToLocalNetwork(iface, routes);
San Mehat873f2142010-01-14 10:25:07 -08001244 }
1245
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001246 @Override
San Mehat873f2142010-01-14 10:25:07 -08001247 public void untetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001248 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001249 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001250 mNetdService.tetherInterfaceRemove(iface);
1251 } catch (RemoteException | ServiceSpecificException e) {
1252 throw new IllegalStateException(e);
Erik Kline1f4278a2016-08-16 16:46:33 +09001253 } finally {
1254 removeInterfaceFromLocalNetwork(iface);
Kenny Roota80ce062010-06-01 13:23:53 -07001255 }
San Mehat873f2142010-01-14 10:25:07 -08001256 }
1257
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001258 @Override
1259 public String[] listTetheredInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001260 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001261 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001262 final List<String> result = mNetdService.tetherInterfaceList();
1263 return result.toArray(EMPTY_STRING_ARRAY);
1264 } catch (RemoteException | ServiceSpecificException e) {
1265 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001266 }
San Mehat873f2142010-01-14 10:25:07 -08001267 }
1268
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001269 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001270 public void setDnsForwarders(Network network, String[] dns) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001271 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001272
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001273 int netId = (network != null) ? network.netId : ConnectivityManager.NETID_UNSET;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001274
San Mehat873f2142010-01-14 10:25:07 -08001275 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001276 mNetdService.tetherDnsSet(netId, dns);
1277 } catch (RemoteException | ServiceSpecificException e) {
1278 throw new IllegalStateException(e);
San Mehat873f2142010-01-14 10:25:07 -08001279 }
1280 }
1281
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001282 @Override
1283 public String[] getDnsForwarders() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001284 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001285 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001286 final List<String> result = mNetdService.tetherDnsList();
1287 return result.toArray(EMPTY_STRING_ARRAY);
1288 } catch (RemoteException | ServiceSpecificException e) {
1289 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001290 }
San Mehat873f2142010-01-14 10:25:07 -08001291 }
1292
jiaguo1da35f72014-01-09 16:39:59 +08001293 private List<InterfaceAddress> excludeLinkLocal(List<InterfaceAddress> addresses) {
Christopher Wiley212b95f2016-08-02 11:38:57 -07001294 ArrayList<InterfaceAddress> filtered = new ArrayList<>(addresses.size());
jiaguo1da35f72014-01-09 16:39:59 +08001295 for (InterfaceAddress ia : addresses) {
1296 if (!ia.getAddress().isLinkLocalAddress())
1297 filtered.add(ia);
1298 }
1299 return filtered;
1300 }
1301
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001302 private void modifyInterfaceForward(boolean add, String fromIface, String toIface) {
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001303 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001304 if (add) {
1305 mNetdService.ipfwdAddInterfaceForward(fromIface, toIface);
1306 } else {
1307 mNetdService.ipfwdRemoveInterfaceForward(fromIface, toIface);
1308 }
1309 } catch (RemoteException | ServiceSpecificException e) {
1310 throw new IllegalStateException(e);
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001311 }
1312 }
1313
1314 @Override
1315 public void startInterfaceForwarding(String fromIface, String toIface) {
1316 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1317 modifyInterfaceForward(true, fromIface, toIface);
1318 }
1319
1320 @Override
1321 public void stopInterfaceForwarding(String fromIface, String toIface) {
1322 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1323 modifyInterfaceForward(false, fromIface, toIface);
1324 }
1325
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001326 @Override
1327 public void enableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001328 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001329 try {
Luke Huanga31e0732018-10-22 13:23:10 +09001330 mNetdService.tetherAddForward(internalInterface, externalInterface);
1331 } catch (RemoteException | ServiceSpecificException e) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001332 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001333 }
San Mehat873f2142010-01-14 10:25:07 -08001334 }
1335
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001336 @Override
1337 public void disableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001338 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001339 try {
Luke Huanga31e0732018-10-22 13:23:10 +09001340 mNetdService.tetherRemoveForward(internalInterface, externalInterface);
1341 } catch (RemoteException | ServiceSpecificException e) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001342 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001343 }
San Mehat873f2142010-01-14 10:25:07 -08001344 }
San Mehat72759df2010-01-19 13:50:37 -08001345
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001346 @Override
1347 public String[] listTtys() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001348 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001349 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001350 return NativeDaemonEvent.filterMessageList(
1351 mConnector.executeForList("list_ttys"), TtyListResult);
Kenny Roota80ce062010-06-01 13:23:53 -07001352 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001353 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001354 }
San Mehat72759df2010-01-19 13:50:37 -08001355 }
1356
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001357 @Override
1358 public void attachPppd(
1359 String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001360 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat72759df2010-01-19 13:50:37 -08001361 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001362 mConnector.execute("pppd", "attach", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -08001363 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
1364 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
1365 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001366 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress());
Kenny Roota80ce062010-06-01 13:23:53 -07001367 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001368 throw e.rethrowAsParcelableException();
San Mehat72759df2010-01-19 13:50:37 -08001369 }
1370 }
1371
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001372 @Override
1373 public void detachPppd(String tty) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001374 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001375 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001376 mConnector.execute("pppd", "detach", tty);
Kenny Roota80ce062010-06-01 13:23:53 -07001377 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001378 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001379 }
San Mehat72759df2010-01-19 13:50:37 -08001380 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -08001381
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001382 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001383 public void addIdleTimer(String iface, int timeout, final int type) {
Haoyu Bai04124232012-06-28 15:26:19 -07001384 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1385
1386 if (DBG) Slog.d(TAG, "Adding idletimer");
1387
1388 synchronized (mIdleTimerLock) {
1389 IdleTimerParams params = mActiveIdleTimers.get(iface);
1390 if (params != null) {
1391 // the interface already has idletimer, update network count
1392 params.networkCount++;
1393 return;
1394 }
1395
1396 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001397 mNetdService.idletimerAddInterface(iface, timeout, Integer.toString(type));
1398 } catch (RemoteException | ServiceSpecificException e) {
1399 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001400 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001401 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
1402
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001403 // Networks start up.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001404 if (ConnectivityManager.isNetworkTypeMobile(type)) {
1405 mNetworkActive = false;
1406 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001407 mDaemonHandler.post(new Runnable() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001408 @Override public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001409 notifyInterfaceClassActivity(type,
1410 DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07001411 SystemClock.elapsedRealtimeNanos(), -1, false);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001412 }
1413 });
Haoyu Bai04124232012-06-28 15:26:19 -07001414 }
1415 }
1416
1417 @Override
1418 public void removeIdleTimer(String iface) {
1419 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1420
1421 if (DBG) Slog.d(TAG, "Removing idletimer");
1422
1423 synchronized (mIdleTimerLock) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001424 final IdleTimerParams params = mActiveIdleTimers.get(iface);
Haoyu Bai04124232012-06-28 15:26:19 -07001425 if (params == null || --(params.networkCount) > 0) {
1426 return;
1427 }
1428
1429 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001430 mNetdService.idletimerRemoveInterface(iface,
1431 params.timeout, Integer.toString(params.type));
1432 } catch (RemoteException | ServiceSpecificException e) {
1433 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001434 }
1435 mActiveIdleTimers.remove(iface);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001436 mDaemonHandler.post(new Runnable() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001437 @Override public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001438 notifyInterfaceClassActivity(params.type,
1439 DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07001440 SystemClock.elapsedRealtimeNanos(), -1, false);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001441 }
1442 });
Haoyu Bai04124232012-06-28 15:26:19 -07001443 }
1444 }
1445
1446 @Override
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001447 public NetworkStats getNetworkStatsSummaryDev() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001448 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001449 try {
1450 return mStatsFactory.readNetworkStatsSummaryDev();
1451 } catch (IOException e) {
1452 throw new IllegalStateException(e);
1453 }
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001454 }
1455
1456 @Override
1457 public NetworkStats getNetworkStatsSummaryXt() {
1458 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001459 try {
1460 return mStatsFactory.readNetworkStatsSummaryXt();
1461 } catch (IOException e) {
1462 throw new IllegalStateException(e);
1463 }
Jeff Sharkeyae2c1812011-10-04 13:11:40 -07001464 }
1465
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001466 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001467 public NetworkStats getNetworkStatsDetail() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001468 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001469 try {
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08001470 return mStatsFactory.readNetworkStatsDetail(UID_ALL, null, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001471 } catch (IOException e) {
1472 throw new IllegalStateException(e);
1473 }
San Mehat91cac642010-03-31 14:31:36 -07001474 }
1475
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001476 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001477 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001478 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001479
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001480 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001481 if (mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001482 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001483 }
1484
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001485 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001486 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001487 mNetdService.bandwidthSetInterfaceQuota(iface, quotaBytes);
1488
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001489 mActiveQuotas.put(iface, quotaBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001490 } catch (RemoteException | ServiceSpecificException e) {
1491 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001492 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001493
1494 synchronized (mTetheringStatsProviders) {
1495 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1496 try {
1497 provider.setInterfaceQuota(iface, quotaBytes);
1498 } catch (RemoteException e) {
1499 Log.e(TAG, "Problem setting tethering data limit on provider " +
1500 mTetheringStatsProviders.get(provider) + ": " + e);
1501 }
1502 }
1503 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001504 }
1505 }
1506
1507 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001508 public void removeInterfaceQuota(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001509 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001510
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001511 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001512 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001513 // TODO: eventually consider throwing
1514 return;
1515 }
1516
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001517 mActiveQuotas.remove(iface);
1518 mActiveAlerts.remove(iface);
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001519
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001520 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001521 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001522 mNetdService.bandwidthRemoveInterfaceQuota(iface);
1523 } catch (RemoteException | ServiceSpecificException e) {
1524 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001525 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001526
1527 synchronized (mTetheringStatsProviders) {
1528 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1529 try {
1530 provider.setInterfaceQuota(iface, ITetheringStatsProvider.QUOTA_UNLIMITED);
1531 } catch (RemoteException e) {
1532 Log.e(TAG, "Problem removing tethering data limit on provider " +
1533 mTetheringStatsProviders.get(provider) + ": " + e);
1534 }
1535 }
1536 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001537 }
1538 }
1539
1540 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001541 public void setInterfaceAlert(String iface, long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001542 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001543
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001544 // quick sanity check
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001545 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001546 throw new IllegalStateException("setting alert requires existing quota on iface");
1547 }
1548
1549 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001550 if (mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001551 throw new IllegalStateException("iface " + iface + " already has alert");
1552 }
1553
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001554 try {
1555 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001556 mNetdService.bandwidthSetInterfaceAlert(iface, alertBytes);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001557 mActiveAlerts.put(iface, alertBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001558 } catch (RemoteException | ServiceSpecificException e) {
1559 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001560 }
1561 }
1562 }
1563
1564 @Override
1565 public void removeInterfaceAlert(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001566 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001567
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001568 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001569 if (!mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001570 // TODO: eventually consider throwing
1571 return;
1572 }
1573
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001574 try {
1575 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001576 mNetdService.bandwidthRemoveInterfaceAlert(iface);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001577 mActiveAlerts.remove(iface);
Luke Huangc7bea8662018-08-07 16:04:26 +08001578 } catch (RemoteException | ServiceSpecificException e) {
1579 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001580 }
1581 }
1582 }
1583
1584 @Override
1585 public void setGlobalAlert(long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001586 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001587
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001588 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001589 mNetdService.bandwidthSetGlobalAlert(alertBytes);
1590 } catch (RemoteException | ServiceSpecificException e) {
1591 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001592 }
1593 }
1594
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001595 private void setUidOnMeteredNetworkList(int uid, boolean blacklist, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001596 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001597
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001598 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001599 boolean oldEnable;
1600 SparseBooleanArray quotaList;
1601 synchronized (mRulesLock) {
1602 quotaList = blacklist ? mUidRejectOnMetered : mUidAllowOnMetered;
1603 oldEnable = quotaList.get(uid, false);
1604 }
Felipe Leme65be3022016-03-22 14:53:13 -07001605 if (oldEnable == enable) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001606 // TODO: eventually consider throwing
1607 return;
1608 }
1609
Felipe Leme29e72ea2016-09-08 13:26:55 -07001610 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "inetd bandwidth");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001611 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001612 if (blacklist) {
1613 if (enable) {
1614 mNetdService.bandwidthAddNaughtyApp(uid);
1615 } else {
1616 mNetdService.bandwidthRemoveNaughtyApp(uid);
1617 }
1618 } else {
1619 if (enable) {
1620 mNetdService.bandwidthAddNiceApp(uid);
1621 } else {
1622 mNetdService.bandwidthRemoveNiceApp(uid);
1623 }
1624 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001625 synchronized (mRulesLock) {
1626 if (enable) {
1627 quotaList.put(uid, true);
1628 } else {
1629 quotaList.delete(uid);
1630 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001631 }
Luke Huangc7bea8662018-08-07 16:04:26 +08001632 } catch (RemoteException | ServiceSpecificException e) {
1633 throw new IllegalStateException(e);
Felipe Leme29e72ea2016-09-08 13:26:55 -07001634 } finally {
1635 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001636 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001637 }
1638 }
1639
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001640 @Override
Felipe Leme65be3022016-03-22 14:53:13 -07001641 public void setUidMeteredNetworkBlacklist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001642 setUidOnMeteredNetworkList(uid, true, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001643 }
1644
1645 @Override
1646 public void setUidMeteredNetworkWhitelist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001647 setUidOnMeteredNetworkList(uid, false, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001648 }
1649
1650 @Override
1651 public boolean setDataSaverModeEnabled(boolean enable) {
Sehee Parka9139bc2017-12-22 13:54:05 +09001652 mContext.enforceCallingOrSelfPermission(NETWORK_SETTINGS, TAG);
1653
Felipe Leme65be3022016-03-22 14:53:13 -07001654 if (DBG) Log.d(TAG, "setDataSaverMode: " + enable);
1655 synchronized (mQuotaLock) {
1656 if (mDataSaverMode == enable) {
1657 Log.w(TAG, "setDataSaverMode(): already " + mDataSaverMode);
1658 return true;
1659 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07001660 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "bandwidthEnableDataSaver");
Felipe Leme65be3022016-03-22 14:53:13 -07001661 try {
1662 final boolean changed = mNetdService.bandwidthEnableDataSaver(enable);
1663 if (changed) {
1664 mDataSaverMode = enable;
1665 } else {
1666 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command silently failed");
1667 }
1668 return changed;
1669 } catch (RemoteException e) {
1670 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command failed", e);
1671 return false;
Felipe Leme29e72ea2016-09-08 13:26:55 -07001672 } finally {
1673 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme65be3022016-03-22 14:53:13 -07001674 }
1675 }
1676 }
1677
1678 @Override
Robin Lee17e61832016-05-09 13:46:28 +01001679 public void setAllowOnlyVpnForUids(boolean add, UidRange[] uidRanges)
1680 throws ServiceSpecificException {
Rubin Xu2ea6c552018-01-11 10:59:19 +00001681 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robin Lee17e61832016-05-09 13:46:28 +01001682 try {
1683 mNetdService.networkRejectNonSecureVpn(add, uidRanges);
1684 } catch (ServiceSpecificException e) {
1685 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1686 + ": netd command failed", e);
1687 throw e;
1688 } catch (RemoteException e) {
1689 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1690 + ": netd command failed", e);
1691 throw e.rethrowAsRuntimeException();
1692 }
1693 }
1694
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001695 private void applyUidCleartextNetworkPolicy(int uid, int policy) {
Luke Huang473eb872018-07-26 17:33:14 +08001696 final int policyValue;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001697 switch (policy) {
1698 case StrictMode.NETWORK_POLICY_ACCEPT:
Luke Huang473eb872018-07-26 17:33:14 +08001699 policyValue = INetd.PENALTY_POLICY_ACCEPT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001700 break;
1701 case StrictMode.NETWORK_POLICY_LOG:
Luke Huang473eb872018-07-26 17:33:14 +08001702 policyValue = INetd.PENALTY_POLICY_LOG;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001703 break;
1704 case StrictMode.NETWORK_POLICY_REJECT:
Luke Huang473eb872018-07-26 17:33:14 +08001705 policyValue = INetd.PENALTY_POLICY_REJECT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001706 break;
1707 default:
1708 throw new IllegalArgumentException("Unknown policy " + policy);
1709 }
1710
1711 try {
Luke Huang473eb872018-07-26 17:33:14 +08001712 mNetdService.strictUidCleartextPenalty(uid, policyValue);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001713 mUidCleartextPolicy.put(uid, policy);
Luke Huang473eb872018-07-26 17:33:14 +08001714 } catch (RemoteException | ServiceSpecificException e) {
1715 throw new IllegalStateException(e);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001716 }
1717 }
1718
Robin Lee17e61832016-05-09 13:46:28 +01001719 @Override
Jeff Sharkey605eb792014-11-04 13:34:06 -08001720 public void setUidCleartextNetworkPolicy(int uid, int policy) {
1721 if (Binder.getCallingUid() != uid) {
1722 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1723 }
1724
1725 synchronized (mQuotaLock) {
1726 final int oldPolicy = mUidCleartextPolicy.get(uid, StrictMode.NETWORK_POLICY_ACCEPT);
1727 if (oldPolicy == policy) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001728 // This also ensures we won't needlessly apply an ACCEPT policy if we've just
1729 // enabled strict and the underlying iptables rules are empty.
Jeff Sharkey605eb792014-11-04 13:34:06 -08001730 return;
1731 }
1732
Luke Huang473eb872018-07-26 17:33:14 +08001733 // TODO: remove this code after removing prepareNativeDaemon()
Jeff Sharkey605eb792014-11-04 13:34:06 -08001734 if (!mStrictEnabled) {
1735 // Module isn't enabled yet; stash the requested policy away to
1736 // apply later once the daemon is connected.
1737 mUidCleartextPolicy.put(uid, policy);
1738 return;
1739 }
1740
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001741 // netd does not keep state on strict mode policies, and cannot replace a non-accept
1742 // policy without deleting it first. Rather than add state to netd, just always send
1743 // it an accept policy when switching between two non-accept policies.
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001744 // TODO: consider keeping state in netd so we can simplify this code.
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001745 if (oldPolicy != StrictMode.NETWORK_POLICY_ACCEPT &&
1746 policy != StrictMode.NETWORK_POLICY_ACCEPT) {
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001747 applyUidCleartextNetworkPolicy(uid, StrictMode.NETWORK_POLICY_ACCEPT);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001748 }
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001749
1750 applyUidCleartextNetworkPolicy(uid, policy);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001751 }
1752 }
1753
1754 @Override
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001755 public boolean isBandwidthControlEnabled() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001756 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang56a03a02018-09-07 12:02:16 +08001757 return true;
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001758 }
1759
1760 @Override
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001761 public NetworkStats getNetworkStatsUidDetail(int uid, String[] ifaces) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001762 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001763 try {
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001764 return mStatsFactory.readNetworkStatsDetail(uid, ifaces, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001765 } catch (IOException e) {
1766 throw new IllegalStateException(e);
1767 }
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001768 }
1769
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001770 private class NetdTetheringStatsProvider extends ITetheringStatsProvider.Stub {
1771 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001772 public NetworkStats getTetherStats(int how) {
1773 // We only need to return per-UID stats. Per-device stats are already counted by
1774 // interface counters.
1775 if (how != STATS_PER_UID) {
1776 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
1777 }
1778
Luke Huang13b79e82018-09-26 14:53:42 +08001779 final TetherStatsParcel[] tetherStatsVec;
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001780 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001781 tetherStatsVec = mNetdService.tetherGetStats();
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001782 } catch (RemoteException | ServiceSpecificException e) {
1783 throw new IllegalStateException("problem parsing tethering stats: ", e);
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001784 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001785
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001786 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(),
Luke Huang13b79e82018-09-26 14:53:42 +08001787 tetherStatsVec.length);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001788 final NetworkStats.Entry entry = new NetworkStats.Entry();
1789
Luke Huang13b79e82018-09-26 14:53:42 +08001790 for (TetherStatsParcel tetherStats : tetherStatsVec) {
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001791 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001792 entry.iface = tetherStats.iface;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001793 entry.uid = UID_TETHERING;
1794 entry.set = SET_DEFAULT;
1795 entry.tag = TAG_NONE;
Luke Huang13b79e82018-09-26 14:53:42 +08001796 entry.rxBytes = tetherStats.rxBytes;
1797 entry.rxPackets = tetherStats.rxPackets;
1798 entry.txBytes = tetherStats.txBytes;
1799 entry.txPackets = tetherStats.txPackets;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001800 stats.combineValues(entry);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001801 } catch (ArrayIndexOutOfBoundsException e) {
Luke Huang13b79e82018-09-26 14:53:42 +08001802 throw new IllegalStateException("invalid tethering stats " + e);
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001803 }
1804 }
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001805
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001806 return stats;
1807 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001808
1809 @Override
1810 public void setInterfaceQuota(String iface, long quotaBytes) {
1811 // Do nothing. netd is already informed of quota changes in setInterfaceQuota.
1812 }
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001813 }
1814
1815 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001816 public NetworkStats getNetworkStatsTethering(int how) {
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001817 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1818
1819 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1820 synchronized (mTetheringStatsProviders) {
1821 for (ITetheringStatsProvider provider: mTetheringStatsProviders.keySet()) {
1822 try {
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001823 stats.combineAllValues(provider.getTetherStats(how));
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001824 } catch (RemoteException e) {
1825 Log.e(TAG, "Problem reading tethering stats from " +
1826 mTetheringStatsProviders.get(provider) + ": " + e);
1827 }
1828 }
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001829 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001830 return stats;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001831 }
1832
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001833 @Override
Erik Kline1742fe12017-12-13 19:40:49 +09001834 public void setDnsConfigurationForNetwork(int netId, String[] servers, String[] domains,
Erik Klinee5dac902018-03-04 21:01:01 +09001835 int[] params, String tlsHostname, String[] tlsServers) {
Pierre Imai8e48e672016-04-21 13:30:43 +09001836 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1837
Ben Schwartz6ec28df2017-10-02 13:08:06 -04001838 final String[] tlsFingerprints = new String[0];
Pierre Imai8e48e672016-04-21 13:30:43 +09001839 try {
Erik Kline1742fe12017-12-13 19:40:49 +09001840 mNetdService.setResolverConfiguration(
Erik Klinee5dac902018-03-04 21:01:01 +09001841 netId, servers, domains, params, tlsHostname, tlsServers, tlsFingerprints);
Pierre Imai8e48e672016-04-21 13:30:43 +09001842 } catch (RemoteException e) {
1843 throw new RuntimeException(e);
1844 }
1845 }
1846
1847 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001848 public void addVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001849 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001850
1851 try {
1852 mNetdService.networkAddUidRanges(netId, ranges);
1853 } catch (RemoteException | ServiceSpecificException e) {
1854 throw new IllegalStateException(e);
Chad Brubaker3277620a2013-06-12 13:37:30 -07001855 }
1856 }
1857
1858 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001859 public void removeVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001860 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001861 try {
1862 mNetdService.networkRemoveUidRanges(netId, ranges);
1863 } catch (RemoteException | ServiceSpecificException e) {
1864 throw new IllegalStateException(e);
Chad Brubakercca54c42013-06-27 17:41:38 -07001865 }
1866 }
1867
1868 @Override
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001869 public void setFirewallEnabled(boolean enabled) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001870 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001871 try {
Luke Huanga241db92018-07-31 20:15:24 +08001872 mNetdService.firewallSetFirewallType(
1873 enabled ? INetd.FIREWALL_WHITELIST : INetd.FIREWALL_BLACKLIST);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001874 mFirewallEnabled = enabled;
Luke Huanga241db92018-07-31 20:15:24 +08001875 } catch (RemoteException | ServiceSpecificException e) {
1876 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001877 }
1878 }
1879
1880 @Override
1881 public boolean isFirewallEnabled() {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001882 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001883 return mFirewallEnabled;
1884 }
1885
1886 @Override
Jeff Sharkey2c092982012-08-24 11:44:40 -07001887 public void setFirewallInterfaceRule(String iface, boolean allow) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001888 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001889 Preconditions.checkState(mFirewallEnabled);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001890 try {
Luke Huanga241db92018-07-31 20:15:24 +08001891 mNetdService.firewallSetInterfaceRule(iface,
1892 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
1893 } catch (RemoteException | ServiceSpecificException e) {
1894 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001895 }
1896 }
1897
Lorenzo Colitti3fef7232016-04-29 18:00:03 +09001898 private void closeSocketsForFirewallChainLocked(int chain, String chainName) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001899 // UID ranges to close sockets on.
1900 UidRange[] ranges;
1901 // UID ranges whose sockets we won't touch.
1902 int[] exemptUids;
1903
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001904 int numUids = 0;
Luke Huanga241db92018-07-31 20:15:24 +08001905 if (DBG) Slog.d(TAG, "Closing sockets after enabling chain " + chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001906 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
1907 // Close all sockets on all non-system UIDs...
1908 ranges = new UidRange[] {
1909 // TODO: is there a better way of finding all existing users? If so, we could
1910 // specify their ranges here.
1911 new UidRange(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE),
1912 };
1913 // ... except for the UIDs that have allow rules.
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001914 synchronized (mRulesLock) {
1915 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1916 exemptUids = new int[rules.size()];
1917 for (int i = 0; i < exemptUids.length; i++) {
1918 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
1919 exemptUids[numUids] = rules.keyAt(i);
1920 numUids++;
1921 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001922 }
1923 }
1924 // Normally, whitelist chains only contain deny rules, so numUids == exemptUids.length.
1925 // But the code does not guarantee this in any way, and at least in one case - if we add
1926 // a UID rule to the firewall, and then disable the firewall - the chains can contain
1927 // the wrong type of rule. In this case, don't close connections that we shouldn't.
1928 //
1929 // TODO: tighten up this code by ensuring we never set the wrong type of rule, and
1930 // fix setFirewallEnabled to grab mQuotaLock and clear rules.
1931 if (numUids != exemptUids.length) {
1932 exemptUids = Arrays.copyOf(exemptUids, numUids);
1933 }
1934 } else {
1935 // Close sockets for every UID that has a deny rule...
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001936 synchronized (mRulesLock) {
1937 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1938 ranges = new UidRange[rules.size()];
1939 for (int i = 0; i < ranges.length; i++) {
1940 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_DENY) {
1941 int uid = rules.keyAt(i);
1942 ranges[numUids] = new UidRange(uid, uid);
1943 numUids++;
1944 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001945 }
1946 }
1947 // As above; usually numUids == ranges.length, but not always.
1948 if (numUids != ranges.length) {
1949 ranges = Arrays.copyOf(ranges, numUids);
1950 }
1951 // ... with no exceptions.
1952 exemptUids = new int[0];
1953 }
1954
1955 try {
1956 mNetdService.socketDestroy(ranges, exemptUids);
1957 } catch(RemoteException | ServiceSpecificException e) {
1958 Slog.e(TAG, "Error closing sockets after enabling chain " + chainName + ": " + e);
1959 }
1960 }
1961
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001962 @Override
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001963 public void setFirewallChainEnabled(int chain, boolean enable) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001964 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001965 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001966 synchronized (mRulesLock) {
1967 if (getFirewallChainState(chain) == enable) {
1968 // All is the same, nothing to do. This relies on the fact that netd has child
1969 // chains default detached.
1970 return;
1971 }
1972 setFirewallChainState(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001973 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001974
Luke Huang615e1022018-10-25 11:54:05 +09001975 final String chainName = getFirewallChainName(chain);
Luke Huanga241db92018-07-31 20:15:24 +08001976 if (chain == FIREWALL_CHAIN_NONE) {
Luke Huang615e1022018-10-25 11:54:05 +09001977 throw new IllegalArgumentException("Bad child chain: " + chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001978 }
1979
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001980 try {
Luke Huanga241db92018-07-31 20:15:24 +08001981 mNetdService.firewallEnableChildChain(chain, enable);
1982 } catch (RemoteException | ServiceSpecificException e) {
1983 throw new IllegalStateException(e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001984 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001985
1986 // Close any sockets that were opened by the affected UIDs. This has to be done after
1987 // disabling network connectivity, in case they react to the socket close by reopening
1988 // the connection and race with the iptables commands that enable the firewall. All
1989 // whitelist and blacklist chains allow RSTs through.
1990 if (enable) {
Luke Huang615e1022018-10-25 11:54:05 +09001991 closeSocketsForFirewallChainLocked(chain, chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001992 }
Amith Yamasani15e472352015-04-24 19:06:07 -07001993 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001994 }
1995
Luke Huanga241db92018-07-31 20:15:24 +08001996 private String getFirewallChainName(int chain) {
1997 switch (chain) {
1998 case FIREWALL_CHAIN_STANDBY:
1999 return FIREWALL_CHAIN_NAME_STANDBY;
2000 case FIREWALL_CHAIN_DOZABLE:
2001 return FIREWALL_CHAIN_NAME_DOZABLE;
2002 case FIREWALL_CHAIN_POWERSAVE:
2003 return FIREWALL_CHAIN_NAME_POWERSAVE;
2004 default:
2005 throw new IllegalArgumentException("Bad child chain: " + chain);
2006 }
2007 }
2008
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002009 private int getFirewallType(int chain) {
2010 switch (chain) {
2011 case FIREWALL_CHAIN_STANDBY:
2012 return FIREWALL_TYPE_BLACKLIST;
2013 case FIREWALL_CHAIN_DOZABLE:
2014 return FIREWALL_TYPE_WHITELIST;
Felipe Leme011b98f2016-02-10 17:28:31 -08002015 case FIREWALL_CHAIN_POWERSAVE:
2016 return FIREWALL_TYPE_WHITELIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002017 default:
2018 return isFirewallEnabled() ? FIREWALL_TYPE_WHITELIST : FIREWALL_TYPE_BLACKLIST;
2019 }
2020 }
2021
2022 @Override
2023 public void setFirewallUidRules(int chain, int[] uids, int[] rules) {
2024 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002025 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002026 synchronized (mRulesLock) {
2027 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
2028 SparseIntArray newRules = new SparseIntArray();
2029 // apply new set of rules
2030 for (int index = uids.length - 1; index >= 0; --index) {
2031 int uid = uids[index];
2032 int rule = rules[index];
2033 updateFirewallUidRuleLocked(chain, uid, rule);
2034 newRules.put(uid, rule);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002035 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002036 // collect the rules to remove.
2037 SparseIntArray rulesToRemove = new SparseIntArray();
2038 for (int index = uidFirewallRules.size() - 1; index >= 0; --index) {
2039 int uid = uidFirewallRules.keyAt(index);
2040 if (newRules.indexOfKey(uid) < 0) {
2041 rulesToRemove.put(uid, FIREWALL_RULE_DEFAULT);
2042 }
2043 }
2044 // remove dead rules
2045 for (int index = rulesToRemove.size() - 1; index >= 0; --index) {
2046 int uid = rulesToRemove.keyAt(index);
2047 updateFirewallUidRuleLocked(chain, uid, FIREWALL_RULE_DEFAULT);
2048 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002049 }
2050 try {
2051 switch (chain) {
2052 case FIREWALL_CHAIN_DOZABLE:
2053 mNetdService.firewallReplaceUidChain("fw_dozable", true, uids);
2054 break;
2055 case FIREWALL_CHAIN_STANDBY:
2056 mNetdService.firewallReplaceUidChain("fw_standby", false, uids);
2057 break;
2058 case FIREWALL_CHAIN_POWERSAVE:
2059 mNetdService.firewallReplaceUidChain("fw_powersave", true, uids);
2060 break;
2061 case FIREWALL_CHAIN_NONE:
2062 default:
2063 Slog.d(TAG, "setFirewallUidRules() called on invalid chain: " + chain);
2064 }
2065 } catch (RemoteException e) {
2066 Slog.w(TAG, "Error flushing firewall chain " + chain, e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002067 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002068 }
2069 }
2070
2071 @Override
2072 public void setFirewallUidRule(int chain, int uid, int rule) {
2073 enforceSystemUid();
Felipe Lemea701cad2016-05-12 09:58:14 -07002074 synchronized (mQuotaLock) {
2075 setFirewallUidRuleLocked(chain, uid, rule);
2076 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002077 }
2078
Felipe Lemea701cad2016-05-12 09:58:14 -07002079 private void setFirewallUidRuleLocked(int chain, int uid, int rule) {
2080 if (updateFirewallUidRuleLocked(chain, uid, rule)) {
Luke Huanga241db92018-07-31 20:15:24 +08002081 final int ruleType = getFirewallRuleType(chain, rule);
Amith Yamasani15e472352015-04-24 19:06:07 -07002082 try {
Luke Huanga241db92018-07-31 20:15:24 +08002083 mNetdService.firewallSetUidRule(chain, uid, ruleType);
2084 } catch (RemoteException | ServiceSpecificException e) {
2085 throw new IllegalStateException(e);
Amith Yamasani15e472352015-04-24 19:06:07 -07002086 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002087 }
2088 }
2089
Felipe Lemea701cad2016-05-12 09:58:14 -07002090 // TODO: now that netd supports batching, NMS should not keep these data structures anymore...
2091 private boolean updateFirewallUidRuleLocked(int chain, int uid, int rule) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002092 synchronized (mRulesLock) {
2093 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Felipe Lemea701cad2016-05-12 09:58:14 -07002094
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002095 final int oldUidFirewallRule = uidFirewallRules.get(uid, FIREWALL_RULE_DEFAULT);
2096 if (DBG) {
2097 Slog.d(TAG, "oldRule = " + oldUidFirewallRule
2098 + ", newRule=" + rule + " for uid=" + uid + " on chain " + chain);
2099 }
2100 if (oldUidFirewallRule == rule) {
2101 if (DBG) Slog.d(TAG, "!!!!! Skipping change");
2102 // TODO: eventually consider throwing
2103 return false;
2104 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002105
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002106 String ruleName = getFirewallRuleName(chain, rule);
2107 String oldRuleName = getFirewallRuleName(chain, oldUidFirewallRule);
Felipe Lemea701cad2016-05-12 09:58:14 -07002108
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002109 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
2110 uidFirewallRules.delete(uid);
2111 } else {
2112 uidFirewallRules.put(uid, rule);
2113 }
2114 return !ruleName.equals(oldRuleName);
Felipe Lemea701cad2016-05-12 09:58:14 -07002115 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002116 }
2117
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002118 private @NonNull String getFirewallRuleName(int chain, int rule) {
2119 String ruleName;
2120 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
2121 if (rule == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
2122 ruleName = "allow";
2123 } else {
2124 ruleName = "deny";
2125 }
2126 } else { // Blacklist mode
2127 if (rule == NetworkPolicyManager.FIREWALL_RULE_DENY) {
2128 ruleName = "deny";
2129 } else {
2130 ruleName = "allow";
2131 }
2132 }
2133 return ruleName;
2134 }
2135
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002136 private @NonNull SparseIntArray getUidFirewallRulesLR(int chain) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002137 switch (chain) {
2138 case FIREWALL_CHAIN_STANDBY:
2139 return mUidFirewallStandbyRules;
2140 case FIREWALL_CHAIN_DOZABLE:
2141 return mUidFirewallDozableRules;
Felipe Leme011b98f2016-02-10 17:28:31 -08002142 case FIREWALL_CHAIN_POWERSAVE:
2143 return mUidFirewallPowerSaveRules;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002144 case FIREWALL_CHAIN_NONE:
2145 return mUidFirewallRules;
2146 default:
2147 throw new IllegalArgumentException("Unknown chain:" + chain);
2148 }
2149 }
2150
Luke Huanga241db92018-07-31 20:15:24 +08002151 private int getFirewallRuleType(int chain, int rule) {
Luke Huang615e1022018-10-25 11:54:05 +09002152 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
2153 return getFirewallType(chain) == FIREWALL_TYPE_WHITELIST
2154 ? INetd.FIREWALL_RULE_DENY : INetd.FIREWALL_RULE_ALLOW;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002155 }
Luke Huang615e1022018-10-25 11:54:05 +09002156 return rule;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002157 }
2158
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07002159 private static void enforceSystemUid() {
2160 final int uid = Binder.getCallingUid();
2161 if (uid != Process.SYSTEM_UID) {
2162 throw new SecurityException("Only available to AID_SYSTEM");
2163 }
2164 }
2165
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002166 @Override
Lorenzo Colitti79751842013-02-28 16:16:03 +09002167 public void startClatd(String interfaceName) throws IllegalStateException {
2168 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2169
2170 try {
Luke Huang69369f32018-08-02 15:51:41 +08002171 mNetdService.clatdStart(interfaceName);
2172 } catch (RemoteException | ServiceSpecificException e) {
2173 throw new IllegalStateException(e);
Lorenzo Colitti79751842013-02-28 16:16:03 +09002174 }
2175 }
2176
2177 @Override
Lorenzo Colitti95439462014-10-09 13:44:48 +09002178 public void stopClatd(String interfaceName) throws IllegalStateException {
Lorenzo Colitti79751842013-02-28 16:16:03 +09002179 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2180
2181 try {
Luke Huang69369f32018-08-02 15:51:41 +08002182 mNetdService.clatdStop(interfaceName);
2183 } catch (RemoteException | ServiceSpecificException e) {
2184 throw new IllegalStateException(e);
Lorenzo Colitti79751842013-02-28 16:16:03 +09002185 }
2186 }
2187
2188 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002189 public void registerNetworkActivityListener(INetworkActivityListener listener) {
2190 mNetworkActivityListeners.register(listener);
2191 }
2192
2193 @Override
2194 public void unregisterNetworkActivityListener(INetworkActivityListener listener) {
2195 mNetworkActivityListeners.unregister(listener);
2196 }
2197
2198 @Override
2199 public boolean isNetworkActive() {
2200 synchronized (mNetworkActivityListeners) {
2201 return mNetworkActive || mActiveIdleTimers.isEmpty();
2202 }
2203 }
2204
2205 private void reportNetworkActive() {
2206 final int length = mNetworkActivityListeners.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002207 try {
2208 for (int i = 0; i < length; i++) {
2209 try {
2210 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
Felipe Leme03e689d2016-03-02 16:17:38 -08002211 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002212 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002213 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002214 } finally {
2215 mNetworkActivityListeners.finishBroadcast();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002216 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002217 }
2218
Mattias Falk8b47b362011-08-23 14:15:13 +02002219 /** {@inheritDoc} */
Jeff Sharkey7b4596f2013-02-25 10:55:29 -08002220 @Override
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002221 public void monitor() {
2222 if (mConnector != null) {
2223 mConnector.monitor();
2224 }
2225 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002226
2227 @Override
2228 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002229 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002230
Robert Greenwalt470fd722012-01-18 12:51:15 -08002231 pw.println("NetworkManagementService NativeDaemonConnector Log:");
2232 mConnector.dump(fd, pw, args);
2233 pw.println();
2234
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07002235 pw.print("mMobileActivityFromRadio="); pw.print(mMobileActivityFromRadio);
2236 pw.print(" mLastPowerStateFromRadio="); pw.println(mLastPowerStateFromRadio);
2237 pw.print("mNetworkActive="); pw.println(mNetworkActive);
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002238
2239 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07002240 pw.print("Active quota ifaces: "); pw.println(mActiveQuotas.toString());
2241 pw.print("Active alert ifaces: "); pw.println(mActiveAlerts.toString());
Felipe Leme65be3022016-03-22 14:53:13 -07002242 pw.print("Data saver mode: "); pw.println(mDataSaverMode);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002243 synchronized (mRulesLock) {
2244 dumpUidRuleOnQuotaLocked(pw, "blacklist", mUidRejectOnMetered);
2245 dumpUidRuleOnQuotaLocked(pw, "whitelist", mUidAllowOnMetered);
2246 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002247 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002248
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002249 synchronized (mRulesLock) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002250 dumpUidFirewallRule(pw, "", mUidFirewallRules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002251
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002252 pw.print("UID firewall standby chain enabled: "); pw.println(
2253 getFirewallChainState(FIREWALL_CHAIN_STANDBY));
Felipe Leme011b98f2016-02-10 17:28:31 -08002254 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_STANDBY, mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002255
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002256 pw.print("UID firewall dozable chain enabled: "); pw.println(
2257 getFirewallChainState(FIREWALL_CHAIN_DOZABLE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002258 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_DOZABLE, mUidFirewallDozableRules);
Felipe Leme011b98f2016-02-10 17:28:31 -08002259
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002260 pw.println("UID firewall powersave chain enabled: " +
2261 getFirewallChainState(FIREWALL_CHAIN_POWERSAVE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002262 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_POWERSAVE, mUidFirewallPowerSaveRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002263 }
2264
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002265 synchronized (mIdleTimerLock) {
2266 pw.println("Idle timers:");
2267 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
2268 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
2269 IdleTimerParams params = ent.getValue();
2270 pw.print(" timeout="); pw.print(params.timeout);
2271 pw.print(" type="); pw.print(params.type);
2272 pw.print(" networkCount="); pw.println(params.networkCount);
2273 }
2274 }
2275
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002276 pw.print("Firewall enabled: "); pw.println(mFirewallEnabled);
Felipe Leme65be3022016-03-22 14:53:13 -07002277 pw.print("Netd service status: " );
2278 if (mNetdService == null) {
2279 pw.println("disconnected");
2280 } else {
2281 try {
2282 final boolean alive = mNetdService.isAlive();
2283 pw.println(alive ? "alive": "dead");
2284 } catch (RemoteException e) {
2285 pw.println("unreachable");
2286 }
2287 }
2288 }
2289
2290 private void dumpUidRuleOnQuotaLocked(PrintWriter pw, String name, SparseBooleanArray list) {
2291 pw.print("UID bandwith control ");
2292 pw.print(name);
2293 pw.print(" rule: [");
2294 final int size = list.size();
2295 for (int i = 0; i < size; i++) {
2296 pw.print(list.keyAt(i));
2297 if (i < size - 1) pw.print(",");
2298 }
2299 pw.println("]");
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002300 }
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002301
Felipe Leme011b98f2016-02-10 17:28:31 -08002302 private void dumpUidFirewallRule(PrintWriter pw, String name, SparseIntArray rules) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002303 pw.print("UID firewall ");
Felipe Leme011b98f2016-02-10 17:28:31 -08002304 pw.print(name);
2305 pw.print(" rule: [");
2306 final int size = rules.size();
2307 for (int i = 0; i < size; i++) {
2308 pw.print(rules.keyAt(i));
2309 pw.print(":");
2310 pw.print(rules.valueAt(i));
2311 if (i < size - 1) pw.print(",");
2312 }
2313 pw.println("]");
2314 }
2315
Robert Greenwalt568891d2014-04-04 13:38:00 -07002316 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002317 public void createPhysicalNetwork(int netId, int permission) {
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002318 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2319
2320 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002321 mNetdService.networkCreatePhysical(netId, permission);
2322 } catch (RemoteException | ServiceSpecificException e) {
2323 throw new IllegalStateException(e);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002324 }
2325 }
2326
Robert Greenwalt568891d2014-04-04 13:38:00 -07002327 @Override
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07002328 public void createVirtualNetwork(int netId, boolean hasDNS, boolean secure) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002329 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2330
2331 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002332 mNetdService.networkCreateVpn(netId, hasDNS, secure);
2333 } catch (RemoteException | ServiceSpecificException e) {
2334 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002335 }
2336 }
2337
2338 @Override
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002339 public void removeNetwork(int netId) {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002340 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002341
2342 try {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002343 mNetdService.networkDestroy(netId);
2344 } catch (ServiceSpecificException e) {
2345 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2346 throw e;
2347 } catch (RemoteException e) {
2348 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2349 throw e.rethrowAsRuntimeException();
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002350 }
2351 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002352
2353 @Override
Paul Jensen992f2522014-04-28 10:33:11 -04002354 public void addInterfaceToNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002355 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, netId, iface);
Paul Jensen992f2522014-04-28 10:33:11 -04002356 }
2357
2358 @Override
2359 public void removeInterfaceFromNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002360 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, netId, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002361 }
Paul Jensen992f2522014-04-28 10:33:11 -04002362
Luke Huang8a462ec2018-08-24 20:33:16 +08002363 private void modifyInterfaceInNetwork(boolean add, int netId, String iface) {
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002364 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Paul Jensen992f2522014-04-28 10:33:11 -04002365 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002366 if (add) {
2367 mNetdService.networkAddInterface(netId, iface);
2368 } else {
2369 mNetdService.networkRemoveInterface(netId, iface);
2370 }
2371 } catch (RemoteException | ServiceSpecificException e) {
2372 throw new IllegalStateException(e);
Paul Jensen992f2522014-04-28 10:33:11 -04002373 }
2374 }
2375
2376 @Override
Robert Greenwalt913c8952014-04-07 17:36:35 -07002377 public void addLegacyRouteForNetId(int netId, RouteInfo routeInfo, int uid) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002378 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2379
Sreeram Ramachandrancc91c7b2014-06-03 18:41:43 -07002380 final LinkAddress la = routeInfo.getDestinationLinkAddress();
Luke Huang8a462ec2018-08-24 20:33:16 +08002381 final String ifName = routeInfo.getInterface();
2382 final String dst = la.toString();
2383 final String nextHop;
Robert Greenwalt568891d2014-04-04 13:38:00 -07002384
Luke Huang8a462ec2018-08-24 20:33:16 +08002385 if (routeInfo.hasGateway()) {
2386 nextHop = routeInfo.getGateway().getHostAddress();
2387 } else {
2388 nextHop = "";
2389 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002390 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002391 mNetdService.networkAddLegacyRoute(netId, ifName, dst, nextHop, uid);
2392 } catch (RemoteException | ServiceSpecificException e) {
2393 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002394 }
2395 }
2396
2397 @Override
Sreeram Ramachandranf047f2a2014-04-15 16:04:26 -07002398 public void setDefaultNetId(int netId) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002399 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2400
2401 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002402 mNetdService.networkSetDefault(netId);
2403 } catch (RemoteException | ServiceSpecificException e) {
2404 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002405 }
2406 }
2407
2408 @Override
2409 public void clearDefaultNetId() {
2410 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2411
2412 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002413 mNetdService.networkClearDefault();
2414 } catch (RemoteException | ServiceSpecificException e) {
2415 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002416 }
2417 }
2418
2419 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002420 public void setNetworkPermission(int netId, int permission) {
Paul Jensen487ffe72015-07-24 15:57:11 -04002421 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2422
2423 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002424 mNetdService.networkSetPermissionForNetwork(netId, permission);
2425 } catch (RemoteException | ServiceSpecificException e) {
2426 throw new IllegalStateException(e);
Paul Jensen487ffe72015-07-24 15:57:11 -04002427 }
2428 }
2429
Luke Huang8a462ec2018-08-24 20:33:16 +08002430 private int parsePermission(String permission) {
2431 if (permission.equals("NETWORK")) {
2432 return INetd.PERMISSION_NETWORK;
2433 }
2434 if (permission.equals("SYSTEM")) {
2435 return INetd.PERMISSION_SYSTEM;
2436 }
2437 return INetd.PERMISSION_NONE;
2438 }
Paul Jensen487ffe72015-07-24 15:57:11 -04002439
2440 @Override
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002441 public void setPermission(String permission, int[] uids) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002442 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2443
Luke Huang8a462ec2018-08-24 20:33:16 +08002444 try {
2445 mNetdService.networkSetPermissionForUser(parsePermission(permission), uids);
2446 } catch (RemoteException | ServiceSpecificException e) {
2447 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002448 }
2449 }
2450
2451 @Override
2452 public void clearPermission(int[] uids) {
2453 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2454
Luke Huang8a462ec2018-08-24 20:33:16 +08002455 try {
2456 mNetdService.networkClearPermissionForUser(uids);
2457 } catch (RemoteException | ServiceSpecificException e) {
2458 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002459 }
2460 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002461
2462 @Override
2463 public void allowProtect(int uid) {
2464 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2465
2466 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002467 mNetdService.networkSetProtectAllow(uid);
2468 } catch (RemoteException | ServiceSpecificException e) {
2469 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002470 }
2471 }
2472
2473 @Override
2474 public void denyProtect(int uid) {
2475 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2476
2477 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002478 mNetdService.networkSetProtectDeny(uid);
2479 } catch (RemoteException | ServiceSpecificException e) {
2480 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002481 }
2482 }
2483
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002484 @Override
2485 public void addInterfaceToLocalNetwork(String iface, List<RouteInfo> routes) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002486 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002487
2488 for (RouteInfo route : routes) {
2489 if (!route.isDefaultRoute()) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002490 modifyRoute(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID, route);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002491 }
2492 }
2493 }
2494
2495 @Override
2496 public void removeInterfaceFromLocalNetwork(String iface) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002497 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, INetd.LOCAL_NET_ID, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002498 }
Erik Kline6599ee82016-07-17 21:28:39 +09002499
2500 @Override
2501 public int removeRoutesFromLocalNetwork(List<RouteInfo> routes) {
2502 int failures = 0;
2503
2504 for (RouteInfo route : routes) {
2505 try {
Luke Huang706d7ab2018-10-16 15:42:15 +08002506 modifyRoute(MODIFY_OPERATION_REMOVE, INetd.LOCAL_NET_ID, route);
Erik Kline6599ee82016-07-17 21:28:39 +09002507 } catch (IllegalStateException e) {
2508 failures++;
2509 }
2510 }
2511
2512 return failures;
2513 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002514
Sudheer Shankab8f23162017-08-04 13:30:10 -07002515 @Override
2516 public boolean isNetworkRestricted(int uid) {
2517 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2518 return isNetworkRestrictedInternal(uid);
2519 }
2520
2521 private boolean isNetworkRestrictedInternal(int uid) {
2522 synchronized (mRulesLock) {
2523 if (getFirewallChainState(FIREWALL_CHAIN_STANDBY)
2524 && mUidFirewallStandbyRules.get(uid) == FIREWALL_RULE_DENY) {
2525 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of app standby mode");
2526 return true;
2527 }
2528 if (getFirewallChainState(FIREWALL_CHAIN_DOZABLE)
2529 && mUidFirewallDozableRules.get(uid) != FIREWALL_RULE_ALLOW) {
2530 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of device idle mode");
2531 return true;
2532 }
2533 if (getFirewallChainState(FIREWALL_CHAIN_POWERSAVE)
2534 && mUidFirewallPowerSaveRules.get(uid) != FIREWALL_RULE_ALLOW) {
2535 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of power saver mode");
2536 return true;
2537 }
2538 if (mUidRejectOnMetered.get(uid)) {
2539 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of no metered data"
2540 + " in the background");
2541 return true;
2542 }
2543 if (mDataSaverMode && !mUidAllowOnMetered.get(uid)) {
2544 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of data saver mode");
2545 return true;
2546 }
2547 return false;
2548 }
2549 }
2550
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002551 private void setFirewallChainState(int chain, boolean state) {
2552 synchronized (mRulesLock) {
2553 mFirewallChainStates.put(chain, state);
2554 }
2555 }
2556
2557 private boolean getFirewallChainState(int chain) {
2558 synchronized (mRulesLock) {
2559 return mFirewallChainStates.get(chain);
2560 }
2561 }
2562
2563 @VisibleForTesting
2564 class LocalService extends NetworkManagementInternal {
2565 @Override
2566 public boolean isNetworkRestrictedForUid(int uid) {
Sudheer Shankab8f23162017-08-04 13:30:10 -07002567 return isNetworkRestrictedInternal(uid);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002568 }
2569 }
2570
2571 @VisibleForTesting
2572 Injector getInjector() {
2573 return new Injector();
2574 }
2575
2576 @VisibleForTesting
2577 class Injector {
2578 void setDataSaverMode(boolean dataSaverMode) {
2579 mDataSaverMode = dataSaverMode;
2580 }
2581
2582 void setFirewallChainState(int chain, boolean state) {
2583 NetworkManagementService.this.setFirewallChainState(chain, state);
2584 }
2585
2586 void setFirewallRule(int chain, int uid, int rule) {
2587 synchronized (mRulesLock) {
2588 getUidFirewallRulesLR(chain).put(uid, rule);
2589 }
2590 }
2591
2592 void setUidOnMeteredNetworkList(boolean blacklist, int uid, boolean enable) {
2593 synchronized (mRulesLock) {
2594 if (blacklist) {
2595 mUidRejectOnMetered.put(uid, enable);
2596 } else {
2597 mUidAllowOnMetered.put(uid, enable);
2598 }
2599 }
2600 }
2601
2602 void reset() {
2603 synchronized (mRulesLock) {
2604 setDataSaverMode(false);
2605 final int[] chains = {
2606 FIREWALL_CHAIN_DOZABLE,
2607 FIREWALL_CHAIN_STANDBY,
2608 FIREWALL_CHAIN_POWERSAVE
2609 };
2610 for (int chain : chains) {
2611 setFirewallChainState(chain, false);
2612 getUidFirewallRulesLR(chain).clear();
2613 }
2614 mUidAllowOnMetered.clear();
2615 mUidRejectOnMetered.clear();
2616 }
2617 }
2618 }
San Mehat873f2142010-01-14 10:25:07 -08002619}