blob: 0f00c114e5bcab35615e94879ef912de388daf89 [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
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700166 /**
167 * Name representing {@link #setGlobalAlert(long)} limit when delivered to
168 * {@link INetworkManagementEventObserver#limitReached(String, String)}.
169 */
170 public static final String LIMIT_GLOBAL_ALERT = "globalAlert";
171
Andrew Scull45f533c2017-05-19 15:37:20 +0100172 static class NetdResponseCode {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -0700173 /* Keep in sync with system/netd/server/ResponseCode.h */
San Mehat873f2142010-01-14 10:25:07 -0800174 public static final int InterfaceListResult = 110;
175 public static final int TetherInterfaceListResult = 111;
176 public static final int TetherDnsFwdTgtListResult = 112;
San Mehat72759df2010-01-19 13:50:37 -0800177 public static final int TtyListResult = 113;
Jeff Sharkeye4984be2013-09-10 21:03:27 -0700178 public static final int TetheringStatsListResult = 114;
San Mehat873f2142010-01-14 10:25:07 -0800179
180 public static final int TetherStatusResult = 210;
181 public static final int IpFwdStatusResult = 211;
San Mehated4fc8a2010-01-22 12:28:36 -0800182 public static final int InterfaceGetCfgResult = 213;
Robert Greenwalte3253922010-02-18 09:23:25 -0800183 public static final int SoftapStatusResult = 214;
San Mehat91cac642010-03-31 14:31:36 -0700184 public static final int InterfaceRxCounterResult = 216;
185 public static final int InterfaceTxCounterResult = 217;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700186 public static final int QuotaCounterResult = 220;
187 public static final int TetheringStatsResult = 221;
Selim Gurun84c00c62012-02-27 15:42:38 -0800188 public static final int DnsProxyQueryResult = 222;
Lorenzo Colitti79751842013-02-28 16:16:03 +0900189 public static final int ClatdStatusResult = 223;
Robert Greenwalte3253922010-02-18 09:23:25 -0800190
191 public static final int InterfaceChange = 600;
JP Abgrall12b933d2011-07-14 18:09:22 -0700192 public static final int BandwidthControl = 601;
Haoyu Bai6b7358d2012-07-17 16:36:50 -0700193 public static final int InterfaceClassActivity = 613;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900194 public static final int InterfaceAddressChange = 614;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900195 public static final int InterfaceDnsServerInfo = 615;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900196 public static final int RouteChange = 616;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800197 public static final int StrictCleartext = 617;
San Mehat873f2142010-01-14 10:25:07 -0800198 }
199
Rebecca Silbersteine2ec94f2016-03-24 13:29:00 -0700200 /**
201 * String indicating a softap command.
202 */
203 static final String SOFT_AP_COMMAND = "softap";
204
205 /**
206 * String passed back to netd connector indicating softap command success.
207 */
208 static final String SOFT_AP_COMMAND_SUCCESS = "Ok";
209
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700210 static final int DAEMON_MSG_MOBILE_CONN_REAL_TIME_INFO = 1;
211
Luke Huang8a462ec2018-08-24 20:33:16 +0800212 static final boolean MODIFY_OPERATION_ADD = true;
213 static final boolean MODIFY_OPERATION_REMOVE = false;
214
San Mehat873f2142010-01-14 10:25:07 -0800215 /**
216 * Binder context for this service
217 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700218 private final Context mContext;
San Mehat873f2142010-01-14 10:25:07 -0800219
220 /**
221 * connector object for communicating with netd
222 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700223 private final NativeDaemonConnector mConnector;
San Mehat873f2142010-01-14 10:25:07 -0800224
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700225 private final Handler mFgHandler;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700226 private final Handler mDaemonHandler;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700227
Lorenzo Colittia0868002017-07-11 02:29:28 +0900228 private final SystemServices mServices;
229
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900230 private INetd mNetdService;
231
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800232 private IBatteryStats mBatteryStats;
233
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700234 private final Thread mThread;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700235 private CountDownLatch mConnectedSignal = new CountDownLatch(1);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700236
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800237 private final RemoteCallbackList<INetworkManagementEventObserver> mObservers =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700238 new RemoteCallbackList<>();
San Mehat4d02d002010-01-22 16:07:46 -0800239
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700240 private final NetworkStatsFactory mStatsFactory = new NetworkStatsFactory();
241
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900242 @GuardedBy("mTetheringStatsProviders")
243 private final HashMap<ITetheringStatsProvider, String>
244 mTetheringStatsProviders = Maps.newHashMap();
245
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700246 /**
247 * If both locks need to be held, then they should be obtained in the order:
248 * first {@link #mQuotaLock} and then {@link #mRulesLock}.
249 */
Andrew Scull45f533c2017-05-19 15:37:20 +0100250 private final Object mQuotaLock = new Object();
Andrew Scull519291f2017-05-23 13:11:03 +0100251 private final Object mRulesLock = new Object();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800252
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700253 /** Set of interfaces with active quotas. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800254 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700255 private HashMap<String, Long> mActiveQuotas = Maps.newHashMap();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700256 /** Set of interfaces with active alerts. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800257 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700258 private HashMap<String, Long> mActiveAlerts = Maps.newHashMap();
Felipe Leme65be3022016-03-22 14:53:13 -0700259 /** Set of UIDs blacklisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700260 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700261 private SparseBooleanArray mUidRejectOnMetered = new SparseBooleanArray();
262 /** Set of UIDs whitelisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700263 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700264 private SparseBooleanArray mUidAllowOnMetered = new SparseBooleanArray();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800265 /** Set of UIDs with cleartext penalties. */
266 @GuardedBy("mQuotaLock")
267 private SparseIntArray mUidCleartextPolicy = new SparseIntArray();
Amith Yamasani15e472352015-04-24 19:06:07 -0700268 /** Set of UIDs that are to be blocked/allowed by firewall controller. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700269 @GuardedBy("mRulesLock")
Amith Yamasani15e472352015-04-24 19:06:07 -0700270 private SparseIntArray mUidFirewallRules = new SparseIntArray();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700271 /**
272 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
273 * to application idles.
274 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700275 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700276 private SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
277 /**
278 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
279 * to device idles.
280 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700281 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700282 private SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800283 /**
284 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
285 * to device on power-save mode.
286 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700287 @GuardedBy("mRulesLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800288 private SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700289 /** Set of states for the child firewall chains. True if the chain is active. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700290 @GuardedBy("mRulesLock")
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700291 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700292
Felipe Leme65be3022016-03-22 14:53:13 -0700293 @GuardedBy("mQuotaLock")
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700294 private volatile boolean mDataSaverMode;
Felipe Leme65be3022016-03-22 14:53:13 -0700295
Andrew Scull45f533c2017-05-19 15:37:20 +0100296 private final Object mIdleTimerLock = new Object();
Haoyu Bai04124232012-06-28 15:26:19 -0700297 /** Set of interfaces with active idle timers. */
298 private static class IdleTimerParams {
299 public final int timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800300 public final int type;
Haoyu Bai04124232012-06-28 15:26:19 -0700301 public int networkCount;
302
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800303 IdleTimerParams(int timeout, int type) {
Haoyu Bai04124232012-06-28 15:26:19 -0700304 this.timeout = timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800305 this.type = type;
Haoyu Bai04124232012-06-28 15:26:19 -0700306 this.networkCount = 1;
307 }
308 }
309 private HashMap<String, IdleTimerParams> mActiveIdleTimers = Maps.newHashMap();
310
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700311 private volatile boolean mFirewallEnabled;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800312 private volatile boolean mStrictEnabled;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700313
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700314 private boolean mMobileActivityFromRadio = false;
315 private int mLastPowerStateFromRadio = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Adam Lesinskie08af192015-03-25 16:42:59 -0700316 private int mLastPowerStateFromWifi = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700317
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800318 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700319 new RemoteCallbackList<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800320 private boolean mNetworkActive;
321
San Mehat873f2142010-01-14 10:25:07 -0800322 /**
323 * Constructs a new NetworkManagementService instance
324 *
325 * @param context Binder context for this service
326 */
Lorenzo Colittia0868002017-07-11 02:29:28 +0900327 private NetworkManagementService(
328 Context context, String socket, SystemServices services) {
San Mehat873f2142010-01-14 10:25:07 -0800329 mContext = context;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900330 mServices = services;
San Mehat4d02d002010-01-22 16:07:46 -0800331
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700332 // make sure this is on the same looper as our NativeDaemonConnector for sync purposes
333 mFgHandler = new Handler(FgThread.get().getLooper());
334
Dianne Hackborn4590e522014-03-24 13:36:46 -0700335 // Don't need this wake lock, since we now have a time stamp for when
336 // the network actually went inactive. (It might be nice to still do this,
337 // but I don't want to do it through the power manager because that pollutes the
338 // battery stats history with pointless noise.)
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700339 //PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
Dianne Hackborn4590e522014-03-24 13:36:46 -0700340 PowerManager.WakeLock wl = null; //pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NETD_TAG);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800341
San Mehat873f2142010-01-14 10:25:07 -0800342 mConnector = new NativeDaemonConnector(
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700343 new NetdCallbackReceiver(), socket, 10, NETD_TAG, 160, wl,
344 FgThread.get().getLooper());
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700345 mThread = new Thread(mConnector, NETD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700346
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700347 mDaemonHandler = new Handler(FgThread.get().getLooper());
Wink Saville67e07892014-06-18 16:43:14 -0700348
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700349 // Add ourself to the Watchdog monitors.
350 Watchdog.getInstance().addMonitor(this);
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700351
Lorenzo Colittia0868002017-07-11 02:29:28 +0900352 mServices.registerLocalService(new LocalService());
Lorenzo Colitti8228eb32017-07-19 06:17:33 +0900353
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900354 synchronized (mTetheringStatsProviders) {
355 mTetheringStatsProviders.put(new NetdTetheringStatsProvider(), "netd");
356 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700357 }
358
359 @VisibleForTesting
360 NetworkManagementService() {
361 mConnector = null;
362 mContext = null;
363 mDaemonHandler = null;
364 mFgHandler = null;
365 mThread = null;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900366 mServices = null;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700367 }
368
Lorenzo Colittia0868002017-07-11 02:29:28 +0900369 static NetworkManagementService create(Context context, String socket, SystemServices services)
Felipe Leme03e689d2016-03-02 16:17:38 -0800370 throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900371 final NetworkManagementService service =
372 new NetworkManagementService(context, socket, services);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700373 final CountDownLatch connectedSignal = service.mConnectedSignal;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700374 if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
375 service.mThread.start();
376 if (DBG) Slog.d(TAG, "Awaiting socket connection");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700377 connectedSignal.await();
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700378 if (DBG) Slog.d(TAG, "Connected");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900379 if (DBG) Slog.d(TAG, "Connecting native netd service");
bohu07cc3bb2016-05-03 15:58:01 -0700380 service.connectNativeNetdService();
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900381 if (DBG) Slog.d(TAG, "Connected");
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700382 return service;
San Mehat873f2142010-01-14 10:25:07 -0800383 }
384
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900385 public static NetworkManagementService create(Context context) throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900386 return create(context, NETD_SERVICE_NAME, new SystemServices());
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900387 }
388
Jeff Sharkey350083e2011-06-29 10:45:16 -0700389 public void systemReady() {
Felipe Leme03e689d2016-03-02 16:17:38 -0800390 if (DBG) {
391 final long start = System.currentTimeMillis();
392 prepareNativeDaemon();
393 final long delta = System.currentTimeMillis() - start;
394 Slog.d(TAG, "Prepared in " + delta + "ms");
395 return;
396 } else {
397 prepareNativeDaemon();
398 }
Jeff Sharkey350083e2011-06-29 10:45:16 -0700399 }
400
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800401 private IBatteryStats getBatteryStats() {
402 synchronized (this) {
403 if (mBatteryStats != null) {
404 return mBatteryStats;
405 }
Lorenzo Colittia0868002017-07-11 02:29:28 +0900406 mBatteryStats =
407 IBatteryStats.Stub.asInterface(mServices.getService(BatteryStats.SERVICE_NAME));
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800408 return mBatteryStats;
409 }
410 }
411
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800412 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800413 public void registerObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800414 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800415 mObservers.register(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800416 }
417
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800418 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800419 public void unregisterObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800420 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800421 mObservers.unregister(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800422 }
423
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900424 @FunctionalInterface
425 private interface NetworkManagementEventCallback {
426 public void sendCallback(INetworkManagementEventObserver o) throws RemoteException;
427 }
428
429 private void invokeForAllObservers(NetworkManagementEventCallback eventCallback) {
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800430 final int length = mObservers.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700431 try {
432 for (int i = 0; i < length; i++) {
433 try {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900434 eventCallback.sendCallback(mObservers.getBroadcastItem(i));
Felipe Leme03e689d2016-03-02 16:17:38 -0800435 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700436 }
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700437 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700438 } finally {
439 mObservers.finishBroadcast();
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700440 }
441 }
442
443 /**
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900444 * Notify our observers of an interface status change
445 */
446 private void notifyInterfaceStatusChanged(String iface, boolean up) {
447 invokeForAllObservers(o -> o.interfaceStatusChanged(iface, up));
448 }
449
450 /**
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700451 * Notify our observers of an interface link state change
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700452 * (typically, an Ethernet cable has been plugged-in or unplugged).
453 */
454 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900455 invokeForAllObservers(o -> o.interfaceLinkStateChanged(iface, up));
San Mehat4d02d002010-01-22 16:07:46 -0800456 }
457
458 /**
459 * Notify our observers of an interface addition.
460 */
461 private void notifyInterfaceAdded(String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900462 invokeForAllObservers(o -> o.interfaceAdded(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800463 }
464
465 /**
466 * Notify our observers of an interface removal.
467 */
468 private void notifyInterfaceRemoved(String iface) {
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700469 // netd already clears out quota and alerts for removed ifaces; update
470 // our sanity-checking state.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700471 mActiveAlerts.remove(iface);
472 mActiveQuotas.remove(iface);
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700473
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900474 invokeForAllObservers(o -> o.interfaceRemoved(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800475 }
476
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700477 /**
JP Abgrall12b933d2011-07-14 18:09:22 -0700478 * Notify our observers of a limit reached.
479 */
480 private void notifyLimitReached(String limitName, String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900481 invokeForAllObservers(o -> o.limitReached(limitName, iface));
JP Abgrall12b933d2011-07-14 18:09:22 -0700482 }
483
484 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700485 * Notify our observers of a change in the data activity state of the interface
486 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700487 private void notifyInterfaceClassActivity(int type, int powerState, long tsNanos,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700488 int uid, boolean fromRadio) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700489 final boolean isMobile = ConnectivityManager.isNetworkTypeMobile(type);
490 if (isMobile) {
491 if (!fromRadio) {
492 if (mMobileActivityFromRadio) {
493 // If this call is not coming from a report from the radio itself, but we
494 // have previously received reports from the radio, then we will take the
495 // power state to just be whatever the radio last reported.
496 powerState = mLastPowerStateFromRadio;
497 }
498 } else {
499 mMobileActivityFromRadio = true;
500 }
501 if (mLastPowerStateFromRadio != powerState) {
502 mLastPowerStateFromRadio = powerState;
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700503 try {
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700504 getBatteryStats().noteMobileRadioPowerState(powerState, tsNanos, uid);
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700505 } catch (RemoteException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700506 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700507 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700508 }
509
Adam Lesinskie08af192015-03-25 16:42:59 -0700510 if (ConnectivityManager.isNetworkTypeWifi(type)) {
511 if (mLastPowerStateFromWifi != powerState) {
512 mLastPowerStateFromWifi = powerState;
513 try {
Adam Lesinski5f056f62016-07-14 16:56:08 -0700514 getBatteryStats().noteWifiRadioPowerState(powerState, tsNanos, uid);
Adam Lesinskie08af192015-03-25 16:42:59 -0700515 } catch (RemoteException e) {
516 }
517 }
518 }
519
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700520 boolean isActive = powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
521 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
522
523 if (!isMobile || fromRadio || !mMobileActivityFromRadio) {
524 // Report the change in data activity. We don't do this if this is a change
525 // on the mobile network, that is not coming from the radio itself, and we
526 // have previously seen change reports from the radio. In that case only
527 // the radio is the authority for the current state.
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900528 final boolean active = isActive;
529 invokeForAllObservers(o -> o.interfaceClassDataActivityChanged(
530 Integer.toString(type), active, tsNanos));
Haoyu Baidb3c8672012-06-20 14:29:57 -0700531 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800532
533 boolean report = false;
534 synchronized (mIdleTimerLock) {
535 if (mActiveIdleTimers.isEmpty()) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700536 // If there are no idle timers, we are not monitoring activity, so we
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800537 // are always considered active.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700538 isActive = true;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800539 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700540 if (mNetworkActive != isActive) {
541 mNetworkActive = isActive;
542 report = isActive;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800543 }
544 }
545 if (report) {
546 reportNetworkActive();
547 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700548 }
549
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900550 @Override
551 public void registerTetheringStatsProvider(ITetheringStatsProvider provider, String name) {
552 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
553 Preconditions.checkNotNull(provider);
554 synchronized(mTetheringStatsProviders) {
555 mTetheringStatsProviders.put(provider, name);
556 }
557 }
558
559 @Override
560 public void unregisterTetheringStatsProvider(ITetheringStatsProvider provider) {
561 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
562 synchronized(mTetheringStatsProviders) {
563 mTetheringStatsProviders.remove(provider);
564 }
565 }
566
Lorenzo Colitti9f0baa92017-08-15 19:25:51 +0900567 @Override
568 public void tetherLimitReached(ITetheringStatsProvider provider) {
569 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
570 synchronized(mTetheringStatsProviders) {
571 if (!mTetheringStatsProviders.containsKey(provider)) {
572 return;
573 }
574 // No current code examines the interface parameter in a global alert. Just pass null.
575 notifyLimitReached(LIMIT_GLOBAL_ALERT, null);
576 }
577 }
578
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900579 // Sync the state of the given chain with the native daemon.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700580 private void syncFirewallChainLocked(int chain, String name) {
581 SparseIntArray rules;
582 synchronized (mRulesLock) {
583 final SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900584 // Make a copy of the current rules, and then clear them. This is because
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700585 // setFirewallUidRuleInternal only pushes down rules to the native daemon if they
586 // are different from the current rules stored in the mUidFirewall*Rules array for
587 // the specified chain. If we don't clear the rules, setFirewallUidRuleInternal
588 // will do nothing.
589 rules = uidFirewallRules.clone();
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900590 uidFirewallRules.clear();
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700591 }
592 if (rules.size() > 0) {
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900593 // Now push the rules. setFirewallUidRuleInternal will push each of these down to the
594 // native daemon, and also add them to the mUidFirewall*Rules array for the specified
595 // chain.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700596 if (DBG) Slog.d(TAG, "Pushing " + rules.size() + " active firewall "
597 + name + "UID rules");
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900598 for (int i = 0; i < rules.size(); i++) {
Felipe Lemea701cad2016-05-12 09:58:14 -0700599 setFirewallUidRuleLocked(chain, rules.keyAt(i), rules.valueAt(i));
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900600 }
601 }
602 }
603
bohu07cc3bb2016-05-03 15:58:01 -0700604 private void connectNativeNetdService() {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900605 mNetdService = mServices.getNetd();
bohu07cc3bb2016-05-03 15:58:01 -0700606 }
607
608 /**
609 * Prepare native daemon once connected, enabling modules and pushing any
610 * existing in-memory rules.
611 */
612 private void prepareNativeDaemon() {
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900613
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700614 // push any existing quota or UID rules
615 synchronized (mQuotaLock) {
Felipe Leme65be3022016-03-22 14:53:13 -0700616
Luke Huang56a03a02018-09-07 12:02:16 +0800617 // Netd unconditionally enable bandwidth control
618 SystemProperties.set(PROP_QTAGUID_ENABLED, "1");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900619
Luke Huang473eb872018-07-26 17:33:14 +0800620 mStrictEnabled = true;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900621
Felipe Leme65be3022016-03-22 14:53:13 -0700622 setDataSaverModeEnabled(mDataSaverMode);
623
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700624 int size = mActiveQuotas.size();
625 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800626 if (DBG) Slog.d(TAG, "Pushing " + size + " active quota rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700627 final HashMap<String, Long> activeQuotas = mActiveQuotas;
628 mActiveQuotas = Maps.newHashMap();
629 for (Map.Entry<String, Long> entry : activeQuotas.entrySet()) {
630 setInterfaceQuota(entry.getKey(), entry.getValue());
631 }
632 }
633
634 size = mActiveAlerts.size();
635 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800636 if (DBG) Slog.d(TAG, "Pushing " + size + " active alert rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700637 final HashMap<String, Long> activeAlerts = mActiveAlerts;
638 mActiveAlerts = Maps.newHashMap();
639 for (Map.Entry<String, Long> entry : activeAlerts.entrySet()) {
640 setInterfaceAlert(entry.getKey(), entry.getValue());
641 }
642 }
643
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700644 SparseBooleanArray uidRejectOnQuota = null;
645 SparseBooleanArray uidAcceptOnQuota = null;
646 synchronized (mRulesLock) {
647 size = mUidRejectOnMetered.size();
648 if (size > 0) {
649 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered blacklist rules");
650 uidRejectOnQuota = mUidRejectOnMetered;
651 mUidRejectOnMetered = new SparseBooleanArray();
652 }
653
654 size = mUidAllowOnMetered.size();
655 if (size > 0) {
656 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered whitelist rules");
657 uidAcceptOnQuota = mUidAllowOnMetered;
658 mUidAllowOnMetered = new SparseBooleanArray();
659 }
660 }
661 if (uidRejectOnQuota != null) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700662 for (int i = 0; i < uidRejectOnQuota.size(); i++) {
Felipe Leme65be3022016-03-22 14:53:13 -0700663 setUidMeteredNetworkBlacklist(uidRejectOnQuota.keyAt(i),
664 uidRejectOnQuota.valueAt(i));
665 }
666 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700667 if (uidAcceptOnQuota != null) {
Felipe Leme65be3022016-03-22 14:53:13 -0700668 for (int i = 0; i < uidAcceptOnQuota.size(); i++) {
669 setUidMeteredNetworkWhitelist(uidAcceptOnQuota.keyAt(i),
670 uidAcceptOnQuota.valueAt(i));
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700671 }
672 }
Jeff Sharkey605eb792014-11-04 13:34:06 -0800673
674 size = mUidCleartextPolicy.size();
675 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800676 if (DBG) Slog.d(TAG, "Pushing " + size + " active UID cleartext policies");
Jeff Sharkey605eb792014-11-04 13:34:06 -0800677 final SparseIntArray local = mUidCleartextPolicy;
678 mUidCleartextPolicy = new SparseIntArray();
679 for (int i = 0; i < local.size(); i++) {
680 setUidCleartextNetworkPolicy(local.keyAt(i), local.valueAt(i));
681 }
682 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700683
Robin Leec3736bc2017-03-10 16:19:54 +0000684 setFirewallEnabled(mFirewallEnabled);
Amith Yamasani15e472352015-04-24 19:06:07 -0700685
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700686 syncFirewallChainLocked(FIREWALL_CHAIN_NONE, "");
687 syncFirewallChainLocked(FIREWALL_CHAIN_STANDBY, "standby ");
688 syncFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, "dozable ");
689 syncFirewallChainLocked(FIREWALL_CHAIN_POWERSAVE, "powersave ");
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700690
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700691 final int[] chains =
692 {FIREWALL_CHAIN_STANDBY, FIREWALL_CHAIN_DOZABLE, FIREWALL_CHAIN_POWERSAVE};
693 for (int chain : chains) {
694 if (getFirewallChainState(chain)) {
695 setFirewallChainEnabled(chain, true);
696 }
Felipe Leme011b98f2016-02-10 17:28:31 -0800697 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700698 }
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900699
Luke Huang56a03a02018-09-07 12:02:16 +0800700
701 try {
702 getBatteryStats().noteNetworkStatsEnabled();
703 } catch (RemoteException e) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900704 }
705
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700706 }
San Mehat4d02d002010-01-22 16:07:46 -0800707
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900708 /**
709 * Notify our observers of a new or updated interface address.
710 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900711 private void notifyAddressUpdated(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900712 invokeForAllObservers(o -> o.addressUpdated(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900713 }
714
715 /**
716 * Notify our observers of a deleted interface address.
717 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900718 private void notifyAddressRemoved(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900719 invokeForAllObservers(o -> o.addressRemoved(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900720 }
721
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900722 /**
723 * Notify our observers of DNS server information received.
724 */
725 private void notifyInterfaceDnsServerInfo(String iface, long lifetime, String[] addresses) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900726 invokeForAllObservers(o -> o.interfaceDnsServerInfo(iface, lifetime, addresses));
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900727 }
728
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900729 /**
730 * Notify our observers of a route change.
731 */
732 private void notifyRouteChange(String action, RouteInfo route) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900733 if (action.equals("updated")) {
734 invokeForAllObservers(o -> o.routeUpdated(route));
735 } else {
736 invokeForAllObservers(o -> o.routeRemoved(route));
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900737 }
738 }
739
San Mehat873f2142010-01-14 10:25:07 -0800740 //
741 // Netd Callback handling
742 //
743
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700744 private class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
745 @Override
San Mehat873f2142010-01-14 10:25:07 -0800746 public void onDaemonConnected() {
Felipe Leme65be3022016-03-22 14:53:13 -0700747 Slog.i(TAG, "onDaemonConnected()");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700748 // event is dispatched from internal NDC thread, so we prepare the
749 // daemon back on main thread.
750 if (mConnectedSignal != null) {
bohu07cc3bb2016-05-03 15:58:01 -0700751 // The system is booting and we're connecting to netd for the first time.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700752 mConnectedSignal.countDown();
753 mConnectedSignal = null;
754 } else {
bohu07cc3bb2016-05-03 15:58:01 -0700755 // We're reconnecting to netd after the socket connection
756 // was interrupted (e.g., if it crashed).
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700757 mFgHandler.post(new Runnable() {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700758 @Override
759 public void run() {
bohu07cc3bb2016-05-03 15:58:01 -0700760 connectNativeNetdService();
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700761 prepareNativeDaemon();
762 }
763 });
764 }
San Mehat873f2142010-01-14 10:25:07 -0800765 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700766
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700767 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800768 public boolean onCheckHoldWakeLock(int code) {
769 return code == NetdResponseCode.InterfaceClassActivity;
770 }
771
772 @Override
San Mehat873f2142010-01-14 10:25:07 -0800773 public boolean onEvent(int code, String raw, String[] cooked) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900774 String errorMessage = String.format("Invalid event from daemon (%s)", raw);
JP Abgrall12b933d2011-07-14 18:09:22 -0700775 switch (code) {
776 case NetdResponseCode.InterfaceChange:
777 /*
778 * a network interface change occured
779 * Format: "NNN Iface added <name>"
780 * "NNN Iface removed <name>"
781 * "NNN Iface changed <name> <up/down>"
782 * "NNN Iface linkstatus <name> <up/down>"
783 */
784 if (cooked.length < 4 || !cooked[1].equals("Iface")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900785 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700786 }
787 if (cooked[2].equals("added")) {
788 notifyInterfaceAdded(cooked[3]);
789 return true;
790 } else if (cooked[2].equals("removed")) {
791 notifyInterfaceRemoved(cooked[3]);
792 return true;
793 } else if (cooked[2].equals("changed") && cooked.length == 5) {
794 notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
795 return true;
796 } else if (cooked[2].equals("linkstate") && cooked.length == 5) {
797 notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
798 return true;
799 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900800 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700801 // break;
802 case NetdResponseCode.BandwidthControl:
803 /*
804 * Bandwidth control needs some attention
805 * Format: "NNN limit alert <alertName> <ifaceName>"
806 */
807 if (cooked.length < 5 || !cooked[1].equals("limit")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900808 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700809 }
810 if (cooked[2].equals("alert")) {
811 notifyLimitReached(cooked[3], cooked[4]);
812 return true;
813 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900814 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700815 // break;
Haoyu Baidb3c8672012-06-20 14:29:57 -0700816 case NetdResponseCode.InterfaceClassActivity:
817 /*
818 * An network interface class state changed (active/idle)
819 * Format: "NNN IfaceClass <active/idle> <label>"
820 */
821 if (cooked.length < 4 || !cooked[1].equals("IfaceClass")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900822 throw new IllegalStateException(errorMessage);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700823 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700824 long timestampNanos = 0;
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700825 int processUid = -1;
826 if (cooked.length >= 5) {
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700827 try {
828 timestampNanos = Long.parseLong(cooked[4]);
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700829 if (cooked.length == 6) {
830 processUid = Integer.parseInt(cooked[5]);
831 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700832 } catch(NumberFormatException ne) {}
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700833 } else {
834 timestampNanos = SystemClock.elapsedRealtimeNanos();
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700835 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700836 boolean isActive = cooked[2].equals("active");
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700837 notifyInterfaceClassActivity(Integer.parseInt(cooked[3]),
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700838 isActive ? DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700839 : DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
840 timestampNanos, processUid, false);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700841 return true;
842 // break;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900843 case NetdResponseCode.InterfaceAddressChange:
844 /*
845 * A network address change occurred
846 * Format: "NNN Address updated <addr> <iface> <flags> <scope>"
847 * "NNN Address removed <addr> <iface> <flags> <scope>"
848 */
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900849 if (cooked.length < 7 || !cooked[1].equals("Address")) {
850 throw new IllegalStateException(errorMessage);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900851 }
852
Lorenzo Colitti64483942013-11-15 18:43:52 +0900853 String iface = cooked[4];
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900854 LinkAddress address;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900855 try {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900856 int flags = Integer.parseInt(cooked[5]);
857 int scope = Integer.parseInt(cooked[6]);
858 address = new LinkAddress(cooked[3], flags, scope);
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900859 } catch(NumberFormatException e) { // Non-numeric lifetime or scope.
860 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti64483942013-11-15 18:43:52 +0900861 } catch(IllegalArgumentException e) { // Malformed/invalid IP address.
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900862 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900863 }
864
865 if (cooked[2].equals("updated")) {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900866 notifyAddressUpdated(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900867 } else {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900868 notifyAddressRemoved(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900869 }
870 return true;
871 // break;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900872 case NetdResponseCode.InterfaceDnsServerInfo:
873 /*
874 * Information about available DNS servers has been received.
875 * Format: "NNN DnsInfo servers <interface> <lifetime> <servers>"
876 */
877 long lifetime; // Actually a 32-bit unsigned integer.
878
879 if (cooked.length == 6 &&
880 cooked[1].equals("DnsInfo") &&
881 cooked[2].equals("servers")) {
882 try {
883 lifetime = Long.parseLong(cooked[4]);
884 } catch (NumberFormatException e) {
885 throw new IllegalStateException(errorMessage);
886 }
887 String[] servers = cooked[5].split(",");
888 notifyInterfaceDnsServerInfo(cooked[3], lifetime, servers);
889 }
890 return true;
891 // break;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900892 case NetdResponseCode.RouteChange:
893 /*
894 * A route has been updated or removed.
895 * Format: "NNN Route <updated|removed> <dst> [via <gateway] [dev <iface>]"
896 */
897 if (!cooked[1].equals("Route") || cooked.length < 6) {
898 throw new IllegalStateException(errorMessage);
899 }
900
901 String via = null;
902 String dev = null;
903 boolean valid = true;
904 for (int i = 4; (i + 1) < cooked.length && valid; i += 2) {
905 if (cooked[i].equals("dev")) {
906 if (dev == null) {
907 dev = cooked[i+1];
908 } else {
909 valid = false; // Duplicate interface.
910 }
911 } else if (cooked[i].equals("via")) {
912 if (via == null) {
913 via = cooked[i+1];
914 } else {
915 valid = false; // Duplicate gateway.
916 }
917 } else {
918 valid = false; // Unknown syntax.
919 }
920 }
921 if (valid) {
922 try {
923 // InetAddress.parseNumericAddress(null) inexplicably returns ::1.
924 InetAddress gateway = null;
925 if (via != null) gateway = InetAddress.parseNumericAddress(via);
926 RouteInfo route = new RouteInfo(new IpPrefix(cooked[3]), gateway, dev);
927 notifyRouteChange(cooked[2], route);
928 return true;
929 } catch (IllegalArgumentException e) {}
930 }
931 throw new IllegalStateException(errorMessage);
932 // break;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800933 case NetdResponseCode.StrictCleartext:
934 final int uid = Integer.parseInt(cooked[1]);
935 final byte[] firstPacket = HexDump.hexStringToByteArray(cooked[2]);
936 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800937 ActivityManager.getService().notifyCleartextNetwork(uid, firstPacket);
Jeff Sharkey605eb792014-11-04 13:34:06 -0800938 } catch (RemoteException ignored) {
939 }
940 break;
JP Abgrall12b933d2011-07-14 18:09:22 -0700941 default: break;
Robert Greenwalte3253922010-02-18 09:23:25 -0800942 }
943 return false;
San Mehat873f2142010-01-14 10:25:07 -0800944 }
945 }
946
San Mehated4fc8a2010-01-22 12:28:36 -0800947
San Mehat873f2142010-01-14 10:25:07 -0800948 //
949 // INetworkManagementService members
950 //
Erik Kline4e37b702016-07-05 11:34:21 +0900951 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800952 public String[] listInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800953 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700954 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +0800955 return mNetdService.interfaceGetList();
Luke Huang14f75442018-08-15 19:22:54 +0800956 } catch (RemoteException | ServiceSpecificException e) {
957 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700958 }
San Mehated4fc8a2010-01-22 12:28:36 -0800959 }
960
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800961 @Override
962 public InterfaceConfiguration getInterfaceConfig(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800963 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang14f75442018-08-15 19:22:54 +0800964 final InterfaceConfigurationParcel result;
Kenny Roota80ce062010-06-01 13:23:53 -0700965 try {
Luke Huang14f75442018-08-15 19:22:54 +0800966 result = mNetdService.interfaceGetCfg(iface);
967 } catch (RemoteException | ServiceSpecificException e) {
968 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700969 }
San Mehated4fc8a2010-01-22 12:28:36 -0800970
San Mehated4fc8a2010-01-22 12:28:36 -0800971 try {
Luke Huang14f75442018-08-15 19:22:54 +0800972 final InterfaceConfiguration cfg = InterfaceConfiguration.fromParcel(result);
973 return cfg;
974 } catch (IllegalArgumentException iae) {
975 throw new IllegalStateException("Invalid InterfaceConfigurationParcel", iae);
San Mehated4fc8a2010-01-22 12:28:36 -0800976 }
San Mehated4fc8a2010-01-22 12:28:36 -0800977 }
978
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800979 @Override
980 public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800981 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800982 LinkAddress linkAddr = cfg.getLinkAddress();
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800983 if (linkAddr == null || linkAddr.getAddress() == null) {
984 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -0800985 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800986
Luke Huang14f75442018-08-15 19:22:54 +0800987 final InterfaceConfigurationParcel cfgParcel = cfg.toParcel(iface);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800988
Kenny Roota80ce062010-06-01 13:23:53 -0700989 try {
Luke Huang14f75442018-08-15 19:22:54 +0800990 mNetdService.interfaceSetCfg(cfgParcel);
991 } catch (RemoteException | ServiceSpecificException e) {
992 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700993 }
San Mehat873f2142010-01-14 10:25:07 -0800994 }
995
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800996 @Override
997 public void setInterfaceDown(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800998 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800999 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001000 ifcg.setInterfaceDown();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001001 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001002 }
1003
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001004 @Override
1005 public void setInterfaceUp(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001006 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001007 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001008 ifcg.setInterfaceUp();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001009 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001010 }
1011
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001012 @Override
1013 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001014 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sheriff73293612011-09-14 12:31:56 -07001015 try {
Luke Huang14f75442018-08-15 19:22:54 +08001016 mNetdService.interfaceSetIPv6PrivacyExtensions(iface, enable);
1017 } catch (RemoteException | ServiceSpecificException e) {
1018 throw new IllegalStateException(e);
Irfan Sheriff73293612011-09-14 12:31:56 -07001019 }
1020 }
1021
Irfan Sherifff5600612011-06-16 10:26:28 -07001022 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
1023 IPv6 addresses on interface down, but we need to do full clean up here */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001024 @Override
1025 public void clearInterfaceAddresses(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001026 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sherifff5600612011-06-16 10:26:28 -07001027 try {
Luke Huang14f75442018-08-15 19:22:54 +08001028 mNetdService.interfaceClearAddrs(iface);
1029 } catch (RemoteException | ServiceSpecificException e) {
1030 throw new IllegalStateException(e);
Irfan Sherifff5600612011-06-16 10:26:28 -07001031 }
1032 }
1033
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001034 @Override
1035 public void enableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001036 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001037 try {
Luke Huang14f75442018-08-15 19:22:54 +08001038 mNetdService.interfaceSetEnableIPv6(iface, true);
1039 } catch (RemoteException | ServiceSpecificException e) {
1040 throw new IllegalStateException(e);
repo sync7960d9f2011-09-29 12:40:02 -07001041 }
1042 }
1043
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001044 @Override
Joel Scherpelz2db10742017-06-07 15:38:38 +09001045 public void setIPv6AddrGenMode(String iface, int mode) throws ServiceSpecificException {
1046 try {
1047 mNetdService.setIPv6AddrGenMode(iface, mode);
1048 } catch (RemoteException e) {
1049 throw e.rethrowAsRuntimeException();
1050 }
1051 }
1052
1053 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001054 public void disableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001055 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001056 try {
Luke Huang14f75442018-08-15 19:22:54 +08001057 mNetdService.interfaceSetEnableIPv6(iface, false);
1058 } catch (RemoteException | ServiceSpecificException e) {
1059 throw new IllegalStateException(e);
repo sync7960d9f2011-09-29 12:40:02 -07001060 }
1061 }
1062
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001063 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001064 public void addRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001065 modifyRoute(MODIFY_OPERATION_ADD, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001066 }
1067
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001068 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001069 public void removeRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001070 modifyRoute(MODIFY_OPERATION_REMOVE, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001071 }
1072
Luke Huang8a462ec2018-08-24 20:33:16 +08001073 private void modifyRoute(boolean add, int netId, RouteInfo route) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001074 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001075
Luke Huang8a462ec2018-08-24 20:33:16 +08001076 final String ifName = route.getInterface();
1077 final String dst = route.getDestination().toString();
1078 final String nextHop;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001079
1080 switch (route.getType()) {
1081 case RouteInfo.RTN_UNICAST:
1082 if (route.hasGateway()) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001083 nextHop = route.getGateway().getHostAddress();
1084 } else {
1085 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001086 }
1087 break;
1088 case RouteInfo.RTN_UNREACHABLE:
Luke Huang8a462ec2018-08-24 20:33:16 +08001089 nextHop = INetd.NEXTHOP_UNREACHABLE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001090 break;
1091 case RouteInfo.RTN_THROW:
Luke Huang8a462ec2018-08-24 20:33:16 +08001092 nextHop = INetd.NEXTHOP_THROW;
1093 break;
1094 default:
1095 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001096 break;
Sreeram Ramachandran1fbcb272014-05-22 16:30:48 -07001097 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001098 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08001099 if (add) {
1100 mNetdService.networkAddRoute(netId, ifName, dst, nextHop);
1101 } else {
1102 mNetdService.networkRemoveRoute(netId, ifName, dst, nextHop);
1103 }
1104 } catch (RemoteException | ServiceSpecificException e) {
1105 throw new IllegalStateException(e);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001106 }
1107 }
1108
1109 private ArrayList<String> readRouteList(String filename) {
1110 FileInputStream fstream = null;
Christopher Wiley212b95f2016-08-02 11:38:57 -07001111 ArrayList<String> list = new ArrayList<>();
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001112
1113 try {
1114 fstream = new FileInputStream(filename);
1115 DataInputStream in = new DataInputStream(fstream);
1116 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1117 String s;
1118
1119 // throw away the title line
1120
1121 while (((s = br.readLine()) != null) && (s.length() != 0)) {
1122 list.add(s);
1123 }
1124 } catch (IOException ex) {
1125 // return current list, possibly empty
1126 } finally {
1127 if (fstream != null) {
1128 try {
1129 fstream.close();
1130 } catch (IOException ex) {}
1131 }
1132 }
1133
1134 return list;
1135 }
1136
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001137 @Override
sy.yun9d9b74a2013-09-02 05:24:09 +09001138 public void setMtu(String iface, int mtu) {
1139 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1140
sy.yun9d9b74a2013-09-02 05:24:09 +09001141 try {
Luke Huang14f75442018-08-15 19:22:54 +08001142 mNetdService.interfaceSetMtu(iface, mtu);
1143 } catch (RemoteException | ServiceSpecificException e) {
1144 throw new IllegalStateException(e);
sy.yun9d9b74a2013-09-02 05:24:09 +09001145 }
1146 }
1147
1148 @Override
San Mehat873f2142010-01-14 10:25:07 -08001149 public void shutdown() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001150 // TODO: remove from aidl if nobody calls externally
1151 mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001152
Felipe Leme03e689d2016-03-02 16:17:38 -08001153 Slog.i(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -08001154 }
1155
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001156 @Override
San Mehat873f2142010-01-14 10:25:07 -08001157 public boolean getIpForwardingEnabled() throws IllegalStateException{
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001158 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001159
Kenny Roota80ce062010-06-01 13:23:53 -07001160 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001161 final boolean isEnabled = mNetdService.ipfwdEnabled();
1162 return isEnabled;
1163 } catch (RemoteException | ServiceSpecificException e) {
1164 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001165 }
San Mehat873f2142010-01-14 10:25:07 -08001166 }
1167
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001168 @Override
1169 public void setIpForwardingEnabled(boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001170 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001171 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001172 if (enable) {
1173 mNetdService.ipfwdEnableForwarding("tethering");
1174 } else {
1175 mNetdService.ipfwdDisableForwarding("tethering");
1176 }
1177 } catch (RemoteException | ServiceSpecificException e) {
1178 throw new IllegalStateException(e);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001179 }
San Mehat873f2142010-01-14 10:25:07 -08001180 }
1181
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001182 @Override
1183 public void startTethering(String[] dhcpRange) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001184 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -07001185 // an odd number of addrs will fail
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001186
Kenny Roota80ce062010-06-01 13:23:53 -07001187 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001188 mNetdService.tetherStart(dhcpRange);
1189 } catch (RemoteException | ServiceSpecificException e) {
1190 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001191 }
San Mehat873f2142010-01-14 10:25:07 -08001192 }
1193
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001194 @Override
1195 public void stopTethering() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001196 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001197 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001198 mNetdService.tetherStop();
1199 } catch (RemoteException | ServiceSpecificException e) {
1200 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001201 }
San Mehat873f2142010-01-14 10:25:07 -08001202 }
1203
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001204 @Override
1205 public boolean isTetheringStarted() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001206 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001207
Kenny Roota80ce062010-06-01 13:23:53 -07001208 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001209 final boolean isEnabled = mNetdService.tetherIsEnabled();
1210 return isEnabled;
1211 } catch (RemoteException | ServiceSpecificException e) {
1212 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001213 }
San Mehat873f2142010-01-14 10:25:07 -08001214 }
Matthew Xiefe19f122012-07-12 16:03:32 -07001215
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001216 @Override
1217 public void tetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001218 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001219 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001220 mNetdService.tetherInterfaceAdd(iface);
1221 } catch (RemoteException | ServiceSpecificException e) {
1222 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001223 }
Christopher Wiley212b95f2016-08-02 11:38:57 -07001224 List<RouteInfo> routes = new ArrayList<>();
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07001225 // The RouteInfo constructor truncates the LinkAddress to a network prefix, thus making it
1226 // suitable to use as a route destination.
1227 routes.add(new RouteInfo(getInterfaceConfig(iface).getLinkAddress(), null, iface));
1228 addInterfaceToLocalNetwork(iface, routes);
San Mehat873f2142010-01-14 10:25:07 -08001229 }
1230
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001231 @Override
San Mehat873f2142010-01-14 10:25:07 -08001232 public void untetherInterface(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.tetherInterfaceRemove(iface);
1236 } catch (RemoteException | ServiceSpecificException e) {
1237 throw new IllegalStateException(e);
Erik Kline1f4278a2016-08-16 16:46:33 +09001238 } finally {
1239 removeInterfaceFromLocalNetwork(iface);
Kenny Roota80ce062010-06-01 13:23:53 -07001240 }
San Mehat873f2142010-01-14 10:25:07 -08001241 }
1242
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001243 @Override
1244 public String[] listTetheredInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001245 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001246 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +08001247 return mNetdService.tetherInterfaceList();
Luke Huang4a32bf42018-08-21 19:09:45 +08001248 } catch (RemoteException | ServiceSpecificException e) {
1249 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001250 }
San Mehat873f2142010-01-14 10:25:07 -08001251 }
1252
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001253 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001254 public void setDnsForwarders(Network network, String[] dns) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001255 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001256
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001257 int netId = (network != null) ? network.netId : ConnectivityManager.NETID_UNSET;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001258
San Mehat873f2142010-01-14 10:25:07 -08001259 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001260 mNetdService.tetherDnsSet(netId, dns);
1261 } catch (RemoteException | ServiceSpecificException e) {
1262 throw new IllegalStateException(e);
San Mehat873f2142010-01-14 10:25:07 -08001263 }
1264 }
1265
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001266 @Override
1267 public String[] getDnsForwarders() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001268 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001269 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +08001270 return mNetdService.tetherDnsList();
Luke Huang4a32bf42018-08-21 19:09:45 +08001271 } catch (RemoteException | ServiceSpecificException e) {
1272 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001273 }
San Mehat873f2142010-01-14 10:25:07 -08001274 }
1275
jiaguo1da35f72014-01-09 16:39:59 +08001276 private List<InterfaceAddress> excludeLinkLocal(List<InterfaceAddress> addresses) {
Christopher Wiley212b95f2016-08-02 11:38:57 -07001277 ArrayList<InterfaceAddress> filtered = new ArrayList<>(addresses.size());
jiaguo1da35f72014-01-09 16:39:59 +08001278 for (InterfaceAddress ia : addresses) {
1279 if (!ia.getAddress().isLinkLocalAddress())
1280 filtered.add(ia);
1281 }
1282 return filtered;
1283 }
1284
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001285 private void modifyInterfaceForward(boolean add, String fromIface, String toIface) {
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001286 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001287 if (add) {
1288 mNetdService.ipfwdAddInterfaceForward(fromIface, toIface);
1289 } else {
1290 mNetdService.ipfwdRemoveInterfaceForward(fromIface, toIface);
1291 }
1292 } catch (RemoteException | ServiceSpecificException e) {
1293 throw new IllegalStateException(e);
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001294 }
1295 }
1296
1297 @Override
1298 public void startInterfaceForwarding(String fromIface, String toIface) {
1299 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1300 modifyInterfaceForward(true, fromIface, toIface);
1301 }
1302
1303 @Override
1304 public void stopInterfaceForwarding(String fromIface, String toIface) {
1305 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1306 modifyInterfaceForward(false, fromIface, toIface);
1307 }
1308
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001309 @Override
1310 public void enableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001311 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001312 try {
Luke Huanga31e0732018-10-22 13:23:10 +09001313 mNetdService.tetherAddForward(internalInterface, externalInterface);
1314 } catch (RemoteException | ServiceSpecificException e) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001315 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001316 }
San Mehat873f2142010-01-14 10:25:07 -08001317 }
1318
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001319 @Override
1320 public void disableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001321 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001322 try {
Luke Huanga31e0732018-10-22 13:23:10 +09001323 mNetdService.tetherRemoveForward(internalInterface, externalInterface);
1324 } catch (RemoteException | ServiceSpecificException e) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001325 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001326 }
San Mehat873f2142010-01-14 10:25:07 -08001327 }
San Mehat72759df2010-01-19 13:50:37 -08001328
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001329 @Override
1330 public String[] listTtys() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001331 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001332 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001333 return NativeDaemonEvent.filterMessageList(
1334 mConnector.executeForList("list_ttys"), TtyListResult);
Kenny Roota80ce062010-06-01 13:23:53 -07001335 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001336 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001337 }
San Mehat72759df2010-01-19 13:50:37 -08001338 }
1339
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001340 @Override
1341 public void attachPppd(
1342 String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001343 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat72759df2010-01-19 13:50:37 -08001344 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001345 mConnector.execute("pppd", "attach", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -08001346 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
1347 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
1348 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001349 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress());
Kenny Roota80ce062010-06-01 13:23:53 -07001350 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001351 throw e.rethrowAsParcelableException();
San Mehat72759df2010-01-19 13:50:37 -08001352 }
1353 }
1354
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001355 @Override
1356 public void detachPppd(String tty) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001357 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001358 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001359 mConnector.execute("pppd", "detach", tty);
Kenny Roota80ce062010-06-01 13:23:53 -07001360 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001361 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001362 }
San Mehat72759df2010-01-19 13:50:37 -08001363 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -08001364
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001365 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001366 public void addIdleTimer(String iface, int timeout, final int type) {
Haoyu Bai04124232012-06-28 15:26:19 -07001367 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1368
1369 if (DBG) Slog.d(TAG, "Adding idletimer");
1370
1371 synchronized (mIdleTimerLock) {
1372 IdleTimerParams params = mActiveIdleTimers.get(iface);
1373 if (params != null) {
1374 // the interface already has idletimer, update network count
1375 params.networkCount++;
1376 return;
1377 }
1378
1379 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001380 mNetdService.idletimerAddInterface(iface, timeout, Integer.toString(type));
1381 } catch (RemoteException | ServiceSpecificException e) {
1382 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001383 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001384 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
1385
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001386 // Networks start up.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001387 if (ConnectivityManager.isNetworkTypeMobile(type)) {
1388 mNetworkActive = false;
1389 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001390 mDaemonHandler.post(new Runnable() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001391 @Override public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001392 notifyInterfaceClassActivity(type,
1393 DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07001394 SystemClock.elapsedRealtimeNanos(), -1, false);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001395 }
1396 });
Haoyu Bai04124232012-06-28 15:26:19 -07001397 }
1398 }
1399
1400 @Override
1401 public void removeIdleTimer(String iface) {
1402 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1403
1404 if (DBG) Slog.d(TAG, "Removing idletimer");
1405
1406 synchronized (mIdleTimerLock) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001407 final IdleTimerParams params = mActiveIdleTimers.get(iface);
Haoyu Bai04124232012-06-28 15:26:19 -07001408 if (params == null || --(params.networkCount) > 0) {
1409 return;
1410 }
1411
1412 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001413 mNetdService.idletimerRemoveInterface(iface,
1414 params.timeout, Integer.toString(params.type));
1415 } catch (RemoteException | ServiceSpecificException e) {
1416 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001417 }
1418 mActiveIdleTimers.remove(iface);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001419 mDaemonHandler.post(new Runnable() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001420 @Override public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001421 notifyInterfaceClassActivity(params.type,
1422 DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07001423 SystemClock.elapsedRealtimeNanos(), -1, false);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001424 }
1425 });
Haoyu Bai04124232012-06-28 15:26:19 -07001426 }
1427 }
1428
1429 @Override
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001430 public NetworkStats getNetworkStatsSummaryDev() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001431 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001432 try {
1433 return mStatsFactory.readNetworkStatsSummaryDev();
1434 } catch (IOException e) {
1435 throw new IllegalStateException(e);
1436 }
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001437 }
1438
1439 @Override
1440 public NetworkStats getNetworkStatsSummaryXt() {
1441 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001442 try {
1443 return mStatsFactory.readNetworkStatsSummaryXt();
1444 } catch (IOException e) {
1445 throw new IllegalStateException(e);
1446 }
Jeff Sharkeyae2c1812011-10-04 13:11:40 -07001447 }
1448
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001449 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001450 public NetworkStats getNetworkStatsDetail() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001451 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001452 try {
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08001453 return mStatsFactory.readNetworkStatsDetail(UID_ALL, null, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001454 } catch (IOException e) {
1455 throw new IllegalStateException(e);
1456 }
San Mehat91cac642010-03-31 14:31:36 -07001457 }
1458
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001459 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001460 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001461 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001462
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001463 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001464 if (mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001465 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001466 }
1467
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001468 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001469 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001470 mNetdService.bandwidthSetInterfaceQuota(iface, quotaBytes);
1471
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001472 mActiveQuotas.put(iface, quotaBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001473 } catch (RemoteException | ServiceSpecificException e) {
1474 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001475 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001476
1477 synchronized (mTetheringStatsProviders) {
1478 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1479 try {
1480 provider.setInterfaceQuota(iface, quotaBytes);
1481 } catch (RemoteException e) {
1482 Log.e(TAG, "Problem setting tethering data limit on provider " +
1483 mTetheringStatsProviders.get(provider) + ": " + e);
1484 }
1485 }
1486 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001487 }
1488 }
1489
1490 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001491 public void removeInterfaceQuota(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001492 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001493
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001494 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001495 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001496 // TODO: eventually consider throwing
1497 return;
1498 }
1499
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001500 mActiveQuotas.remove(iface);
1501 mActiveAlerts.remove(iface);
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001502
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001503 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001504 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001505 mNetdService.bandwidthRemoveInterfaceQuota(iface);
1506 } catch (RemoteException | ServiceSpecificException e) {
1507 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001508 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001509
1510 synchronized (mTetheringStatsProviders) {
1511 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1512 try {
1513 provider.setInterfaceQuota(iface, ITetheringStatsProvider.QUOTA_UNLIMITED);
1514 } catch (RemoteException e) {
1515 Log.e(TAG, "Problem removing tethering data limit on provider " +
1516 mTetheringStatsProviders.get(provider) + ": " + e);
1517 }
1518 }
1519 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001520 }
1521 }
1522
1523 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001524 public void setInterfaceAlert(String iface, long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001525 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001526
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001527 // quick sanity check
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001528 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001529 throw new IllegalStateException("setting alert requires existing quota on iface");
1530 }
1531
1532 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001533 if (mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001534 throw new IllegalStateException("iface " + iface + " already has alert");
1535 }
1536
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001537 try {
1538 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001539 mNetdService.bandwidthSetInterfaceAlert(iface, alertBytes);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001540 mActiveAlerts.put(iface, alertBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001541 } catch (RemoteException | ServiceSpecificException e) {
1542 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001543 }
1544 }
1545 }
1546
1547 @Override
1548 public void removeInterfaceAlert(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001549 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001550
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001551 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001552 if (!mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001553 // TODO: eventually consider throwing
1554 return;
1555 }
1556
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001557 try {
1558 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001559 mNetdService.bandwidthRemoveInterfaceAlert(iface);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001560 mActiveAlerts.remove(iface);
Luke Huangc7bea8662018-08-07 16:04:26 +08001561 } catch (RemoteException | ServiceSpecificException e) {
1562 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001563 }
1564 }
1565 }
1566
1567 @Override
1568 public void setGlobalAlert(long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001569 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001570
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001571 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001572 mNetdService.bandwidthSetGlobalAlert(alertBytes);
1573 } catch (RemoteException | ServiceSpecificException e) {
1574 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001575 }
1576 }
1577
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001578 private void setUidOnMeteredNetworkList(int uid, boolean blacklist, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001579 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001580
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001581 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001582 boolean oldEnable;
1583 SparseBooleanArray quotaList;
1584 synchronized (mRulesLock) {
1585 quotaList = blacklist ? mUidRejectOnMetered : mUidAllowOnMetered;
1586 oldEnable = quotaList.get(uid, false);
1587 }
Felipe Leme65be3022016-03-22 14:53:13 -07001588 if (oldEnable == enable) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001589 // TODO: eventually consider throwing
1590 return;
1591 }
1592
Felipe Leme29e72ea2016-09-08 13:26:55 -07001593 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "inetd bandwidth");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001594 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001595 if (blacklist) {
1596 if (enable) {
1597 mNetdService.bandwidthAddNaughtyApp(uid);
1598 } else {
1599 mNetdService.bandwidthRemoveNaughtyApp(uid);
1600 }
1601 } else {
1602 if (enable) {
1603 mNetdService.bandwidthAddNiceApp(uid);
1604 } else {
1605 mNetdService.bandwidthRemoveNiceApp(uid);
1606 }
1607 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001608 synchronized (mRulesLock) {
1609 if (enable) {
1610 quotaList.put(uid, true);
1611 } else {
1612 quotaList.delete(uid);
1613 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001614 }
Luke Huangc7bea8662018-08-07 16:04:26 +08001615 } catch (RemoteException | ServiceSpecificException e) {
1616 throw new IllegalStateException(e);
Felipe Leme29e72ea2016-09-08 13:26:55 -07001617 } finally {
1618 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001619 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001620 }
1621 }
1622
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001623 @Override
Felipe Leme65be3022016-03-22 14:53:13 -07001624 public void setUidMeteredNetworkBlacklist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001625 setUidOnMeteredNetworkList(uid, true, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001626 }
1627
1628 @Override
1629 public void setUidMeteredNetworkWhitelist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001630 setUidOnMeteredNetworkList(uid, false, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001631 }
1632
1633 @Override
1634 public boolean setDataSaverModeEnabled(boolean enable) {
Sehee Parka9139bc2017-12-22 13:54:05 +09001635 mContext.enforceCallingOrSelfPermission(NETWORK_SETTINGS, TAG);
1636
Felipe Leme65be3022016-03-22 14:53:13 -07001637 if (DBG) Log.d(TAG, "setDataSaverMode: " + enable);
1638 synchronized (mQuotaLock) {
1639 if (mDataSaverMode == enable) {
1640 Log.w(TAG, "setDataSaverMode(): already " + mDataSaverMode);
1641 return true;
1642 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07001643 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "bandwidthEnableDataSaver");
Felipe Leme65be3022016-03-22 14:53:13 -07001644 try {
1645 final boolean changed = mNetdService.bandwidthEnableDataSaver(enable);
1646 if (changed) {
1647 mDataSaverMode = enable;
1648 } else {
1649 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command silently failed");
1650 }
1651 return changed;
1652 } catch (RemoteException e) {
1653 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command failed", e);
1654 return false;
Felipe Leme29e72ea2016-09-08 13:26:55 -07001655 } finally {
1656 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme65be3022016-03-22 14:53:13 -07001657 }
1658 }
1659 }
1660
1661 @Override
Robin Lee17e61832016-05-09 13:46:28 +01001662 public void setAllowOnlyVpnForUids(boolean add, UidRange[] uidRanges)
1663 throws ServiceSpecificException {
Rubin Xu2ea6c552018-01-11 10:59:19 +00001664 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robin Lee17e61832016-05-09 13:46:28 +01001665 try {
1666 mNetdService.networkRejectNonSecureVpn(add, uidRanges);
1667 } catch (ServiceSpecificException e) {
1668 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1669 + ": netd command failed", e);
1670 throw e;
1671 } catch (RemoteException e) {
1672 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1673 + ": netd command failed", e);
1674 throw e.rethrowAsRuntimeException();
1675 }
1676 }
1677
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001678 private void applyUidCleartextNetworkPolicy(int uid, int policy) {
Luke Huang473eb872018-07-26 17:33:14 +08001679 final int policyValue;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001680 switch (policy) {
1681 case StrictMode.NETWORK_POLICY_ACCEPT:
Luke Huang473eb872018-07-26 17:33:14 +08001682 policyValue = INetd.PENALTY_POLICY_ACCEPT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001683 break;
1684 case StrictMode.NETWORK_POLICY_LOG:
Luke Huang473eb872018-07-26 17:33:14 +08001685 policyValue = INetd.PENALTY_POLICY_LOG;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001686 break;
1687 case StrictMode.NETWORK_POLICY_REJECT:
Luke Huang473eb872018-07-26 17:33:14 +08001688 policyValue = INetd.PENALTY_POLICY_REJECT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001689 break;
1690 default:
1691 throw new IllegalArgumentException("Unknown policy " + policy);
1692 }
1693
1694 try {
Luke Huang473eb872018-07-26 17:33:14 +08001695 mNetdService.strictUidCleartextPenalty(uid, policyValue);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001696 mUidCleartextPolicy.put(uid, policy);
Luke Huang473eb872018-07-26 17:33:14 +08001697 } catch (RemoteException | ServiceSpecificException e) {
1698 throw new IllegalStateException(e);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001699 }
1700 }
1701
Robin Lee17e61832016-05-09 13:46:28 +01001702 @Override
Jeff Sharkey605eb792014-11-04 13:34:06 -08001703 public void setUidCleartextNetworkPolicy(int uid, int policy) {
1704 if (Binder.getCallingUid() != uid) {
1705 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1706 }
1707
1708 synchronized (mQuotaLock) {
1709 final int oldPolicy = mUidCleartextPolicy.get(uid, StrictMode.NETWORK_POLICY_ACCEPT);
1710 if (oldPolicy == policy) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001711 // This also ensures we won't needlessly apply an ACCEPT policy if we've just
1712 // enabled strict and the underlying iptables rules are empty.
Jeff Sharkey605eb792014-11-04 13:34:06 -08001713 return;
1714 }
1715
Luke Huang473eb872018-07-26 17:33:14 +08001716 // TODO: remove this code after removing prepareNativeDaemon()
Jeff Sharkey605eb792014-11-04 13:34:06 -08001717 if (!mStrictEnabled) {
1718 // Module isn't enabled yet; stash the requested policy away to
1719 // apply later once the daemon is connected.
1720 mUidCleartextPolicy.put(uid, policy);
1721 return;
1722 }
1723
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001724 // netd does not keep state on strict mode policies, and cannot replace a non-accept
1725 // policy without deleting it first. Rather than add state to netd, just always send
1726 // it an accept policy when switching between two non-accept policies.
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001727 // TODO: consider keeping state in netd so we can simplify this code.
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001728 if (oldPolicy != StrictMode.NETWORK_POLICY_ACCEPT &&
1729 policy != StrictMode.NETWORK_POLICY_ACCEPT) {
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001730 applyUidCleartextNetworkPolicy(uid, StrictMode.NETWORK_POLICY_ACCEPT);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001731 }
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001732
1733 applyUidCleartextNetworkPolicy(uid, policy);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001734 }
1735 }
1736
1737 @Override
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001738 public boolean isBandwidthControlEnabled() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001739 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang56a03a02018-09-07 12:02:16 +08001740 return true;
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001741 }
1742
1743 @Override
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001744 public NetworkStats getNetworkStatsUidDetail(int uid, String[] ifaces) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001745 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001746 try {
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001747 return mStatsFactory.readNetworkStatsDetail(uid, ifaces, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001748 } catch (IOException e) {
1749 throw new IllegalStateException(e);
1750 }
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001751 }
1752
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001753 private class NetdTetheringStatsProvider extends ITetheringStatsProvider.Stub {
1754 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001755 public NetworkStats getTetherStats(int how) {
1756 // We only need to return per-UID stats. Per-device stats are already counted by
1757 // interface counters.
1758 if (how != STATS_PER_UID) {
1759 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
1760 }
1761
Luke Huang13b79e82018-09-26 14:53:42 +08001762 final TetherStatsParcel[] tetherStatsVec;
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001763 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001764 tetherStatsVec = mNetdService.tetherGetStats();
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001765 } catch (RemoteException | ServiceSpecificException e) {
1766 throw new IllegalStateException("problem parsing tethering stats: ", e);
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001767 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001768
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001769 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(),
Luke Huang13b79e82018-09-26 14:53:42 +08001770 tetherStatsVec.length);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001771 final NetworkStats.Entry entry = new NetworkStats.Entry();
1772
Luke Huang13b79e82018-09-26 14:53:42 +08001773 for (TetherStatsParcel tetherStats : tetherStatsVec) {
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001774 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001775 entry.iface = tetherStats.iface;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001776 entry.uid = UID_TETHERING;
1777 entry.set = SET_DEFAULT;
1778 entry.tag = TAG_NONE;
Luke Huang13b79e82018-09-26 14:53:42 +08001779 entry.rxBytes = tetherStats.rxBytes;
1780 entry.rxPackets = tetherStats.rxPackets;
1781 entry.txBytes = tetherStats.txBytes;
1782 entry.txPackets = tetherStats.txPackets;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001783 stats.combineValues(entry);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001784 } catch (ArrayIndexOutOfBoundsException e) {
Luke Huang13b79e82018-09-26 14:53:42 +08001785 throw new IllegalStateException("invalid tethering stats " + e);
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001786 }
1787 }
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001788
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001789 return stats;
1790 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001791
1792 @Override
1793 public void setInterfaceQuota(String iface, long quotaBytes) {
1794 // Do nothing. netd is already informed of quota changes in setInterfaceQuota.
1795 }
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001796 }
1797
1798 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001799 public NetworkStats getNetworkStatsTethering(int how) {
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001800 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1801
1802 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1803 synchronized (mTetheringStatsProviders) {
1804 for (ITetheringStatsProvider provider: mTetheringStatsProviders.keySet()) {
1805 try {
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001806 stats.combineAllValues(provider.getTetherStats(how));
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001807 } catch (RemoteException e) {
1808 Log.e(TAG, "Problem reading tethering stats from " +
1809 mTetheringStatsProviders.get(provider) + ": " + e);
1810 }
1811 }
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001812 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001813 return stats;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001814 }
1815
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001816 @Override
Erik Kline1742fe12017-12-13 19:40:49 +09001817 public void setDnsConfigurationForNetwork(int netId, String[] servers, String[] domains,
Erik Klinee5dac902018-03-04 21:01:01 +09001818 int[] params, String tlsHostname, String[] tlsServers) {
Pierre Imai8e48e672016-04-21 13:30:43 +09001819 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1820
Ben Schwartz6ec28df2017-10-02 13:08:06 -04001821 final String[] tlsFingerprints = new String[0];
Pierre Imai8e48e672016-04-21 13:30:43 +09001822 try {
Erik Kline1742fe12017-12-13 19:40:49 +09001823 mNetdService.setResolverConfiguration(
Erik Klinee5dac902018-03-04 21:01:01 +09001824 netId, servers, domains, params, tlsHostname, tlsServers, tlsFingerprints);
Pierre Imai8e48e672016-04-21 13:30:43 +09001825 } catch (RemoteException e) {
1826 throw new RuntimeException(e);
1827 }
1828 }
1829
1830 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001831 public void addVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001832 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001833
1834 try {
1835 mNetdService.networkAddUidRanges(netId, ranges);
1836 } catch (RemoteException | ServiceSpecificException e) {
1837 throw new IllegalStateException(e);
Chad Brubaker3277620a2013-06-12 13:37:30 -07001838 }
1839 }
1840
1841 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001842 public void removeVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001843 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001844 try {
1845 mNetdService.networkRemoveUidRanges(netId, ranges);
1846 } catch (RemoteException | ServiceSpecificException e) {
1847 throw new IllegalStateException(e);
Chad Brubakercca54c42013-06-27 17:41:38 -07001848 }
1849 }
1850
1851 @Override
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001852 public void setFirewallEnabled(boolean enabled) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001853 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001854 try {
Luke Huanga241db92018-07-31 20:15:24 +08001855 mNetdService.firewallSetFirewallType(
1856 enabled ? INetd.FIREWALL_WHITELIST : INetd.FIREWALL_BLACKLIST);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001857 mFirewallEnabled = enabled;
Luke Huanga241db92018-07-31 20:15:24 +08001858 } catch (RemoteException | ServiceSpecificException e) {
1859 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001860 }
1861 }
1862
1863 @Override
1864 public boolean isFirewallEnabled() {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001865 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001866 return mFirewallEnabled;
1867 }
1868
1869 @Override
Jeff Sharkey2c092982012-08-24 11:44:40 -07001870 public void setFirewallInterfaceRule(String iface, boolean allow) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001871 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001872 Preconditions.checkState(mFirewallEnabled);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001873 try {
Luke Huanga241db92018-07-31 20:15:24 +08001874 mNetdService.firewallSetInterfaceRule(iface,
1875 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
1876 } catch (RemoteException | ServiceSpecificException e) {
1877 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001878 }
1879 }
1880
Lorenzo Colitti3fef7232016-04-29 18:00:03 +09001881 private void closeSocketsForFirewallChainLocked(int chain, String chainName) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001882 // UID ranges to close sockets on.
1883 UidRange[] ranges;
1884 // UID ranges whose sockets we won't touch.
1885 int[] exemptUids;
1886
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001887 int numUids = 0;
Luke Huanga241db92018-07-31 20:15:24 +08001888 if (DBG) Slog.d(TAG, "Closing sockets after enabling chain " + chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001889 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
1890 // Close all sockets on all non-system UIDs...
1891 ranges = new UidRange[] {
1892 // TODO: is there a better way of finding all existing users? If so, we could
1893 // specify their ranges here.
1894 new UidRange(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE),
1895 };
1896 // ... except for the UIDs that have allow rules.
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001897 synchronized (mRulesLock) {
1898 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1899 exemptUids = new int[rules.size()];
1900 for (int i = 0; i < exemptUids.length; i++) {
1901 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
1902 exemptUids[numUids] = rules.keyAt(i);
1903 numUids++;
1904 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001905 }
1906 }
1907 // Normally, whitelist chains only contain deny rules, so numUids == exemptUids.length.
1908 // But the code does not guarantee this in any way, and at least in one case - if we add
1909 // a UID rule to the firewall, and then disable the firewall - the chains can contain
1910 // the wrong type of rule. In this case, don't close connections that we shouldn't.
1911 //
1912 // TODO: tighten up this code by ensuring we never set the wrong type of rule, and
1913 // fix setFirewallEnabled to grab mQuotaLock and clear rules.
1914 if (numUids != exemptUids.length) {
1915 exemptUids = Arrays.copyOf(exemptUids, numUids);
1916 }
1917 } else {
1918 // Close sockets for every UID that has a deny rule...
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001919 synchronized (mRulesLock) {
1920 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1921 ranges = new UidRange[rules.size()];
1922 for (int i = 0; i < ranges.length; i++) {
1923 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_DENY) {
1924 int uid = rules.keyAt(i);
1925 ranges[numUids] = new UidRange(uid, uid);
1926 numUids++;
1927 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001928 }
1929 }
1930 // As above; usually numUids == ranges.length, but not always.
1931 if (numUids != ranges.length) {
1932 ranges = Arrays.copyOf(ranges, numUids);
1933 }
1934 // ... with no exceptions.
1935 exemptUids = new int[0];
1936 }
1937
1938 try {
1939 mNetdService.socketDestroy(ranges, exemptUids);
1940 } catch(RemoteException | ServiceSpecificException e) {
1941 Slog.e(TAG, "Error closing sockets after enabling chain " + chainName + ": " + e);
1942 }
1943 }
1944
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001945 @Override
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001946 public void setFirewallChainEnabled(int chain, boolean enable) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001947 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001948 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001949 synchronized (mRulesLock) {
1950 if (getFirewallChainState(chain) == enable) {
1951 // All is the same, nothing to do. This relies on the fact that netd has child
1952 // chains default detached.
1953 return;
1954 }
1955 setFirewallChainState(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001956 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001957
Luke Huang615e1022018-10-25 11:54:05 +09001958 final String chainName = getFirewallChainName(chain);
Luke Huanga241db92018-07-31 20:15:24 +08001959 if (chain == FIREWALL_CHAIN_NONE) {
Luke Huang615e1022018-10-25 11:54:05 +09001960 throw new IllegalArgumentException("Bad child chain: " + chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001961 }
1962
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001963 try {
Luke Huanga241db92018-07-31 20:15:24 +08001964 mNetdService.firewallEnableChildChain(chain, enable);
1965 } catch (RemoteException | ServiceSpecificException e) {
1966 throw new IllegalStateException(e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001967 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001968
1969 // Close any sockets that were opened by the affected UIDs. This has to be done after
1970 // disabling network connectivity, in case they react to the socket close by reopening
1971 // the connection and race with the iptables commands that enable the firewall. All
1972 // whitelist and blacklist chains allow RSTs through.
1973 if (enable) {
Luke Huang615e1022018-10-25 11:54:05 +09001974 closeSocketsForFirewallChainLocked(chain, chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001975 }
Amith Yamasani15e472352015-04-24 19:06:07 -07001976 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001977 }
1978
Luke Huanga241db92018-07-31 20:15:24 +08001979 private String getFirewallChainName(int chain) {
1980 switch (chain) {
1981 case FIREWALL_CHAIN_STANDBY:
1982 return FIREWALL_CHAIN_NAME_STANDBY;
1983 case FIREWALL_CHAIN_DOZABLE:
1984 return FIREWALL_CHAIN_NAME_DOZABLE;
1985 case FIREWALL_CHAIN_POWERSAVE:
1986 return FIREWALL_CHAIN_NAME_POWERSAVE;
1987 default:
1988 throw new IllegalArgumentException("Bad child chain: " + chain);
1989 }
1990 }
1991
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001992 private int getFirewallType(int chain) {
1993 switch (chain) {
1994 case FIREWALL_CHAIN_STANDBY:
1995 return FIREWALL_TYPE_BLACKLIST;
1996 case FIREWALL_CHAIN_DOZABLE:
1997 return FIREWALL_TYPE_WHITELIST;
Felipe Leme011b98f2016-02-10 17:28:31 -08001998 case FIREWALL_CHAIN_POWERSAVE:
1999 return FIREWALL_TYPE_WHITELIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002000 default:
2001 return isFirewallEnabled() ? FIREWALL_TYPE_WHITELIST : FIREWALL_TYPE_BLACKLIST;
2002 }
2003 }
2004
2005 @Override
2006 public void setFirewallUidRules(int chain, int[] uids, int[] rules) {
2007 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002008 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002009 synchronized (mRulesLock) {
2010 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
2011 SparseIntArray newRules = new SparseIntArray();
2012 // apply new set of rules
2013 for (int index = uids.length - 1; index >= 0; --index) {
2014 int uid = uids[index];
2015 int rule = rules[index];
2016 updateFirewallUidRuleLocked(chain, uid, rule);
2017 newRules.put(uid, rule);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002018 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002019 // collect the rules to remove.
2020 SparseIntArray rulesToRemove = new SparseIntArray();
2021 for (int index = uidFirewallRules.size() - 1; index >= 0; --index) {
2022 int uid = uidFirewallRules.keyAt(index);
2023 if (newRules.indexOfKey(uid) < 0) {
2024 rulesToRemove.put(uid, FIREWALL_RULE_DEFAULT);
2025 }
2026 }
2027 // remove dead rules
2028 for (int index = rulesToRemove.size() - 1; index >= 0; --index) {
2029 int uid = rulesToRemove.keyAt(index);
2030 updateFirewallUidRuleLocked(chain, uid, FIREWALL_RULE_DEFAULT);
2031 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002032 }
2033 try {
2034 switch (chain) {
2035 case FIREWALL_CHAIN_DOZABLE:
2036 mNetdService.firewallReplaceUidChain("fw_dozable", true, uids);
2037 break;
2038 case FIREWALL_CHAIN_STANDBY:
2039 mNetdService.firewallReplaceUidChain("fw_standby", false, uids);
2040 break;
2041 case FIREWALL_CHAIN_POWERSAVE:
2042 mNetdService.firewallReplaceUidChain("fw_powersave", true, uids);
2043 break;
2044 case FIREWALL_CHAIN_NONE:
2045 default:
2046 Slog.d(TAG, "setFirewallUidRules() called on invalid chain: " + chain);
2047 }
2048 } catch (RemoteException e) {
2049 Slog.w(TAG, "Error flushing firewall chain " + chain, e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002050 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002051 }
2052 }
2053
2054 @Override
2055 public void setFirewallUidRule(int chain, int uid, int rule) {
2056 enforceSystemUid();
Felipe Lemea701cad2016-05-12 09:58:14 -07002057 synchronized (mQuotaLock) {
2058 setFirewallUidRuleLocked(chain, uid, rule);
2059 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002060 }
2061
Felipe Lemea701cad2016-05-12 09:58:14 -07002062 private void setFirewallUidRuleLocked(int chain, int uid, int rule) {
2063 if (updateFirewallUidRuleLocked(chain, uid, rule)) {
Luke Huanga241db92018-07-31 20:15:24 +08002064 final int ruleType = getFirewallRuleType(chain, rule);
Amith Yamasani15e472352015-04-24 19:06:07 -07002065 try {
Luke Huanga241db92018-07-31 20:15:24 +08002066 mNetdService.firewallSetUidRule(chain, uid, ruleType);
2067 } catch (RemoteException | ServiceSpecificException e) {
2068 throw new IllegalStateException(e);
Amith Yamasani15e472352015-04-24 19:06:07 -07002069 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002070 }
2071 }
2072
Felipe Lemea701cad2016-05-12 09:58:14 -07002073 // TODO: now that netd supports batching, NMS should not keep these data structures anymore...
2074 private boolean updateFirewallUidRuleLocked(int chain, int uid, int rule) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002075 synchronized (mRulesLock) {
2076 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Felipe Lemea701cad2016-05-12 09:58:14 -07002077
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002078 final int oldUidFirewallRule = uidFirewallRules.get(uid, FIREWALL_RULE_DEFAULT);
2079 if (DBG) {
2080 Slog.d(TAG, "oldRule = " + oldUidFirewallRule
2081 + ", newRule=" + rule + " for uid=" + uid + " on chain " + chain);
2082 }
2083 if (oldUidFirewallRule == rule) {
2084 if (DBG) Slog.d(TAG, "!!!!! Skipping change");
2085 // TODO: eventually consider throwing
2086 return false;
2087 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002088
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002089 String ruleName = getFirewallRuleName(chain, rule);
2090 String oldRuleName = getFirewallRuleName(chain, oldUidFirewallRule);
Felipe Lemea701cad2016-05-12 09:58:14 -07002091
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002092 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
2093 uidFirewallRules.delete(uid);
2094 } else {
2095 uidFirewallRules.put(uid, rule);
2096 }
2097 return !ruleName.equals(oldRuleName);
Felipe Lemea701cad2016-05-12 09:58:14 -07002098 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002099 }
2100
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002101 private @NonNull String getFirewallRuleName(int chain, int rule) {
2102 String ruleName;
2103 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
2104 if (rule == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
2105 ruleName = "allow";
2106 } else {
2107 ruleName = "deny";
2108 }
2109 } else { // Blacklist mode
2110 if (rule == NetworkPolicyManager.FIREWALL_RULE_DENY) {
2111 ruleName = "deny";
2112 } else {
2113 ruleName = "allow";
2114 }
2115 }
2116 return ruleName;
2117 }
2118
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002119 private @NonNull SparseIntArray getUidFirewallRulesLR(int chain) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002120 switch (chain) {
2121 case FIREWALL_CHAIN_STANDBY:
2122 return mUidFirewallStandbyRules;
2123 case FIREWALL_CHAIN_DOZABLE:
2124 return mUidFirewallDozableRules;
Felipe Leme011b98f2016-02-10 17:28:31 -08002125 case FIREWALL_CHAIN_POWERSAVE:
2126 return mUidFirewallPowerSaveRules;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002127 case FIREWALL_CHAIN_NONE:
2128 return mUidFirewallRules;
2129 default:
2130 throw new IllegalArgumentException("Unknown chain:" + chain);
2131 }
2132 }
2133
Luke Huanga241db92018-07-31 20:15:24 +08002134 private int getFirewallRuleType(int chain, int rule) {
Luke Huang615e1022018-10-25 11:54:05 +09002135 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
2136 return getFirewallType(chain) == FIREWALL_TYPE_WHITELIST
2137 ? INetd.FIREWALL_RULE_DENY : INetd.FIREWALL_RULE_ALLOW;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002138 }
Luke Huang615e1022018-10-25 11:54:05 +09002139 return rule;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002140 }
2141
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07002142 private static void enforceSystemUid() {
2143 final int uid = Binder.getCallingUid();
2144 if (uid != Process.SYSTEM_UID) {
2145 throw new SecurityException("Only available to AID_SYSTEM");
2146 }
2147 }
2148
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002149 @Override
Lorenzo Colitti79751842013-02-28 16:16:03 +09002150 public void startClatd(String interfaceName) throws IllegalStateException {
2151 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2152
2153 try {
Luke Huang69369f32018-08-02 15:51:41 +08002154 mNetdService.clatdStart(interfaceName);
2155 } catch (RemoteException | ServiceSpecificException e) {
2156 throw new IllegalStateException(e);
Lorenzo Colitti79751842013-02-28 16:16:03 +09002157 }
2158 }
2159
2160 @Override
Lorenzo Colitti95439462014-10-09 13:44:48 +09002161 public void stopClatd(String interfaceName) throws IllegalStateException {
Lorenzo Colitti79751842013-02-28 16:16:03 +09002162 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2163
2164 try {
Luke Huang69369f32018-08-02 15:51:41 +08002165 mNetdService.clatdStop(interfaceName);
2166 } catch (RemoteException | ServiceSpecificException e) {
2167 throw new IllegalStateException(e);
Lorenzo Colitti79751842013-02-28 16:16:03 +09002168 }
2169 }
2170
2171 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002172 public void registerNetworkActivityListener(INetworkActivityListener listener) {
2173 mNetworkActivityListeners.register(listener);
2174 }
2175
2176 @Override
2177 public void unregisterNetworkActivityListener(INetworkActivityListener listener) {
2178 mNetworkActivityListeners.unregister(listener);
2179 }
2180
2181 @Override
2182 public boolean isNetworkActive() {
2183 synchronized (mNetworkActivityListeners) {
2184 return mNetworkActive || mActiveIdleTimers.isEmpty();
2185 }
2186 }
2187
2188 private void reportNetworkActive() {
2189 final int length = mNetworkActivityListeners.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002190 try {
2191 for (int i = 0; i < length; i++) {
2192 try {
2193 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
Felipe Leme03e689d2016-03-02 16:17:38 -08002194 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002195 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002196 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002197 } finally {
2198 mNetworkActivityListeners.finishBroadcast();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002199 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002200 }
2201
Mattias Falk8b47b362011-08-23 14:15:13 +02002202 /** {@inheritDoc} */
Jeff Sharkey7b4596f2013-02-25 10:55:29 -08002203 @Override
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002204 public void monitor() {
2205 if (mConnector != null) {
2206 mConnector.monitor();
2207 }
2208 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002209
2210 @Override
2211 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002212 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002213
Robert Greenwalt470fd722012-01-18 12:51:15 -08002214 pw.println("NetworkManagementService NativeDaemonConnector Log:");
2215 mConnector.dump(fd, pw, args);
2216 pw.println();
2217
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07002218 pw.print("mMobileActivityFromRadio="); pw.print(mMobileActivityFromRadio);
2219 pw.print(" mLastPowerStateFromRadio="); pw.println(mLastPowerStateFromRadio);
2220 pw.print("mNetworkActive="); pw.println(mNetworkActive);
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002221
2222 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07002223 pw.print("Active quota ifaces: "); pw.println(mActiveQuotas.toString());
2224 pw.print("Active alert ifaces: "); pw.println(mActiveAlerts.toString());
Felipe Leme65be3022016-03-22 14:53:13 -07002225 pw.print("Data saver mode: "); pw.println(mDataSaverMode);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002226 synchronized (mRulesLock) {
2227 dumpUidRuleOnQuotaLocked(pw, "blacklist", mUidRejectOnMetered);
2228 dumpUidRuleOnQuotaLocked(pw, "whitelist", mUidAllowOnMetered);
2229 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002230 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002231
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002232 synchronized (mRulesLock) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002233 dumpUidFirewallRule(pw, "", mUidFirewallRules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002234
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002235 pw.print("UID firewall standby chain enabled: "); pw.println(
2236 getFirewallChainState(FIREWALL_CHAIN_STANDBY));
Felipe Leme011b98f2016-02-10 17:28:31 -08002237 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_STANDBY, mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002238
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002239 pw.print("UID firewall dozable chain enabled: "); pw.println(
2240 getFirewallChainState(FIREWALL_CHAIN_DOZABLE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002241 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_DOZABLE, mUidFirewallDozableRules);
Felipe Leme011b98f2016-02-10 17:28:31 -08002242
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002243 pw.println("UID firewall powersave chain enabled: " +
2244 getFirewallChainState(FIREWALL_CHAIN_POWERSAVE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002245 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_POWERSAVE, mUidFirewallPowerSaveRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002246 }
2247
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002248 synchronized (mIdleTimerLock) {
2249 pw.println("Idle timers:");
2250 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
2251 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
2252 IdleTimerParams params = ent.getValue();
2253 pw.print(" timeout="); pw.print(params.timeout);
2254 pw.print(" type="); pw.print(params.type);
2255 pw.print(" networkCount="); pw.println(params.networkCount);
2256 }
2257 }
2258
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002259 pw.print("Firewall enabled: "); pw.println(mFirewallEnabled);
Felipe Leme65be3022016-03-22 14:53:13 -07002260 pw.print("Netd service status: " );
2261 if (mNetdService == null) {
2262 pw.println("disconnected");
2263 } else {
2264 try {
2265 final boolean alive = mNetdService.isAlive();
2266 pw.println(alive ? "alive": "dead");
2267 } catch (RemoteException e) {
2268 pw.println("unreachable");
2269 }
2270 }
2271 }
2272
2273 private void dumpUidRuleOnQuotaLocked(PrintWriter pw, String name, SparseBooleanArray list) {
2274 pw.print("UID bandwith control ");
2275 pw.print(name);
2276 pw.print(" rule: [");
2277 final int size = list.size();
2278 for (int i = 0; i < size; i++) {
2279 pw.print(list.keyAt(i));
2280 if (i < size - 1) pw.print(",");
2281 }
2282 pw.println("]");
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002283 }
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002284
Felipe Leme011b98f2016-02-10 17:28:31 -08002285 private void dumpUidFirewallRule(PrintWriter pw, String name, SparseIntArray rules) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002286 pw.print("UID firewall ");
Felipe Leme011b98f2016-02-10 17:28:31 -08002287 pw.print(name);
2288 pw.print(" rule: [");
2289 final int size = rules.size();
2290 for (int i = 0; i < size; i++) {
2291 pw.print(rules.keyAt(i));
2292 pw.print(":");
2293 pw.print(rules.valueAt(i));
2294 if (i < size - 1) pw.print(",");
2295 }
2296 pw.println("]");
2297 }
2298
Robert Greenwalt568891d2014-04-04 13:38:00 -07002299 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002300 public void createPhysicalNetwork(int netId, int permission) {
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002301 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2302
2303 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002304 mNetdService.networkCreatePhysical(netId, permission);
2305 } catch (RemoteException | ServiceSpecificException e) {
2306 throw new IllegalStateException(e);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002307 }
2308 }
2309
Robert Greenwalt568891d2014-04-04 13:38:00 -07002310 @Override
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07002311 public void createVirtualNetwork(int netId, boolean hasDNS, boolean secure) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002312 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2313
2314 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002315 mNetdService.networkCreateVpn(netId, hasDNS, secure);
2316 } catch (RemoteException | ServiceSpecificException e) {
2317 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002318 }
2319 }
2320
2321 @Override
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002322 public void removeNetwork(int netId) {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002323 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002324
2325 try {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002326 mNetdService.networkDestroy(netId);
2327 } catch (ServiceSpecificException e) {
2328 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2329 throw e;
2330 } catch (RemoteException e) {
2331 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2332 throw e.rethrowAsRuntimeException();
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002333 }
2334 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002335
2336 @Override
Paul Jensen992f2522014-04-28 10:33:11 -04002337 public void addInterfaceToNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002338 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, netId, iface);
Paul Jensen992f2522014-04-28 10:33:11 -04002339 }
2340
2341 @Override
2342 public void removeInterfaceFromNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002343 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, netId, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002344 }
Paul Jensen992f2522014-04-28 10:33:11 -04002345
Luke Huang8a462ec2018-08-24 20:33:16 +08002346 private void modifyInterfaceInNetwork(boolean add, int netId, String iface) {
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002347 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Paul Jensen992f2522014-04-28 10:33:11 -04002348 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002349 if (add) {
2350 mNetdService.networkAddInterface(netId, iface);
2351 } else {
2352 mNetdService.networkRemoveInterface(netId, iface);
2353 }
2354 } catch (RemoteException | ServiceSpecificException e) {
2355 throw new IllegalStateException(e);
Paul Jensen992f2522014-04-28 10:33:11 -04002356 }
2357 }
2358
2359 @Override
Robert Greenwalt913c8952014-04-07 17:36:35 -07002360 public void addLegacyRouteForNetId(int netId, RouteInfo routeInfo, int uid) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002361 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2362
Sreeram Ramachandrancc91c7b2014-06-03 18:41:43 -07002363 final LinkAddress la = routeInfo.getDestinationLinkAddress();
Luke Huang8a462ec2018-08-24 20:33:16 +08002364 final String ifName = routeInfo.getInterface();
2365 final String dst = la.toString();
2366 final String nextHop;
Robert Greenwalt568891d2014-04-04 13:38:00 -07002367
Luke Huang8a462ec2018-08-24 20:33:16 +08002368 if (routeInfo.hasGateway()) {
2369 nextHop = routeInfo.getGateway().getHostAddress();
2370 } else {
2371 nextHop = "";
2372 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002373 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002374 mNetdService.networkAddLegacyRoute(netId, ifName, dst, nextHop, uid);
2375 } catch (RemoteException | ServiceSpecificException e) {
2376 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002377 }
2378 }
2379
2380 @Override
Sreeram Ramachandranf047f2a2014-04-15 16:04:26 -07002381 public void setDefaultNetId(int netId) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002382 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2383
2384 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002385 mNetdService.networkSetDefault(netId);
2386 } catch (RemoteException | ServiceSpecificException e) {
2387 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002388 }
2389 }
2390
2391 @Override
2392 public void clearDefaultNetId() {
2393 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2394
2395 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002396 mNetdService.networkClearDefault();
2397 } catch (RemoteException | ServiceSpecificException e) {
2398 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002399 }
2400 }
2401
2402 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002403 public void setNetworkPermission(int netId, int permission) {
Paul Jensen487ffe72015-07-24 15:57:11 -04002404 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2405
2406 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002407 mNetdService.networkSetPermissionForNetwork(netId, permission);
2408 } catch (RemoteException | ServiceSpecificException e) {
2409 throw new IllegalStateException(e);
Paul Jensen487ffe72015-07-24 15:57:11 -04002410 }
2411 }
2412
Luke Huang8a462ec2018-08-24 20:33:16 +08002413 private int parsePermission(String permission) {
2414 if (permission.equals("NETWORK")) {
2415 return INetd.PERMISSION_NETWORK;
2416 }
2417 if (permission.equals("SYSTEM")) {
2418 return INetd.PERMISSION_SYSTEM;
2419 }
2420 return INetd.PERMISSION_NONE;
2421 }
Paul Jensen487ffe72015-07-24 15:57:11 -04002422
2423 @Override
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002424 public void setPermission(String permission, int[] uids) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002425 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2426
Luke Huang8a462ec2018-08-24 20:33:16 +08002427 try {
2428 mNetdService.networkSetPermissionForUser(parsePermission(permission), uids);
2429 } catch (RemoteException | ServiceSpecificException e) {
2430 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002431 }
2432 }
2433
2434 @Override
2435 public void clearPermission(int[] uids) {
2436 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2437
Luke Huang8a462ec2018-08-24 20:33:16 +08002438 try {
2439 mNetdService.networkClearPermissionForUser(uids);
2440 } catch (RemoteException | ServiceSpecificException e) {
2441 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002442 }
2443 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002444
2445 @Override
2446 public void allowProtect(int uid) {
2447 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2448
2449 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002450 mNetdService.networkSetProtectAllow(uid);
2451 } catch (RemoteException | ServiceSpecificException e) {
2452 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002453 }
2454 }
2455
2456 @Override
2457 public void denyProtect(int uid) {
2458 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2459
2460 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002461 mNetdService.networkSetProtectDeny(uid);
2462 } catch (RemoteException | ServiceSpecificException e) {
2463 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002464 }
2465 }
2466
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002467 @Override
2468 public void addInterfaceToLocalNetwork(String iface, List<RouteInfo> routes) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002469 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002470
2471 for (RouteInfo route : routes) {
2472 if (!route.isDefaultRoute()) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002473 modifyRoute(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID, route);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002474 }
2475 }
2476 }
2477
2478 @Override
2479 public void removeInterfaceFromLocalNetwork(String iface) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002480 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, INetd.LOCAL_NET_ID, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002481 }
Erik Kline6599ee82016-07-17 21:28:39 +09002482
2483 @Override
2484 public int removeRoutesFromLocalNetwork(List<RouteInfo> routes) {
2485 int failures = 0;
2486
2487 for (RouteInfo route : routes) {
2488 try {
Luke Huang706d7ab2018-10-16 15:42:15 +08002489 modifyRoute(MODIFY_OPERATION_REMOVE, INetd.LOCAL_NET_ID, route);
Erik Kline6599ee82016-07-17 21:28:39 +09002490 } catch (IllegalStateException e) {
2491 failures++;
2492 }
2493 }
2494
2495 return failures;
2496 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002497
Sudheer Shankab8f23162017-08-04 13:30:10 -07002498 @Override
2499 public boolean isNetworkRestricted(int uid) {
2500 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2501 return isNetworkRestrictedInternal(uid);
2502 }
2503
2504 private boolean isNetworkRestrictedInternal(int uid) {
2505 synchronized (mRulesLock) {
2506 if (getFirewallChainState(FIREWALL_CHAIN_STANDBY)
2507 && mUidFirewallStandbyRules.get(uid) == FIREWALL_RULE_DENY) {
2508 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of app standby mode");
2509 return true;
2510 }
2511 if (getFirewallChainState(FIREWALL_CHAIN_DOZABLE)
2512 && mUidFirewallDozableRules.get(uid) != FIREWALL_RULE_ALLOW) {
2513 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of device idle mode");
2514 return true;
2515 }
2516 if (getFirewallChainState(FIREWALL_CHAIN_POWERSAVE)
2517 && mUidFirewallPowerSaveRules.get(uid) != FIREWALL_RULE_ALLOW) {
2518 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of power saver mode");
2519 return true;
2520 }
2521 if (mUidRejectOnMetered.get(uid)) {
2522 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of no metered data"
2523 + " in the background");
2524 return true;
2525 }
2526 if (mDataSaverMode && !mUidAllowOnMetered.get(uid)) {
2527 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of data saver mode");
2528 return true;
2529 }
2530 return false;
2531 }
2532 }
2533
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002534 private void setFirewallChainState(int chain, boolean state) {
2535 synchronized (mRulesLock) {
2536 mFirewallChainStates.put(chain, state);
2537 }
2538 }
2539
2540 private boolean getFirewallChainState(int chain) {
2541 synchronized (mRulesLock) {
2542 return mFirewallChainStates.get(chain);
2543 }
2544 }
2545
2546 @VisibleForTesting
2547 class LocalService extends NetworkManagementInternal {
2548 @Override
2549 public boolean isNetworkRestrictedForUid(int uid) {
Sudheer Shankab8f23162017-08-04 13:30:10 -07002550 return isNetworkRestrictedInternal(uid);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002551 }
2552 }
2553
2554 @VisibleForTesting
2555 Injector getInjector() {
2556 return new Injector();
2557 }
2558
2559 @VisibleForTesting
2560 class Injector {
2561 void setDataSaverMode(boolean dataSaverMode) {
2562 mDataSaverMode = dataSaverMode;
2563 }
2564
2565 void setFirewallChainState(int chain, boolean state) {
2566 NetworkManagementService.this.setFirewallChainState(chain, state);
2567 }
2568
2569 void setFirewallRule(int chain, int uid, int rule) {
2570 synchronized (mRulesLock) {
2571 getUidFirewallRulesLR(chain).put(uid, rule);
2572 }
2573 }
2574
2575 void setUidOnMeteredNetworkList(boolean blacklist, int uid, boolean enable) {
2576 synchronized (mRulesLock) {
2577 if (blacklist) {
2578 mUidRejectOnMetered.put(uid, enable);
2579 } else {
2580 mUidAllowOnMetered.put(uid, enable);
2581 }
2582 }
2583 }
2584
2585 void reset() {
2586 synchronized (mRulesLock) {
2587 setDataSaverMode(false);
2588 final int[] chains = {
2589 FIREWALL_CHAIN_DOZABLE,
2590 FIREWALL_CHAIN_STANDBY,
2591 FIREWALL_CHAIN_POWERSAVE
2592 };
2593 for (int chain : chains) {
2594 setFirewallChainState(chain, false);
2595 getUidFirewallRulesLR(chain).clear();
2596 }
2597 mUidAllowOnMetered.clear();
2598 mUidRejectOnMetered.clear();
2599 }
2600 }
2601 }
San Mehat873f2142010-01-14 10:25:07 -08002602}