blob: 385ef7f2a81c1ee3c17a6b45fcd5d2a9e23d0e2c [file] [log] [blame]
San Mehat873f2142010-01-14 10:25:07 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey4529bb62011-12-14 10:31:54 -080019import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey47eb1022011-08-25 17:48:52 -070020import static android.Manifest.permission.DUMP;
Sehee Parka9139bc2017-12-22 13:54:05 +090021import static android.Manifest.permission.NETWORK_SETTINGS;
Lorenzo Colitti07f13042017-07-10 19:06:57 +090022import static android.Manifest.permission.NETWORK_STACK;
Jeff Sharkeyaf75c332011-11-18 12:41:12 -080023import static android.Manifest.permission.SHUTDOWN;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070024import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
25import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_DOZABLE;
26import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_NONE;
Felipe Leme011b98f2016-02-10 17:28:31 -080027import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070028import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_STANDBY;
29import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NONE;
Felipe Leme011b98f2016-02-10 17:28:31 -080030import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070031import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
Sudheer Shanka62f5c172017-03-17 16:25:55 -070032import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070033import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Sudheer Shanka62f5c172017-03-17 16:25:55 -070034import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070035import static android.net.NetworkPolicyManager.FIREWALL_TYPE_BLACKLIST;
36import static android.net.NetworkPolicyManager.FIREWALL_TYPE_WHITELIST;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -070037import static android.net.NetworkStats.SET_DEFAULT;
Lorenzo Colittif1912ca2017-08-17 19:23:08 +090038import static android.net.NetworkStats.STATS_PER_UID;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080039import static android.net.NetworkStats.TAG_ALL;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070040import static android.net.NetworkStats.TAG_NONE;
41import static android.net.NetworkStats.UID_ALL;
Jeff Sharkeyae2c1812011-10-04 13:11:40 -070042import static android.net.TrafficStats.UID_TETHERING;
Lorenzo Colitti79751842013-02-28 16:16:03 +090043import static com.android.server.NetworkManagementService.NetdResponseCode.ClatdStatusResult;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -080044import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceGetCfgResult;
45import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceListResult;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -080046import static com.android.server.NetworkManagementService.NetdResponseCode.IpFwdStatusResult;
47import static com.android.server.NetworkManagementService.NetdResponseCode.TetherDnsFwdTgtListResult;
48import static com.android.server.NetworkManagementService.NetdResponseCode.TetherInterfaceListResult;
49import static com.android.server.NetworkManagementService.NetdResponseCode.TetherStatusResult;
Jeff Sharkeye4984be2013-09-10 21:03:27 -070050import static com.android.server.NetworkManagementService.NetdResponseCode.TetheringStatsListResult;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -080051import static com.android.server.NetworkManagementService.NetdResponseCode.TtyListResult;
Jeff Sharkeya63ba592011-07-19 23:47:12 -070052import static com.android.server.NetworkManagementSocketTagger.PROP_QTAGUID_ENABLED;
Erik Klineb2cfdfb2017-01-18 20:54:14 +090053
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070054import android.annotation.NonNull;
Sudheer Shankadc589ac2016-11-10 15:30:17 -080055import android.app.ActivityManager;
Pierre Imai8e48e672016-04-21 13:30:43 +090056import android.content.ContentResolver;
San Mehat873f2142010-01-14 10:25:07 -080057import android.content.Context;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080058import android.net.ConnectivityManager;
Lorenzo Colitti58967ba2016-02-02 17:21:21 +090059import android.net.INetd;
Luke Huang13b79e82018-09-26 14:53:42 +080060import android.net.TetherStatsParcel;
San Mehat4d02d002010-01-22 16:07:46 -080061import android.net.INetworkManagementEventObserver;
Lorenzo Colitti07f13042017-07-10 19:06:57 +090062import android.net.ITetheringStatsProvider;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070063import android.net.InterfaceConfiguration;
Luke Huang14f75442018-08-15 19:22:54 +080064import android.net.InterfaceConfigurationParcel;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +090065import android.net.IpPrefix;
Robert Greenwalted126402011-01-28 15:34:55 -080066import android.net.LinkAddress;
Lorenzo Colittib57edc52014-08-22 17:10:50 -070067import android.net.Network;
Amith Yamasani15e472352015-04-24 19:06:07 -070068import android.net.NetworkPolicyManager;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070069import android.net.NetworkStats;
Robert Greenwalted126402011-01-28 15:34:55 -080070import android.net.NetworkUtils;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070071import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040072import android.net.UidRange;
Luke Huang77017912018-10-19 15:57:05 +090073import android.net.UidRangeParcel;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +090074import android.net.util.NetdService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080075import android.net.wifi.WifiConfiguration;
76import android.net.wifi.WifiConfiguration.KeyMgmt;
Dianne Hackborn91268cf2013-06-13 19:06:50 -070077import android.os.BatteryStats;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070078import android.os.Binder;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -070079import android.os.Handler;
Lorenzo Colittia0868002017-07-11 02:29:28 +090080import android.os.IBinder;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080081import android.os.INetworkActivityListener;
San Mehat873f2142010-01-14 10:25:07 -080082import android.os.INetworkManagementService;
Lorenzo Colitti563dc452017-09-01 17:12:34 +090083import android.os.PersistableBundle;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080084import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070085import android.os.Process;
Jeff Sharkey3df273e2011-12-15 15:47:12 -080086import android.os.RemoteCallbackList;
87import android.os.RemoteException;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070088import android.os.ServiceManager;
Lorenzo Colitti4cb42402016-04-24 12:52:00 +090089import android.os.ServiceSpecificException;
Jeff Sharkey605eb792014-11-04 13:34:06 -080090import android.os.StrictMode;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070091import android.os.SystemClock;
Marco Nelissen62dbb222010-02-18 10:56:30 -080092import android.os.SystemProperties;
Felipe Leme29e72ea2016-09-08 13:26:55 -070093import android.os.Trace;
Pierre Imai8e48e672016-04-21 13:30:43 +090094import android.provider.Settings;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070095import android.telephony.DataConnectionRealTimeInfo;
96import android.telephony.PhoneStateListener;
Wink Savillefb40dd42014-06-12 17:02:31 -070097import android.telephony.SubscriptionManager;
Wink Saville67e07892014-06-18 16:43:14 -070098import android.telephony.TelephonyManager;
Erik Kline4d092232017-10-30 15:29:44 +090099import android.text.TextUtils;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800100import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800101import android.util.Slog;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700102import android.util.SparseBooleanArray;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800103import android.util.SparseIntArray;
San Mehat873f2142010-01-14 10:25:07 -0800104
Jeff Sharkey605eb792014-11-04 13:34:06 -0800105import com.android.internal.annotations.GuardedBy;
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700106import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700107import com.android.internal.app.IBatteryStats;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700108import com.android.internal.net.NetworkStatsFactory;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600109import com.android.internal.util.DumpUtils;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800110import com.android.internal.util.HexDump;
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700111import com.android.internal.util.Preconditions;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800112import com.android.server.NativeDaemonConnector.Command;
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700113import com.android.server.NativeDaemonConnector.SensitiveArg;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700114import com.google.android.collect.Maps;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700115
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700116import java.io.BufferedReader;
117import java.io.DataInputStream;
San Mehat873f2142010-01-14 10:25:07 -0800118import java.io.File;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700119import java.io.FileDescriptor;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700120import java.io.FileInputStream;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700121import java.io.IOException;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700122import java.io.InputStreamReader;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700123import java.io.PrintWriter;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700124import java.net.InetAddress;
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700125import java.net.InterfaceAddress;
126import java.net.NetworkInterface;
127import java.net.SocketException;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700128import java.util.ArrayList;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400129import java.util.Arrays;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700130import java.util.HashMap;
jiaguo1da35f72014-01-09 16:39:59 +0800131import java.util.List;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700132import java.util.Map;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700133import java.util.NoSuchElementException;
134import java.util.StringTokenizer;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700135import java.util.concurrent.CountDownLatch;
San Mehat873f2142010-01-14 10:25:07 -0800136
137/**
138 * @hide
139 */
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700140public class NetworkManagementService extends INetworkManagementService.Stub
141 implements Watchdog.Monitor {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900142
143 /**
144 * Helper class that encapsulates NetworkManagementService dependencies and makes them
145 * easier to mock in unit tests.
146 */
147 static class SystemServices {
148 public IBinder getService(String name) {
149 return ServiceManager.getService(name);
150 }
151 public void registerLocalService(NetworkManagementInternal nmi) {
152 LocalServices.addService(NetworkManagementInternal.class, nmi);
153 }
154 public INetd getNetd() {
155 return NetdService.get();
156 }
157 }
158
Amith Yamasani15e472352015-04-24 19:06:07 -0700159 private static final String TAG = "NetworkManagement";
160 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Kenny Root305bcbf2010-09-03 07:56:38 -0700161 private static final String NETD_TAG = "NetdConnector";
Lorenzo Colittia0868002017-07-11 02:29:28 +0900162 static final String NETD_SERVICE_NAME = "netd";
Kenny Root305bcbf2010-09-03 07:56:38 -0700163
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400164 private static final int MAX_UID_RANGES_PER_COMMAND = 10;
165
Luke Huang4a32bf42018-08-21 19:09:45 +0800166 private static final String[] EMPTY_STRING_ARRAY = new String[0];
167
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700168 /**
169 * Name representing {@link #setGlobalAlert(long)} limit when delivered to
170 * {@link INetworkManagementEventObserver#limitReached(String, String)}.
171 */
172 public static final String LIMIT_GLOBAL_ALERT = "globalAlert";
173
Andrew Scull45f533c2017-05-19 15:37:20 +0100174 static class NetdResponseCode {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -0700175 /* Keep in sync with system/netd/server/ResponseCode.h */
San Mehat873f2142010-01-14 10:25:07 -0800176 public static final int InterfaceListResult = 110;
177 public static final int TetherInterfaceListResult = 111;
178 public static final int TetherDnsFwdTgtListResult = 112;
San Mehat72759df2010-01-19 13:50:37 -0800179 public static final int TtyListResult = 113;
Jeff Sharkeye4984be2013-09-10 21:03:27 -0700180 public static final int TetheringStatsListResult = 114;
San Mehat873f2142010-01-14 10:25:07 -0800181
182 public static final int TetherStatusResult = 210;
183 public static final int IpFwdStatusResult = 211;
San Mehated4fc8a2010-01-22 12:28:36 -0800184 public static final int InterfaceGetCfgResult = 213;
Robert Greenwalte3253922010-02-18 09:23:25 -0800185 public static final int SoftapStatusResult = 214;
San Mehat91cac642010-03-31 14:31:36 -0700186 public static final int InterfaceRxCounterResult = 216;
187 public static final int InterfaceTxCounterResult = 217;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700188 public static final int QuotaCounterResult = 220;
189 public static final int TetheringStatsResult = 221;
Selim Gurun84c00c62012-02-27 15:42:38 -0800190 public static final int DnsProxyQueryResult = 222;
Lorenzo Colitti79751842013-02-28 16:16:03 +0900191 public static final int ClatdStatusResult = 223;
Robert Greenwalte3253922010-02-18 09:23:25 -0800192
193 public static final int InterfaceChange = 600;
JP Abgrall12b933d2011-07-14 18:09:22 -0700194 public static final int BandwidthControl = 601;
Haoyu Bai6b7358d2012-07-17 16:36:50 -0700195 public static final int InterfaceClassActivity = 613;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900196 public static final int InterfaceAddressChange = 614;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900197 public static final int InterfaceDnsServerInfo = 615;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900198 public static final int RouteChange = 616;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800199 public static final int StrictCleartext = 617;
San Mehat873f2142010-01-14 10:25:07 -0800200 }
201
Rebecca Silbersteine2ec94f2016-03-24 13:29:00 -0700202 /**
203 * String indicating a softap command.
204 */
205 static final String SOFT_AP_COMMAND = "softap";
206
207 /**
208 * String passed back to netd connector indicating softap command success.
209 */
210 static final String SOFT_AP_COMMAND_SUCCESS = "Ok";
211
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700212 static final int DAEMON_MSG_MOBILE_CONN_REAL_TIME_INFO = 1;
213
Luke Huang8a462ec2018-08-24 20:33:16 +0800214 static final boolean MODIFY_OPERATION_ADD = true;
215 static final boolean MODIFY_OPERATION_REMOVE = false;
216
San Mehat873f2142010-01-14 10:25:07 -0800217 /**
218 * Binder context for this service
219 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700220 private final Context mContext;
San Mehat873f2142010-01-14 10:25:07 -0800221
222 /**
223 * connector object for communicating with netd
224 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700225 private final NativeDaemonConnector mConnector;
San Mehat873f2142010-01-14 10:25:07 -0800226
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700227 private final Handler mFgHandler;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700228 private final Handler mDaemonHandler;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700229
Lorenzo Colittia0868002017-07-11 02:29:28 +0900230 private final SystemServices mServices;
231
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900232 private INetd mNetdService;
233
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800234 private IBatteryStats mBatteryStats;
235
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700236 private final Thread mThread;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700237 private CountDownLatch mConnectedSignal = new CountDownLatch(1);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700238
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800239 private final RemoteCallbackList<INetworkManagementEventObserver> mObservers =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700240 new RemoteCallbackList<>();
San Mehat4d02d002010-01-22 16:07:46 -0800241
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700242 private final NetworkStatsFactory mStatsFactory = new NetworkStatsFactory();
243
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900244 @GuardedBy("mTetheringStatsProviders")
245 private final HashMap<ITetheringStatsProvider, String>
246 mTetheringStatsProviders = Maps.newHashMap();
247
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700248 /**
249 * If both locks need to be held, then they should be obtained in the order:
250 * first {@link #mQuotaLock} and then {@link #mRulesLock}.
251 */
Andrew Scull45f533c2017-05-19 15:37:20 +0100252 private final Object mQuotaLock = new Object();
Andrew Scull519291f2017-05-23 13:11:03 +0100253 private final Object mRulesLock = new Object();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800254
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700255 /** Set of interfaces with active quotas. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800256 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700257 private HashMap<String, Long> mActiveQuotas = Maps.newHashMap();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700258 /** Set of interfaces with active alerts. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800259 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700260 private HashMap<String, Long> mActiveAlerts = Maps.newHashMap();
Felipe Leme65be3022016-03-22 14:53:13 -0700261 /** Set of UIDs blacklisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700262 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700263 private SparseBooleanArray mUidRejectOnMetered = new SparseBooleanArray();
264 /** Set of UIDs whitelisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700265 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700266 private SparseBooleanArray mUidAllowOnMetered = new SparseBooleanArray();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800267 /** Set of UIDs with cleartext penalties. */
268 @GuardedBy("mQuotaLock")
269 private SparseIntArray mUidCleartextPolicy = new SparseIntArray();
Amith Yamasani15e472352015-04-24 19:06:07 -0700270 /** Set of UIDs that are to be blocked/allowed by firewall controller. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700271 @GuardedBy("mRulesLock")
Amith Yamasani15e472352015-04-24 19:06:07 -0700272 private SparseIntArray mUidFirewallRules = new SparseIntArray();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700273 /**
274 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
275 * to application idles.
276 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700277 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700278 private SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
279 /**
280 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
281 * to device idles.
282 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700283 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700284 private SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800285 /**
286 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
287 * to device on power-save mode.
288 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700289 @GuardedBy("mRulesLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800290 private SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700291 /** Set of states for the child firewall chains. True if the chain is active. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700292 @GuardedBy("mRulesLock")
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700293 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700294
Felipe Leme65be3022016-03-22 14:53:13 -0700295 @GuardedBy("mQuotaLock")
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700296 private volatile boolean mDataSaverMode;
Felipe Leme65be3022016-03-22 14:53:13 -0700297
Andrew Scull45f533c2017-05-19 15:37:20 +0100298 private final Object mIdleTimerLock = new Object();
Haoyu Bai04124232012-06-28 15:26:19 -0700299 /** Set of interfaces with active idle timers. */
300 private static class IdleTimerParams {
301 public final int timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800302 public final int type;
Haoyu Bai04124232012-06-28 15:26:19 -0700303 public int networkCount;
304
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800305 IdleTimerParams(int timeout, int type) {
Haoyu Bai04124232012-06-28 15:26:19 -0700306 this.timeout = timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800307 this.type = type;
Haoyu Bai04124232012-06-28 15:26:19 -0700308 this.networkCount = 1;
309 }
310 }
311 private HashMap<String, IdleTimerParams> mActiveIdleTimers = Maps.newHashMap();
312
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700313 private volatile boolean mFirewallEnabled;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800314 private volatile boolean mStrictEnabled;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700315
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700316 private boolean mMobileActivityFromRadio = false;
317 private int mLastPowerStateFromRadio = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Adam Lesinskie08af192015-03-25 16:42:59 -0700318 private int mLastPowerStateFromWifi = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700319
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800320 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700321 new RemoteCallbackList<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800322 private boolean mNetworkActive;
323
San Mehat873f2142010-01-14 10:25:07 -0800324 /**
325 * Constructs a new NetworkManagementService instance
326 *
327 * @param context Binder context for this service
328 */
Lorenzo Colittia0868002017-07-11 02:29:28 +0900329 private NetworkManagementService(
330 Context context, String socket, SystemServices services) {
San Mehat873f2142010-01-14 10:25:07 -0800331 mContext = context;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900332 mServices = services;
San Mehat4d02d002010-01-22 16:07:46 -0800333
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700334 // make sure this is on the same looper as our NativeDaemonConnector for sync purposes
335 mFgHandler = new Handler(FgThread.get().getLooper());
336
Dianne Hackborn4590e522014-03-24 13:36:46 -0700337 // Don't need this wake lock, since we now have a time stamp for when
338 // the network actually went inactive. (It might be nice to still do this,
339 // but I don't want to do it through the power manager because that pollutes the
340 // battery stats history with pointless noise.)
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700341 //PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
Dianne Hackborn4590e522014-03-24 13:36:46 -0700342 PowerManager.WakeLock wl = null; //pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NETD_TAG);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800343
San Mehat873f2142010-01-14 10:25:07 -0800344 mConnector = new NativeDaemonConnector(
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700345 new NetdCallbackReceiver(), socket, 10, NETD_TAG, 160, wl,
346 FgThread.get().getLooper());
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700347 mThread = new Thread(mConnector, NETD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700348
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700349 mDaemonHandler = new Handler(FgThread.get().getLooper());
Wink Saville67e07892014-06-18 16:43:14 -0700350
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700351 // Add ourself to the Watchdog monitors.
352 Watchdog.getInstance().addMonitor(this);
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700353
Lorenzo Colittia0868002017-07-11 02:29:28 +0900354 mServices.registerLocalService(new LocalService());
Lorenzo Colitti8228eb32017-07-19 06:17:33 +0900355
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900356 synchronized (mTetheringStatsProviders) {
357 mTetheringStatsProviders.put(new NetdTetheringStatsProvider(), "netd");
358 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700359 }
360
361 @VisibleForTesting
362 NetworkManagementService() {
363 mConnector = null;
364 mContext = null;
365 mDaemonHandler = null;
366 mFgHandler = null;
367 mThread = null;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900368 mServices = null;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700369 }
370
Lorenzo Colittia0868002017-07-11 02:29:28 +0900371 static NetworkManagementService create(Context context, String socket, SystemServices services)
Felipe Leme03e689d2016-03-02 16:17:38 -0800372 throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900373 final NetworkManagementService service =
374 new NetworkManagementService(context, socket, services);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700375 final CountDownLatch connectedSignal = service.mConnectedSignal;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700376 if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
377 service.mThread.start();
378 if (DBG) Slog.d(TAG, "Awaiting socket connection");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700379 connectedSignal.await();
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700380 if (DBG) Slog.d(TAG, "Connected");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900381 if (DBG) Slog.d(TAG, "Connecting native netd service");
bohu07cc3bb2016-05-03 15:58:01 -0700382 service.connectNativeNetdService();
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900383 if (DBG) Slog.d(TAG, "Connected");
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700384 return service;
San Mehat873f2142010-01-14 10:25:07 -0800385 }
386
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900387 public static NetworkManagementService create(Context context) throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900388 return create(context, NETD_SERVICE_NAME, new SystemServices());
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900389 }
390
Jeff Sharkey350083e2011-06-29 10:45:16 -0700391 public void systemReady() {
Felipe Leme03e689d2016-03-02 16:17:38 -0800392 if (DBG) {
393 final long start = System.currentTimeMillis();
394 prepareNativeDaemon();
395 final long delta = System.currentTimeMillis() - start;
396 Slog.d(TAG, "Prepared in " + delta + "ms");
397 return;
398 } else {
399 prepareNativeDaemon();
400 }
Jeff Sharkey350083e2011-06-29 10:45:16 -0700401 }
402
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800403 private IBatteryStats getBatteryStats() {
404 synchronized (this) {
405 if (mBatteryStats != null) {
406 return mBatteryStats;
407 }
Lorenzo Colittia0868002017-07-11 02:29:28 +0900408 mBatteryStats =
409 IBatteryStats.Stub.asInterface(mServices.getService(BatteryStats.SERVICE_NAME));
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800410 return mBatteryStats;
411 }
412 }
413
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800414 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800415 public void registerObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800416 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800417 mObservers.register(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800418 }
419
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800420 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800421 public void unregisterObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800422 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800423 mObservers.unregister(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800424 }
425
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900426 @FunctionalInterface
427 private interface NetworkManagementEventCallback {
428 public void sendCallback(INetworkManagementEventObserver o) throws RemoteException;
429 }
430
431 private void invokeForAllObservers(NetworkManagementEventCallback eventCallback) {
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800432 final int length = mObservers.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700433 try {
434 for (int i = 0; i < length; i++) {
435 try {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900436 eventCallback.sendCallback(mObservers.getBroadcastItem(i));
Felipe Leme03e689d2016-03-02 16:17:38 -0800437 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700438 }
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700439 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700440 } finally {
441 mObservers.finishBroadcast();
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700442 }
443 }
444
445 /**
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900446 * Notify our observers of an interface status change
447 */
448 private void notifyInterfaceStatusChanged(String iface, boolean up) {
449 invokeForAllObservers(o -> o.interfaceStatusChanged(iface, up));
450 }
451
452 /**
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700453 * Notify our observers of an interface link state change
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700454 * (typically, an Ethernet cable has been plugged-in or unplugged).
455 */
456 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900457 invokeForAllObservers(o -> o.interfaceLinkStateChanged(iface, up));
San Mehat4d02d002010-01-22 16:07:46 -0800458 }
459
460 /**
461 * Notify our observers of an interface addition.
462 */
463 private void notifyInterfaceAdded(String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900464 invokeForAllObservers(o -> o.interfaceAdded(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800465 }
466
467 /**
468 * Notify our observers of an interface removal.
469 */
470 private void notifyInterfaceRemoved(String iface) {
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700471 // netd already clears out quota and alerts for removed ifaces; update
472 // our sanity-checking state.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700473 mActiveAlerts.remove(iface);
474 mActiveQuotas.remove(iface);
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700475
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900476 invokeForAllObservers(o -> o.interfaceRemoved(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800477 }
478
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700479 /**
JP Abgrall12b933d2011-07-14 18:09:22 -0700480 * Notify our observers of a limit reached.
481 */
482 private void notifyLimitReached(String limitName, String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900483 invokeForAllObservers(o -> o.limitReached(limitName, iface));
JP Abgrall12b933d2011-07-14 18:09:22 -0700484 }
485
486 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700487 * Notify our observers of a change in the data activity state of the interface
488 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700489 private void notifyInterfaceClassActivity(int type, int powerState, long tsNanos,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700490 int uid, boolean fromRadio) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700491 final boolean isMobile = ConnectivityManager.isNetworkTypeMobile(type);
492 if (isMobile) {
493 if (!fromRadio) {
494 if (mMobileActivityFromRadio) {
495 // If this call is not coming from a report from the radio itself, but we
496 // have previously received reports from the radio, then we will take the
497 // power state to just be whatever the radio last reported.
498 powerState = mLastPowerStateFromRadio;
499 }
500 } else {
501 mMobileActivityFromRadio = true;
502 }
503 if (mLastPowerStateFromRadio != powerState) {
504 mLastPowerStateFromRadio = powerState;
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700505 try {
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700506 getBatteryStats().noteMobileRadioPowerState(powerState, tsNanos, uid);
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700507 } catch (RemoteException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700508 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700509 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700510 }
511
Adam Lesinskie08af192015-03-25 16:42:59 -0700512 if (ConnectivityManager.isNetworkTypeWifi(type)) {
513 if (mLastPowerStateFromWifi != powerState) {
514 mLastPowerStateFromWifi = powerState;
515 try {
Adam Lesinski5f056f62016-07-14 16:56:08 -0700516 getBatteryStats().noteWifiRadioPowerState(powerState, tsNanos, uid);
Adam Lesinskie08af192015-03-25 16:42:59 -0700517 } catch (RemoteException e) {
518 }
519 }
520 }
521
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700522 boolean isActive = powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
523 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
524
525 if (!isMobile || fromRadio || !mMobileActivityFromRadio) {
526 // Report the change in data activity. We don't do this if this is a change
527 // on the mobile network, that is not coming from the radio itself, and we
528 // have previously seen change reports from the radio. In that case only
529 // the radio is the authority for the current state.
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900530 final boolean active = isActive;
531 invokeForAllObservers(o -> o.interfaceClassDataActivityChanged(
532 Integer.toString(type), active, tsNanos));
Haoyu Baidb3c8672012-06-20 14:29:57 -0700533 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800534
535 boolean report = false;
536 synchronized (mIdleTimerLock) {
537 if (mActiveIdleTimers.isEmpty()) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700538 // If there are no idle timers, we are not monitoring activity, so we
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800539 // are always considered active.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700540 isActive = true;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800541 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700542 if (mNetworkActive != isActive) {
543 mNetworkActive = isActive;
544 report = isActive;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800545 }
546 }
547 if (report) {
548 reportNetworkActive();
549 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700550 }
551
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900552 @Override
553 public void registerTetheringStatsProvider(ITetheringStatsProvider provider, String name) {
554 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
555 Preconditions.checkNotNull(provider);
556 synchronized(mTetheringStatsProviders) {
557 mTetheringStatsProviders.put(provider, name);
558 }
559 }
560
561 @Override
562 public void unregisterTetheringStatsProvider(ITetheringStatsProvider provider) {
563 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
564 synchronized(mTetheringStatsProviders) {
565 mTetheringStatsProviders.remove(provider);
566 }
567 }
568
Lorenzo Colitti9f0baa92017-08-15 19:25:51 +0900569 @Override
570 public void tetherLimitReached(ITetheringStatsProvider provider) {
571 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
572 synchronized(mTetheringStatsProviders) {
573 if (!mTetheringStatsProviders.containsKey(provider)) {
574 return;
575 }
576 // No current code examines the interface parameter in a global alert. Just pass null.
577 notifyLimitReached(LIMIT_GLOBAL_ALERT, null);
578 }
579 }
580
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900581 // Sync the state of the given chain with the native daemon.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700582 private void syncFirewallChainLocked(int chain, String name) {
583 SparseIntArray rules;
584 synchronized (mRulesLock) {
585 final SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900586 // Make a copy of the current rules, and then clear them. This is because
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700587 // setFirewallUidRuleInternal only pushes down rules to the native daemon if they
588 // are different from the current rules stored in the mUidFirewall*Rules array for
589 // the specified chain. If we don't clear the rules, setFirewallUidRuleInternal
590 // will do nothing.
591 rules = uidFirewallRules.clone();
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900592 uidFirewallRules.clear();
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700593 }
594 if (rules.size() > 0) {
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900595 // Now push the rules. setFirewallUidRuleInternal will push each of these down to the
596 // native daemon, and also add them to the mUidFirewall*Rules array for the specified
597 // chain.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700598 if (DBG) Slog.d(TAG, "Pushing " + rules.size() + " active firewall "
599 + name + "UID rules");
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900600 for (int i = 0; i < rules.size(); i++) {
Felipe Lemea701cad2016-05-12 09:58:14 -0700601 setFirewallUidRuleLocked(chain, rules.keyAt(i), rules.valueAt(i));
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900602 }
603 }
604 }
605
bohu07cc3bb2016-05-03 15:58:01 -0700606 private void connectNativeNetdService() {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900607 mNetdService = mServices.getNetd();
bohu07cc3bb2016-05-03 15:58:01 -0700608 }
609
610 /**
611 * Prepare native daemon once connected, enabling modules and pushing any
612 * existing in-memory rules.
613 */
614 private void prepareNativeDaemon() {
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900615
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700616 // push any existing quota or UID rules
617 synchronized (mQuotaLock) {
Felipe Leme65be3022016-03-22 14:53:13 -0700618
Luke Huang56a03a02018-09-07 12:02:16 +0800619 // Netd unconditionally enable bandwidth control
620 SystemProperties.set(PROP_QTAGUID_ENABLED, "1");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900621
Luke Huang473eb872018-07-26 17:33:14 +0800622 mStrictEnabled = true;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900623
Felipe Leme65be3022016-03-22 14:53:13 -0700624 setDataSaverModeEnabled(mDataSaverMode);
625
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700626 int size = mActiveQuotas.size();
627 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800628 if (DBG) Slog.d(TAG, "Pushing " + size + " active quota rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700629 final HashMap<String, Long> activeQuotas = mActiveQuotas;
630 mActiveQuotas = Maps.newHashMap();
631 for (Map.Entry<String, Long> entry : activeQuotas.entrySet()) {
632 setInterfaceQuota(entry.getKey(), entry.getValue());
633 }
634 }
635
636 size = mActiveAlerts.size();
637 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800638 if (DBG) Slog.d(TAG, "Pushing " + size + " active alert rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700639 final HashMap<String, Long> activeAlerts = mActiveAlerts;
640 mActiveAlerts = Maps.newHashMap();
641 for (Map.Entry<String, Long> entry : activeAlerts.entrySet()) {
642 setInterfaceAlert(entry.getKey(), entry.getValue());
643 }
644 }
645
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700646 SparseBooleanArray uidRejectOnQuota = null;
647 SparseBooleanArray uidAcceptOnQuota = null;
648 synchronized (mRulesLock) {
649 size = mUidRejectOnMetered.size();
650 if (size > 0) {
651 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered blacklist rules");
652 uidRejectOnQuota = mUidRejectOnMetered;
653 mUidRejectOnMetered = new SparseBooleanArray();
654 }
655
656 size = mUidAllowOnMetered.size();
657 if (size > 0) {
658 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered whitelist rules");
659 uidAcceptOnQuota = mUidAllowOnMetered;
660 mUidAllowOnMetered = new SparseBooleanArray();
661 }
662 }
663 if (uidRejectOnQuota != null) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700664 for (int i = 0; i < uidRejectOnQuota.size(); i++) {
Felipe Leme65be3022016-03-22 14:53:13 -0700665 setUidMeteredNetworkBlacklist(uidRejectOnQuota.keyAt(i),
666 uidRejectOnQuota.valueAt(i));
667 }
668 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700669 if (uidAcceptOnQuota != null) {
Felipe Leme65be3022016-03-22 14:53:13 -0700670 for (int i = 0; i < uidAcceptOnQuota.size(); i++) {
671 setUidMeteredNetworkWhitelist(uidAcceptOnQuota.keyAt(i),
672 uidAcceptOnQuota.valueAt(i));
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700673 }
674 }
Jeff Sharkey605eb792014-11-04 13:34:06 -0800675
676 size = mUidCleartextPolicy.size();
677 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800678 if (DBG) Slog.d(TAG, "Pushing " + size + " active UID cleartext policies");
Jeff Sharkey605eb792014-11-04 13:34:06 -0800679 final SparseIntArray local = mUidCleartextPolicy;
680 mUidCleartextPolicy = new SparseIntArray();
681 for (int i = 0; i < local.size(); i++) {
682 setUidCleartextNetworkPolicy(local.keyAt(i), local.valueAt(i));
683 }
684 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700685
Robin Leec3736bc2017-03-10 16:19:54 +0000686 setFirewallEnabled(mFirewallEnabled);
Amith Yamasani15e472352015-04-24 19:06:07 -0700687
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700688 syncFirewallChainLocked(FIREWALL_CHAIN_NONE, "");
689 syncFirewallChainLocked(FIREWALL_CHAIN_STANDBY, "standby ");
690 syncFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, "dozable ");
691 syncFirewallChainLocked(FIREWALL_CHAIN_POWERSAVE, "powersave ");
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700692
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700693 final int[] chains =
694 {FIREWALL_CHAIN_STANDBY, FIREWALL_CHAIN_DOZABLE, FIREWALL_CHAIN_POWERSAVE};
695 for (int chain : chains) {
696 if (getFirewallChainState(chain)) {
697 setFirewallChainEnabled(chain, true);
698 }
Felipe Leme011b98f2016-02-10 17:28:31 -0800699 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700700 }
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900701
Luke Huang56a03a02018-09-07 12:02:16 +0800702
703 try {
704 getBatteryStats().noteNetworkStatsEnabled();
705 } catch (RemoteException e) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900706 }
707
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700708 }
San Mehat4d02d002010-01-22 16:07:46 -0800709
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900710 /**
711 * Notify our observers of a new or updated interface address.
712 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900713 private void notifyAddressUpdated(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900714 invokeForAllObservers(o -> o.addressUpdated(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900715 }
716
717 /**
718 * Notify our observers of a deleted interface address.
719 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900720 private void notifyAddressRemoved(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900721 invokeForAllObservers(o -> o.addressRemoved(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900722 }
723
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900724 /**
725 * Notify our observers of DNS server information received.
726 */
727 private void notifyInterfaceDnsServerInfo(String iface, long lifetime, String[] addresses) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900728 invokeForAllObservers(o -> o.interfaceDnsServerInfo(iface, lifetime, addresses));
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900729 }
730
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900731 /**
732 * Notify our observers of a route change.
733 */
734 private void notifyRouteChange(String action, RouteInfo route) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900735 if (action.equals("updated")) {
736 invokeForAllObservers(o -> o.routeUpdated(route));
737 } else {
738 invokeForAllObservers(o -> o.routeRemoved(route));
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900739 }
740 }
741
San Mehat873f2142010-01-14 10:25:07 -0800742 //
743 // Netd Callback handling
744 //
745
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700746 private class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
747 @Override
San Mehat873f2142010-01-14 10:25:07 -0800748 public void onDaemonConnected() {
Felipe Leme65be3022016-03-22 14:53:13 -0700749 Slog.i(TAG, "onDaemonConnected()");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700750 // event is dispatched from internal NDC thread, so we prepare the
751 // daemon back on main thread.
752 if (mConnectedSignal != null) {
bohu07cc3bb2016-05-03 15:58:01 -0700753 // The system is booting and we're connecting to netd for the first time.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700754 mConnectedSignal.countDown();
755 mConnectedSignal = null;
756 } else {
bohu07cc3bb2016-05-03 15:58:01 -0700757 // We're reconnecting to netd after the socket connection
758 // was interrupted (e.g., if it crashed).
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700759 mFgHandler.post(new Runnable() {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700760 @Override
761 public void run() {
bohu07cc3bb2016-05-03 15:58:01 -0700762 connectNativeNetdService();
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700763 prepareNativeDaemon();
764 }
765 });
766 }
San Mehat873f2142010-01-14 10:25:07 -0800767 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700768
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700769 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800770 public boolean onCheckHoldWakeLock(int code) {
771 return code == NetdResponseCode.InterfaceClassActivity;
772 }
773
774 @Override
San Mehat873f2142010-01-14 10:25:07 -0800775 public boolean onEvent(int code, String raw, String[] cooked) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900776 String errorMessage = String.format("Invalid event from daemon (%s)", raw);
JP Abgrall12b933d2011-07-14 18:09:22 -0700777 switch (code) {
778 case NetdResponseCode.InterfaceChange:
779 /*
780 * a network interface change occured
781 * Format: "NNN Iface added <name>"
782 * "NNN Iface removed <name>"
783 * "NNN Iface changed <name> <up/down>"
784 * "NNN Iface linkstatus <name> <up/down>"
785 */
786 if (cooked.length < 4 || !cooked[1].equals("Iface")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900787 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700788 }
789 if (cooked[2].equals("added")) {
790 notifyInterfaceAdded(cooked[3]);
791 return true;
792 } else if (cooked[2].equals("removed")) {
793 notifyInterfaceRemoved(cooked[3]);
794 return true;
795 } else if (cooked[2].equals("changed") && cooked.length == 5) {
796 notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
797 return true;
798 } else if (cooked[2].equals("linkstate") && cooked.length == 5) {
799 notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
800 return true;
801 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900802 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700803 // break;
804 case NetdResponseCode.BandwidthControl:
805 /*
806 * Bandwidth control needs some attention
807 * Format: "NNN limit alert <alertName> <ifaceName>"
808 */
809 if (cooked.length < 5 || !cooked[1].equals("limit")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900810 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700811 }
812 if (cooked[2].equals("alert")) {
813 notifyLimitReached(cooked[3], cooked[4]);
814 return true;
815 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900816 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700817 // break;
Haoyu Baidb3c8672012-06-20 14:29:57 -0700818 case NetdResponseCode.InterfaceClassActivity:
819 /*
820 * An network interface class state changed (active/idle)
821 * Format: "NNN IfaceClass <active/idle> <label>"
822 */
823 if (cooked.length < 4 || !cooked[1].equals("IfaceClass")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900824 throw new IllegalStateException(errorMessage);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700825 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700826 long timestampNanos = 0;
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700827 int processUid = -1;
828 if (cooked.length >= 5) {
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700829 try {
830 timestampNanos = Long.parseLong(cooked[4]);
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700831 if (cooked.length == 6) {
832 processUid = Integer.parseInt(cooked[5]);
833 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700834 } catch(NumberFormatException ne) {}
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700835 } else {
836 timestampNanos = SystemClock.elapsedRealtimeNanos();
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700837 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700838 boolean isActive = cooked[2].equals("active");
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700839 notifyInterfaceClassActivity(Integer.parseInt(cooked[3]),
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700840 isActive ? DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700841 : DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
842 timestampNanos, processUid, false);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700843 return true;
844 // break;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900845 case NetdResponseCode.InterfaceAddressChange:
846 /*
847 * A network address change occurred
848 * Format: "NNN Address updated <addr> <iface> <flags> <scope>"
849 * "NNN Address removed <addr> <iface> <flags> <scope>"
850 */
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900851 if (cooked.length < 7 || !cooked[1].equals("Address")) {
852 throw new IllegalStateException(errorMessage);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900853 }
854
Lorenzo Colitti64483942013-11-15 18:43:52 +0900855 String iface = cooked[4];
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900856 LinkAddress address;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900857 try {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900858 int flags = Integer.parseInt(cooked[5]);
859 int scope = Integer.parseInt(cooked[6]);
860 address = new LinkAddress(cooked[3], flags, scope);
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900861 } catch(NumberFormatException e) { // Non-numeric lifetime or scope.
862 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti64483942013-11-15 18:43:52 +0900863 } catch(IllegalArgumentException e) { // Malformed/invalid IP address.
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900864 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900865 }
866
867 if (cooked[2].equals("updated")) {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900868 notifyAddressUpdated(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900869 } else {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900870 notifyAddressRemoved(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900871 }
872 return true;
873 // break;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900874 case NetdResponseCode.InterfaceDnsServerInfo:
875 /*
876 * Information about available DNS servers has been received.
877 * Format: "NNN DnsInfo servers <interface> <lifetime> <servers>"
878 */
879 long lifetime; // Actually a 32-bit unsigned integer.
880
881 if (cooked.length == 6 &&
882 cooked[1].equals("DnsInfo") &&
883 cooked[2].equals("servers")) {
884 try {
885 lifetime = Long.parseLong(cooked[4]);
886 } catch (NumberFormatException e) {
887 throw new IllegalStateException(errorMessage);
888 }
889 String[] servers = cooked[5].split(",");
890 notifyInterfaceDnsServerInfo(cooked[3], lifetime, servers);
891 }
892 return true;
893 // break;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900894 case NetdResponseCode.RouteChange:
895 /*
896 * A route has been updated or removed.
897 * Format: "NNN Route <updated|removed> <dst> [via <gateway] [dev <iface>]"
898 */
899 if (!cooked[1].equals("Route") || cooked.length < 6) {
900 throw new IllegalStateException(errorMessage);
901 }
902
903 String via = null;
904 String dev = null;
905 boolean valid = true;
906 for (int i = 4; (i + 1) < cooked.length && valid; i += 2) {
907 if (cooked[i].equals("dev")) {
908 if (dev == null) {
909 dev = cooked[i+1];
910 } else {
911 valid = false; // Duplicate interface.
912 }
913 } else if (cooked[i].equals("via")) {
914 if (via == null) {
915 via = cooked[i+1];
916 } else {
917 valid = false; // Duplicate gateway.
918 }
919 } else {
920 valid = false; // Unknown syntax.
921 }
922 }
923 if (valid) {
924 try {
925 // InetAddress.parseNumericAddress(null) inexplicably returns ::1.
926 InetAddress gateway = null;
927 if (via != null) gateway = InetAddress.parseNumericAddress(via);
928 RouteInfo route = new RouteInfo(new IpPrefix(cooked[3]), gateway, dev);
929 notifyRouteChange(cooked[2], route);
930 return true;
931 } catch (IllegalArgumentException e) {}
932 }
933 throw new IllegalStateException(errorMessage);
934 // break;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800935 case NetdResponseCode.StrictCleartext:
936 final int uid = Integer.parseInt(cooked[1]);
937 final byte[] firstPacket = HexDump.hexStringToByteArray(cooked[2]);
938 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800939 ActivityManager.getService().notifyCleartextNetwork(uid, firstPacket);
Jeff Sharkey605eb792014-11-04 13:34:06 -0800940 } catch (RemoteException ignored) {
941 }
942 break;
JP Abgrall12b933d2011-07-14 18:09:22 -0700943 default: break;
Robert Greenwalte3253922010-02-18 09:23:25 -0800944 }
945 return false;
San Mehat873f2142010-01-14 10:25:07 -0800946 }
947 }
948
San Mehated4fc8a2010-01-22 12:28:36 -0800949
San Mehat873f2142010-01-14 10:25:07 -0800950 //
951 // INetworkManagementService members
952 //
Erik Kline4e37b702016-07-05 11:34:21 +0900953 @Override
954 public INetd getNetdService() throws RemoteException {
955 final CountDownLatch connectedSignal = mConnectedSignal;
956 if (connectedSignal != null) {
957 try {
958 connectedSignal.await();
959 } catch (InterruptedException ignored) {}
960 }
961
962 return mNetdService;
963 }
San Mehat873f2142010-01-14 10:25:07 -0800964
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800965 @Override
966 public String[] listInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800967 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700968 try {
Luke Huang14f75442018-08-15 19:22:54 +0800969 final List<String> result = mNetdService.interfaceGetList();
970 return result.toArray(EMPTY_STRING_ARRAY);
971 } catch (RemoteException | ServiceSpecificException e) {
972 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700973 }
San Mehated4fc8a2010-01-22 12:28:36 -0800974 }
975
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800976 @Override
977 public InterfaceConfiguration getInterfaceConfig(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800978 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang14f75442018-08-15 19:22:54 +0800979 final InterfaceConfigurationParcel result;
Kenny Roota80ce062010-06-01 13:23:53 -0700980 try {
Luke Huang14f75442018-08-15 19:22:54 +0800981 result = mNetdService.interfaceGetCfg(iface);
982 } catch (RemoteException | ServiceSpecificException e) {
983 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700984 }
San Mehated4fc8a2010-01-22 12:28:36 -0800985
San Mehated4fc8a2010-01-22 12:28:36 -0800986 try {
Luke Huang14f75442018-08-15 19:22:54 +0800987 final InterfaceConfiguration cfg = InterfaceConfiguration.fromParcel(result);
988 return cfg;
989 } catch (IllegalArgumentException iae) {
990 throw new IllegalStateException("Invalid InterfaceConfigurationParcel", iae);
San Mehated4fc8a2010-01-22 12:28:36 -0800991 }
San Mehated4fc8a2010-01-22 12:28:36 -0800992 }
993
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800994 @Override
995 public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800996 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800997 LinkAddress linkAddr = cfg.getLinkAddress();
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800998 if (linkAddr == null || linkAddr.getAddress() == null) {
999 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -08001000 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001001
Luke Huang14f75442018-08-15 19:22:54 +08001002 final InterfaceConfigurationParcel cfgParcel = cfg.toParcel(iface);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001003
Kenny Roota80ce062010-06-01 13:23:53 -07001004 try {
Luke Huang14f75442018-08-15 19:22:54 +08001005 mNetdService.interfaceSetCfg(cfgParcel);
1006 } catch (RemoteException | ServiceSpecificException e) {
1007 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001008 }
San Mehat873f2142010-01-14 10:25:07 -08001009 }
1010
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001011 @Override
1012 public void setInterfaceDown(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001013 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001014 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001015 ifcg.setInterfaceDown();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001016 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001017 }
1018
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001019 @Override
1020 public void setInterfaceUp(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001021 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001022 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001023 ifcg.setInterfaceUp();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001024 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001025 }
1026
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001027 @Override
1028 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001029 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sheriff73293612011-09-14 12:31:56 -07001030 try {
Luke Huang14f75442018-08-15 19:22:54 +08001031 mNetdService.interfaceSetIPv6PrivacyExtensions(iface, enable);
1032 } catch (RemoteException | ServiceSpecificException e) {
1033 throw new IllegalStateException(e);
Irfan Sheriff73293612011-09-14 12:31:56 -07001034 }
1035 }
1036
Irfan Sherifff5600612011-06-16 10:26:28 -07001037 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
1038 IPv6 addresses on interface down, but we need to do full clean up here */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001039 @Override
1040 public void clearInterfaceAddresses(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001041 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sherifff5600612011-06-16 10:26:28 -07001042 try {
Luke Huang14f75442018-08-15 19:22:54 +08001043 mNetdService.interfaceClearAddrs(iface);
1044 } catch (RemoteException | ServiceSpecificException e) {
1045 throw new IllegalStateException(e);
Irfan Sherifff5600612011-06-16 10:26:28 -07001046 }
1047 }
1048
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001049 @Override
1050 public void enableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001051 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001052 try {
Luke Huang14f75442018-08-15 19:22:54 +08001053 mNetdService.interfaceSetEnableIPv6(iface, true);
1054 } catch (RemoteException | ServiceSpecificException e) {
1055 throw new IllegalStateException(e);
repo sync7960d9f2011-09-29 12:40:02 -07001056 }
1057 }
1058
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001059 @Override
Joel Scherpelz2db10742017-06-07 15:38:38 +09001060 public void setIPv6AddrGenMode(String iface, int mode) throws ServiceSpecificException {
1061 try {
1062 mNetdService.setIPv6AddrGenMode(iface, mode);
1063 } catch (RemoteException e) {
1064 throw e.rethrowAsRuntimeException();
1065 }
1066 }
1067
1068 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001069 public void disableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001070 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001071 try {
Luke Huang14f75442018-08-15 19:22:54 +08001072 mNetdService.interfaceSetEnableIPv6(iface, false);
1073 } catch (RemoteException | ServiceSpecificException e) {
1074 throw new IllegalStateException(e);
repo sync7960d9f2011-09-29 12:40:02 -07001075 }
1076 }
1077
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001078 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001079 public void addRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001080 modifyRoute(MODIFY_OPERATION_ADD, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001081 }
1082
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001083 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001084 public void removeRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001085 modifyRoute(MODIFY_OPERATION_REMOVE, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001086 }
1087
Luke Huang8a462ec2018-08-24 20:33:16 +08001088 private void modifyRoute(boolean add, int netId, RouteInfo route) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001089 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001090
Luke Huang8a462ec2018-08-24 20:33:16 +08001091 final String ifName = route.getInterface();
1092 final String dst = route.getDestination().toString();
1093 final String nextHop;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001094
1095 switch (route.getType()) {
1096 case RouteInfo.RTN_UNICAST:
1097 if (route.hasGateway()) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001098 nextHop = route.getGateway().getHostAddress();
1099 } else {
1100 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001101 }
1102 break;
1103 case RouteInfo.RTN_UNREACHABLE:
Luke Huang8a462ec2018-08-24 20:33:16 +08001104 nextHop = INetd.NEXTHOP_UNREACHABLE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001105 break;
1106 case RouteInfo.RTN_THROW:
Luke Huang8a462ec2018-08-24 20:33:16 +08001107 nextHop = INetd.NEXTHOP_THROW;
1108 break;
1109 default:
1110 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001111 break;
Sreeram Ramachandran1fbcb272014-05-22 16:30:48 -07001112 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001113 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08001114 if (add) {
1115 mNetdService.networkAddRoute(netId, ifName, dst, nextHop);
1116 } else {
1117 mNetdService.networkRemoveRoute(netId, ifName, dst, nextHop);
1118 }
1119 } catch (RemoteException | ServiceSpecificException e) {
1120 throw new IllegalStateException(e);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001121 }
1122 }
1123
1124 private ArrayList<String> readRouteList(String filename) {
1125 FileInputStream fstream = null;
Christopher Wiley212b95f2016-08-02 11:38:57 -07001126 ArrayList<String> list = new ArrayList<>();
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001127
1128 try {
1129 fstream = new FileInputStream(filename);
1130 DataInputStream in = new DataInputStream(fstream);
1131 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1132 String s;
1133
1134 // throw away the title line
1135
1136 while (((s = br.readLine()) != null) && (s.length() != 0)) {
1137 list.add(s);
1138 }
1139 } catch (IOException ex) {
1140 // return current list, possibly empty
1141 } finally {
1142 if (fstream != null) {
1143 try {
1144 fstream.close();
1145 } catch (IOException ex) {}
1146 }
1147 }
1148
1149 return list;
1150 }
1151
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001152 @Override
sy.yun9d9b74a2013-09-02 05:24:09 +09001153 public void setMtu(String iface, int mtu) {
1154 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1155
sy.yun9d9b74a2013-09-02 05:24:09 +09001156 try {
Luke Huang14f75442018-08-15 19:22:54 +08001157 mNetdService.interfaceSetMtu(iface, mtu);
1158 } catch (RemoteException | ServiceSpecificException e) {
1159 throw new IllegalStateException(e);
sy.yun9d9b74a2013-09-02 05:24:09 +09001160 }
1161 }
1162
1163 @Override
San Mehat873f2142010-01-14 10:25:07 -08001164 public void shutdown() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001165 // TODO: remove from aidl if nobody calls externally
1166 mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001167
Felipe Leme03e689d2016-03-02 16:17:38 -08001168 Slog.i(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -08001169 }
1170
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001171 @Override
San Mehat873f2142010-01-14 10:25:07 -08001172 public boolean getIpForwardingEnabled() throws IllegalStateException{
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001173 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001174
Kenny Roota80ce062010-06-01 13:23:53 -07001175 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001176 final boolean isEnabled = mNetdService.ipfwdEnabled();
1177 return isEnabled;
1178 } catch (RemoteException | ServiceSpecificException e) {
1179 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001180 }
San Mehat873f2142010-01-14 10:25:07 -08001181 }
1182
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001183 @Override
1184 public void setIpForwardingEnabled(boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001185 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001186 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001187 if (enable) {
1188 mNetdService.ipfwdEnableForwarding("tethering");
1189 } else {
1190 mNetdService.ipfwdDisableForwarding("tethering");
1191 }
1192 } catch (RemoteException | ServiceSpecificException e) {
1193 throw new IllegalStateException(e);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001194 }
San Mehat873f2142010-01-14 10:25:07 -08001195 }
1196
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001197 @Override
1198 public void startTethering(String[] dhcpRange) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001199 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -07001200 // an odd number of addrs will fail
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001201
Kenny Roota80ce062010-06-01 13:23:53 -07001202 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001203 mNetdService.tetherStart(dhcpRange);
1204 } catch (RemoteException | ServiceSpecificException e) {
1205 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001206 }
San Mehat873f2142010-01-14 10:25:07 -08001207 }
1208
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001209 @Override
1210 public void stopTethering() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001211 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001212 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001213 mNetdService.tetherStop();
1214 } catch (RemoteException | ServiceSpecificException e) {
1215 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001216 }
San Mehat873f2142010-01-14 10:25:07 -08001217 }
1218
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001219 @Override
1220 public boolean isTetheringStarted() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001221 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001222
Kenny Roota80ce062010-06-01 13:23:53 -07001223 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001224 final boolean isEnabled = mNetdService.tetherIsEnabled();
1225 return isEnabled;
1226 } catch (RemoteException | ServiceSpecificException e) {
1227 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001228 }
San Mehat873f2142010-01-14 10:25:07 -08001229 }
Matthew Xiefe19f122012-07-12 16:03:32 -07001230
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001231 @Override
1232 public void tetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001233 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001234 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001235 mNetdService.tetherInterfaceAdd(iface);
1236 } catch (RemoteException | ServiceSpecificException e) {
1237 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001238 }
Christopher Wiley212b95f2016-08-02 11:38:57 -07001239 List<RouteInfo> routes = new ArrayList<>();
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07001240 // The RouteInfo constructor truncates the LinkAddress to a network prefix, thus making it
1241 // suitable to use as a route destination.
1242 routes.add(new RouteInfo(getInterfaceConfig(iface).getLinkAddress(), null, iface));
1243 addInterfaceToLocalNetwork(iface, routes);
San Mehat873f2142010-01-14 10:25:07 -08001244 }
1245
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001246 @Override
San Mehat873f2142010-01-14 10:25:07 -08001247 public void untetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001248 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001249 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001250 mNetdService.tetherInterfaceRemove(iface);
1251 } catch (RemoteException | ServiceSpecificException e) {
1252 throw new IllegalStateException(e);
Erik Kline1f4278a2016-08-16 16:46:33 +09001253 } finally {
1254 removeInterfaceFromLocalNetwork(iface);
Kenny Roota80ce062010-06-01 13:23:53 -07001255 }
San Mehat873f2142010-01-14 10:25:07 -08001256 }
1257
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001258 @Override
1259 public String[] listTetheredInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001260 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001261 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001262 final List<String> result = mNetdService.tetherInterfaceList();
1263 return result.toArray(EMPTY_STRING_ARRAY);
1264 } catch (RemoteException | ServiceSpecificException e) {
1265 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001266 }
San Mehat873f2142010-01-14 10:25:07 -08001267 }
1268
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001269 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001270 public void setDnsForwarders(Network network, String[] dns) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001271 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001272
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001273 int netId = (network != null) ? network.netId : ConnectivityManager.NETID_UNSET;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001274
San Mehat873f2142010-01-14 10:25:07 -08001275 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001276 mNetdService.tetherDnsSet(netId, dns);
1277 } catch (RemoteException | ServiceSpecificException e) {
1278 throw new IllegalStateException(e);
San Mehat873f2142010-01-14 10:25:07 -08001279 }
1280 }
1281
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001282 @Override
1283 public String[] getDnsForwarders() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001284 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001285 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001286 final List<String> result = mNetdService.tetherDnsList();
1287 return result.toArray(EMPTY_STRING_ARRAY);
1288 } catch (RemoteException | ServiceSpecificException e) {
1289 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001290 }
San Mehat873f2142010-01-14 10:25:07 -08001291 }
1292
jiaguo1da35f72014-01-09 16:39:59 +08001293 private List<InterfaceAddress> excludeLinkLocal(List<InterfaceAddress> addresses) {
Christopher Wiley212b95f2016-08-02 11:38:57 -07001294 ArrayList<InterfaceAddress> filtered = new ArrayList<>(addresses.size());
jiaguo1da35f72014-01-09 16:39:59 +08001295 for (InterfaceAddress ia : addresses) {
1296 if (!ia.getAddress().isLinkLocalAddress())
1297 filtered.add(ia);
1298 }
1299 return filtered;
1300 }
1301
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001302 private void modifyInterfaceForward(boolean add, String fromIface, String toIface) {
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001303 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001304 if (add) {
1305 mNetdService.ipfwdAddInterfaceForward(fromIface, toIface);
1306 } else {
1307 mNetdService.ipfwdRemoveInterfaceForward(fromIface, toIface);
1308 }
1309 } catch (RemoteException | ServiceSpecificException e) {
1310 throw new IllegalStateException(e);
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001311 }
1312 }
1313
1314 @Override
1315 public void startInterfaceForwarding(String fromIface, String toIface) {
1316 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1317 modifyInterfaceForward(true, fromIface, toIface);
1318 }
1319
1320 @Override
1321 public void stopInterfaceForwarding(String fromIface, String toIface) {
1322 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1323 modifyInterfaceForward(false, fromIface, toIface);
1324 }
1325
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001326 private void modifyNat(String action, String internalInterface, String externalInterface)
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001327 throws SocketException {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001328 final Command cmd = new Command("nat", action, internalInterface, externalInterface);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001329
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001330 final NetworkInterface internalNetworkInterface = NetworkInterface.getByName(
1331 internalInterface);
Robert Greenwalte83d1812011-11-21 14:44:39 -08001332 if (internalNetworkInterface == null) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001333 cmd.appendArg("0");
Robert Greenwalte83d1812011-11-21 14:44:39 -08001334 } else {
jiaguo1da35f72014-01-09 16:39:59 +08001335 // Don't touch link-local routes, as link-local addresses aren't routable,
1336 // kernel creates link-local routes on all interfaces automatically
1337 List<InterfaceAddress> interfaceAddresses = excludeLinkLocal(
1338 internalNetworkInterface.getInterfaceAddresses());
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001339 cmd.appendArg(interfaceAddresses.size());
Robert Greenwalte83d1812011-11-21 14:44:39 -08001340 for (InterfaceAddress ia : interfaceAddresses) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001341 InetAddress addr = NetworkUtils.getNetworkPart(
1342 ia.getAddress(), ia.getNetworkPrefixLength());
1343 cmd.appendArg(addr.getHostAddress() + "/" + ia.getNetworkPrefixLength());
Robert Greenwalte83d1812011-11-21 14:44:39 -08001344 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001345 }
1346
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001347 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001348 mConnector.execute(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001349 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001350 throw e.rethrowAsParcelableException();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001351 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001352 }
1353
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001354 @Override
1355 public void enableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001356 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001357 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001358 modifyNat("enable", internalInterface, externalInterface);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001359 } catch (SocketException e) {
1360 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001361 }
San Mehat873f2142010-01-14 10:25:07 -08001362 }
1363
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001364 @Override
1365 public void disableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001366 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001367 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001368 modifyNat("disable", internalInterface, externalInterface);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001369 } catch (SocketException e) {
1370 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001371 }
San Mehat873f2142010-01-14 10:25:07 -08001372 }
San Mehat72759df2010-01-19 13:50:37 -08001373
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001374 @Override
1375 public String[] listTtys() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001376 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001377 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001378 return NativeDaemonEvent.filterMessageList(
1379 mConnector.executeForList("list_ttys"), TtyListResult);
Kenny Roota80ce062010-06-01 13:23:53 -07001380 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001381 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001382 }
San Mehat72759df2010-01-19 13:50:37 -08001383 }
1384
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001385 @Override
1386 public void attachPppd(
1387 String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001388 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat72759df2010-01-19 13:50:37 -08001389 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001390 mConnector.execute("pppd", "attach", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -08001391 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
1392 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
1393 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001394 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress());
Kenny Roota80ce062010-06-01 13:23:53 -07001395 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001396 throw e.rethrowAsParcelableException();
San Mehat72759df2010-01-19 13:50:37 -08001397 }
1398 }
1399
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001400 @Override
1401 public void detachPppd(String tty) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001402 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001403 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001404 mConnector.execute("pppd", "detach", tty);
Kenny Roota80ce062010-06-01 13:23:53 -07001405 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001406 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001407 }
San Mehat72759df2010-01-19 13:50:37 -08001408 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -08001409
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001410 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001411 public void addIdleTimer(String iface, int timeout, final int type) {
Haoyu Bai04124232012-06-28 15:26:19 -07001412 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1413
1414 if (DBG) Slog.d(TAG, "Adding idletimer");
1415
1416 synchronized (mIdleTimerLock) {
1417 IdleTimerParams params = mActiveIdleTimers.get(iface);
1418 if (params != null) {
1419 // the interface already has idletimer, update network count
1420 params.networkCount++;
1421 return;
1422 }
1423
1424 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001425 mNetdService.idletimerAddInterface(iface, timeout, Integer.toString(type));
1426 } catch (RemoteException | ServiceSpecificException e) {
1427 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001428 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001429 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
1430
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001431 // Networks start up.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001432 if (ConnectivityManager.isNetworkTypeMobile(type)) {
1433 mNetworkActive = false;
1434 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001435 mDaemonHandler.post(new Runnable() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001436 @Override public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001437 notifyInterfaceClassActivity(type,
1438 DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07001439 SystemClock.elapsedRealtimeNanos(), -1, false);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001440 }
1441 });
Haoyu Bai04124232012-06-28 15:26:19 -07001442 }
1443 }
1444
1445 @Override
1446 public void removeIdleTimer(String iface) {
1447 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1448
1449 if (DBG) Slog.d(TAG, "Removing idletimer");
1450
1451 synchronized (mIdleTimerLock) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001452 final IdleTimerParams params = mActiveIdleTimers.get(iface);
Haoyu Bai04124232012-06-28 15:26:19 -07001453 if (params == null || --(params.networkCount) > 0) {
1454 return;
1455 }
1456
1457 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001458 mNetdService.idletimerRemoveInterface(iface,
1459 params.timeout, Integer.toString(params.type));
1460 } catch (RemoteException | ServiceSpecificException e) {
1461 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001462 }
1463 mActiveIdleTimers.remove(iface);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001464 mDaemonHandler.post(new Runnable() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001465 @Override public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001466 notifyInterfaceClassActivity(params.type,
1467 DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07001468 SystemClock.elapsedRealtimeNanos(), -1, false);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001469 }
1470 });
Haoyu Bai04124232012-06-28 15:26:19 -07001471 }
1472 }
1473
1474 @Override
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001475 public NetworkStats getNetworkStatsSummaryDev() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001476 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001477 try {
1478 return mStatsFactory.readNetworkStatsSummaryDev();
1479 } catch (IOException e) {
1480 throw new IllegalStateException(e);
1481 }
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001482 }
1483
1484 @Override
1485 public NetworkStats getNetworkStatsSummaryXt() {
1486 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001487 try {
1488 return mStatsFactory.readNetworkStatsSummaryXt();
1489 } catch (IOException e) {
1490 throw new IllegalStateException(e);
1491 }
Jeff Sharkeyae2c1812011-10-04 13:11:40 -07001492 }
1493
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001494 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001495 public NetworkStats getNetworkStatsDetail() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001496 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001497 try {
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08001498 return mStatsFactory.readNetworkStatsDetail(UID_ALL, null, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001499 } catch (IOException e) {
1500 throw new IllegalStateException(e);
1501 }
San Mehat91cac642010-03-31 14:31:36 -07001502 }
1503
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001504 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001505 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001506 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001507
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001508 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001509 if (mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001510 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001511 }
1512
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001513 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001514 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001515 mNetdService.bandwidthSetInterfaceQuota(iface, quotaBytes);
1516
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001517 mActiveQuotas.put(iface, quotaBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001518 } catch (RemoteException | ServiceSpecificException e) {
1519 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001520 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001521
1522 synchronized (mTetheringStatsProviders) {
1523 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1524 try {
1525 provider.setInterfaceQuota(iface, quotaBytes);
1526 } catch (RemoteException e) {
1527 Log.e(TAG, "Problem setting tethering data limit on provider " +
1528 mTetheringStatsProviders.get(provider) + ": " + e);
1529 }
1530 }
1531 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001532 }
1533 }
1534
1535 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001536 public void removeInterfaceQuota(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001537 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001538
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001539 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001540 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001541 // TODO: eventually consider throwing
1542 return;
1543 }
1544
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001545 mActiveQuotas.remove(iface);
1546 mActiveAlerts.remove(iface);
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001547
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001548 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001549 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001550 mNetdService.bandwidthRemoveInterfaceQuota(iface);
1551 } catch (RemoteException | ServiceSpecificException e) {
1552 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001553 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001554
1555 synchronized (mTetheringStatsProviders) {
1556 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1557 try {
1558 provider.setInterfaceQuota(iface, ITetheringStatsProvider.QUOTA_UNLIMITED);
1559 } catch (RemoteException e) {
1560 Log.e(TAG, "Problem removing tethering data limit on provider " +
1561 mTetheringStatsProviders.get(provider) + ": " + e);
1562 }
1563 }
1564 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001565 }
1566 }
1567
1568 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001569 public void setInterfaceAlert(String iface, long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001570 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001571
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001572 // quick sanity check
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001573 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001574 throw new IllegalStateException("setting alert requires existing quota on iface");
1575 }
1576
1577 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001578 if (mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001579 throw new IllegalStateException("iface " + iface + " already has alert");
1580 }
1581
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001582 try {
1583 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001584 mNetdService.bandwidthSetInterfaceAlert(iface, alertBytes);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001585 mActiveAlerts.put(iface, alertBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001586 } catch (RemoteException | ServiceSpecificException e) {
1587 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001588 }
1589 }
1590 }
1591
1592 @Override
1593 public void removeInterfaceAlert(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001594 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001595
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001596 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001597 if (!mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001598 // TODO: eventually consider throwing
1599 return;
1600 }
1601
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001602 try {
1603 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001604 mNetdService.bandwidthRemoveInterfaceAlert(iface);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001605 mActiveAlerts.remove(iface);
Luke Huangc7bea8662018-08-07 16:04:26 +08001606 } catch (RemoteException | ServiceSpecificException e) {
1607 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001608 }
1609 }
1610 }
1611
1612 @Override
1613 public void setGlobalAlert(long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001614 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001615
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001616 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001617 mNetdService.bandwidthSetGlobalAlert(alertBytes);
1618 } catch (RemoteException | ServiceSpecificException e) {
1619 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001620 }
1621 }
1622
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001623 private void setUidOnMeteredNetworkList(int uid, boolean blacklist, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001624 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001625
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001626 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001627 boolean oldEnable;
1628 SparseBooleanArray quotaList;
1629 synchronized (mRulesLock) {
1630 quotaList = blacklist ? mUidRejectOnMetered : mUidAllowOnMetered;
1631 oldEnable = quotaList.get(uid, false);
1632 }
Felipe Leme65be3022016-03-22 14:53:13 -07001633 if (oldEnable == enable) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001634 // TODO: eventually consider throwing
1635 return;
1636 }
1637
Felipe Leme29e72ea2016-09-08 13:26:55 -07001638 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "inetd bandwidth");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001639 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001640 if (blacklist) {
1641 if (enable) {
1642 mNetdService.bandwidthAddNaughtyApp(uid);
1643 } else {
1644 mNetdService.bandwidthRemoveNaughtyApp(uid);
1645 }
1646 } else {
1647 if (enable) {
1648 mNetdService.bandwidthAddNiceApp(uid);
1649 } else {
1650 mNetdService.bandwidthRemoveNiceApp(uid);
1651 }
1652 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001653 synchronized (mRulesLock) {
1654 if (enable) {
1655 quotaList.put(uid, true);
1656 } else {
1657 quotaList.delete(uid);
1658 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001659 }
Luke Huangc7bea8662018-08-07 16:04:26 +08001660 } catch (RemoteException | ServiceSpecificException e) {
1661 throw new IllegalStateException(e);
Felipe Leme29e72ea2016-09-08 13:26:55 -07001662 } finally {
1663 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001664 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001665 }
1666 }
1667
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001668 @Override
Felipe Leme65be3022016-03-22 14:53:13 -07001669 public void setUidMeteredNetworkBlacklist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001670 setUidOnMeteredNetworkList(uid, true, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001671 }
1672
1673 @Override
1674 public void setUidMeteredNetworkWhitelist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001675 setUidOnMeteredNetworkList(uid, false, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001676 }
1677
1678 @Override
1679 public boolean setDataSaverModeEnabled(boolean enable) {
Sehee Parka9139bc2017-12-22 13:54:05 +09001680 mContext.enforceCallingOrSelfPermission(NETWORK_SETTINGS, TAG);
1681
Felipe Leme65be3022016-03-22 14:53:13 -07001682 if (DBG) Log.d(TAG, "setDataSaverMode: " + enable);
1683 synchronized (mQuotaLock) {
1684 if (mDataSaverMode == enable) {
1685 Log.w(TAG, "setDataSaverMode(): already " + mDataSaverMode);
1686 return true;
1687 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07001688 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "bandwidthEnableDataSaver");
Felipe Leme65be3022016-03-22 14:53:13 -07001689 try {
1690 final boolean changed = mNetdService.bandwidthEnableDataSaver(enable);
1691 if (changed) {
1692 mDataSaverMode = enable;
1693 } else {
1694 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command silently failed");
1695 }
1696 return changed;
1697 } catch (RemoteException e) {
1698 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command failed", e);
1699 return false;
Felipe Leme29e72ea2016-09-08 13:26:55 -07001700 } finally {
1701 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme65be3022016-03-22 14:53:13 -07001702 }
1703 }
1704 }
1705
1706 @Override
Robin Lee17e61832016-05-09 13:46:28 +01001707 public void setAllowOnlyVpnForUids(boolean add, UidRange[] uidRanges)
1708 throws ServiceSpecificException {
Rubin Xu2ea6c552018-01-11 10:59:19 +00001709 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robin Lee17e61832016-05-09 13:46:28 +01001710 try {
1711 mNetdService.networkRejectNonSecureVpn(add, uidRanges);
1712 } catch (ServiceSpecificException e) {
1713 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1714 + ": netd command failed", e);
1715 throw e;
1716 } catch (RemoteException e) {
1717 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1718 + ": netd command failed", e);
1719 throw e.rethrowAsRuntimeException();
1720 }
1721 }
1722
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001723 private void applyUidCleartextNetworkPolicy(int uid, int policy) {
Luke Huang473eb872018-07-26 17:33:14 +08001724 final int policyValue;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001725 switch (policy) {
1726 case StrictMode.NETWORK_POLICY_ACCEPT:
Luke Huang473eb872018-07-26 17:33:14 +08001727 policyValue = INetd.PENALTY_POLICY_ACCEPT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001728 break;
1729 case StrictMode.NETWORK_POLICY_LOG:
Luke Huang473eb872018-07-26 17:33:14 +08001730 policyValue = INetd.PENALTY_POLICY_LOG;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001731 break;
1732 case StrictMode.NETWORK_POLICY_REJECT:
Luke Huang473eb872018-07-26 17:33:14 +08001733 policyValue = INetd.PENALTY_POLICY_REJECT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001734 break;
1735 default:
1736 throw new IllegalArgumentException("Unknown policy " + policy);
1737 }
1738
1739 try {
Luke Huang473eb872018-07-26 17:33:14 +08001740 mNetdService.strictUidCleartextPenalty(uid, policyValue);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001741 mUidCleartextPolicy.put(uid, policy);
Luke Huang473eb872018-07-26 17:33:14 +08001742 } catch (RemoteException | ServiceSpecificException e) {
1743 throw new IllegalStateException(e);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001744 }
1745 }
1746
Robin Lee17e61832016-05-09 13:46:28 +01001747 @Override
Jeff Sharkey605eb792014-11-04 13:34:06 -08001748 public void setUidCleartextNetworkPolicy(int uid, int policy) {
1749 if (Binder.getCallingUid() != uid) {
1750 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1751 }
1752
1753 synchronized (mQuotaLock) {
1754 final int oldPolicy = mUidCleartextPolicy.get(uid, StrictMode.NETWORK_POLICY_ACCEPT);
1755 if (oldPolicy == policy) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001756 // This also ensures we won't needlessly apply an ACCEPT policy if we've just
1757 // enabled strict and the underlying iptables rules are empty.
Jeff Sharkey605eb792014-11-04 13:34:06 -08001758 return;
1759 }
1760
Luke Huang473eb872018-07-26 17:33:14 +08001761 // TODO: remove this code after removing prepareNativeDaemon()
Jeff Sharkey605eb792014-11-04 13:34:06 -08001762 if (!mStrictEnabled) {
1763 // Module isn't enabled yet; stash the requested policy away to
1764 // apply later once the daemon is connected.
1765 mUidCleartextPolicy.put(uid, policy);
1766 return;
1767 }
1768
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001769 // netd does not keep state on strict mode policies, and cannot replace a non-accept
1770 // policy without deleting it first. Rather than add state to netd, just always send
1771 // it an accept policy when switching between two non-accept policies.
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001772 // TODO: consider keeping state in netd so we can simplify this code.
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001773 if (oldPolicy != StrictMode.NETWORK_POLICY_ACCEPT &&
1774 policy != StrictMode.NETWORK_POLICY_ACCEPT) {
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001775 applyUidCleartextNetworkPolicy(uid, StrictMode.NETWORK_POLICY_ACCEPT);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001776 }
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001777
1778 applyUidCleartextNetworkPolicy(uid, policy);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001779 }
1780 }
1781
1782 @Override
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001783 public boolean isBandwidthControlEnabled() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001784 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang56a03a02018-09-07 12:02:16 +08001785 return true;
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001786 }
1787
1788 @Override
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001789 public NetworkStats getNetworkStatsUidDetail(int uid, String[] ifaces) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001790 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001791 try {
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001792 return mStatsFactory.readNetworkStatsDetail(uid, ifaces, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001793 } catch (IOException e) {
1794 throw new IllegalStateException(e);
1795 }
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001796 }
1797
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001798 private class NetdTetheringStatsProvider extends ITetheringStatsProvider.Stub {
1799 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001800 public NetworkStats getTetherStats(int how) {
1801 // We only need to return per-UID stats. Per-device stats are already counted by
1802 // interface counters.
1803 if (how != STATS_PER_UID) {
1804 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
1805 }
1806
Luke Huang13b79e82018-09-26 14:53:42 +08001807 final TetherStatsParcel[] tetherStatsVec;
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001808 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001809 tetherStatsVec = mNetdService.tetherGetStats();
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001810 } catch (RemoteException | ServiceSpecificException e) {
1811 throw new IllegalStateException("problem parsing tethering stats: ", e);
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001812 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001813
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001814 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(),
Luke Huang13b79e82018-09-26 14:53:42 +08001815 tetherStatsVec.length);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001816 final NetworkStats.Entry entry = new NetworkStats.Entry();
1817
Luke Huang13b79e82018-09-26 14:53:42 +08001818 for (TetherStatsParcel tetherStats : tetherStatsVec) {
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001819 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001820 entry.iface = tetherStats.iface;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001821 entry.uid = UID_TETHERING;
1822 entry.set = SET_DEFAULT;
1823 entry.tag = TAG_NONE;
Luke Huang13b79e82018-09-26 14:53:42 +08001824 entry.rxBytes = tetherStats.rxBytes;
1825 entry.rxPackets = tetherStats.rxPackets;
1826 entry.txBytes = tetherStats.txBytes;
1827 entry.txPackets = tetherStats.txPackets;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001828 stats.combineValues(entry);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001829 } catch (ArrayIndexOutOfBoundsException e) {
Luke Huang13b79e82018-09-26 14:53:42 +08001830 throw new IllegalStateException("invalid tethering stats " + e);
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001831 }
1832 }
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001833
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001834 return stats;
1835 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001836
1837 @Override
1838 public void setInterfaceQuota(String iface, long quotaBytes) {
1839 // Do nothing. netd is already informed of quota changes in setInterfaceQuota.
1840 }
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001841 }
1842
1843 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001844 public NetworkStats getNetworkStatsTethering(int how) {
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001845 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1846
1847 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1848 synchronized (mTetheringStatsProviders) {
1849 for (ITetheringStatsProvider provider: mTetheringStatsProviders.keySet()) {
1850 try {
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001851 stats.combineAllValues(provider.getTetherStats(how));
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001852 } catch (RemoteException e) {
1853 Log.e(TAG, "Problem reading tethering stats from " +
1854 mTetheringStatsProviders.get(provider) + ": " + e);
1855 }
1856 }
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001857 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001858 return stats;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001859 }
1860
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001861 @Override
Erik Kline1742fe12017-12-13 19:40:49 +09001862 public void setDnsConfigurationForNetwork(int netId, String[] servers, String[] domains,
Erik Klinee5dac902018-03-04 21:01:01 +09001863 int[] params, String tlsHostname, String[] tlsServers) {
Pierre Imai8e48e672016-04-21 13:30:43 +09001864 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1865
Ben Schwartz6ec28df2017-10-02 13:08:06 -04001866 final String[] tlsFingerprints = new String[0];
Pierre Imai8e48e672016-04-21 13:30:43 +09001867 try {
Erik Kline1742fe12017-12-13 19:40:49 +09001868 mNetdService.setResolverConfiguration(
Erik Klinee5dac902018-03-04 21:01:01 +09001869 netId, servers, domains, params, tlsHostname, tlsServers, tlsFingerprints);
Pierre Imai8e48e672016-04-21 13:30:43 +09001870 } catch (RemoteException e) {
1871 throw new RuntimeException(e);
1872 }
1873 }
1874
1875 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001876 public void addVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001877 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001878
1879 try {
1880 mNetdService.networkAddUidRanges(netId, ranges);
1881 } catch (RemoteException | ServiceSpecificException e) {
1882 throw new IllegalStateException(e);
Chad Brubaker3277620a2013-06-12 13:37:30 -07001883 }
1884 }
1885
1886 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001887 public void removeVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001888 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001889 try {
1890 mNetdService.networkRemoveUidRanges(netId, ranges);
1891 } catch (RemoteException | ServiceSpecificException e) {
1892 throw new IllegalStateException(e);
Chad Brubakercca54c42013-06-27 17:41:38 -07001893 }
1894 }
1895
1896 @Override
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001897 public void setFirewallEnabled(boolean enabled) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001898 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001899 try {
Luke Huanga241db92018-07-31 20:15:24 +08001900 mNetdService.firewallSetFirewallType(
1901 enabled ? INetd.FIREWALL_WHITELIST : INetd.FIREWALL_BLACKLIST);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001902 mFirewallEnabled = enabled;
Luke Huanga241db92018-07-31 20:15:24 +08001903 } catch (RemoteException | ServiceSpecificException e) {
1904 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001905 }
1906 }
1907
1908 @Override
1909 public boolean isFirewallEnabled() {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001910 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001911 return mFirewallEnabled;
1912 }
1913
1914 @Override
Jeff Sharkey2c092982012-08-24 11:44:40 -07001915 public void setFirewallInterfaceRule(String iface, boolean allow) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001916 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001917 Preconditions.checkState(mFirewallEnabled);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001918 try {
Luke Huanga241db92018-07-31 20:15:24 +08001919 mNetdService.firewallSetInterfaceRule(iface,
1920 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
1921 } catch (RemoteException | ServiceSpecificException e) {
1922 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001923 }
1924 }
1925
Lorenzo Colitti3fef7232016-04-29 18:00:03 +09001926 private void closeSocketsForFirewallChainLocked(int chain, String chainName) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001927 // UID ranges to close sockets on.
1928 UidRange[] ranges;
1929 // UID ranges whose sockets we won't touch.
1930 int[] exemptUids;
1931
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001932 int numUids = 0;
Luke Huanga241db92018-07-31 20:15:24 +08001933 if (DBG) Slog.d(TAG, "Closing sockets after enabling chain " + chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001934 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
1935 // Close all sockets on all non-system UIDs...
1936 ranges = new UidRange[] {
1937 // TODO: is there a better way of finding all existing users? If so, we could
1938 // specify their ranges here.
1939 new UidRange(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE),
1940 };
1941 // ... except for the UIDs that have allow rules.
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001942 synchronized (mRulesLock) {
1943 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1944 exemptUids = new int[rules.size()];
1945 for (int i = 0; i < exemptUids.length; i++) {
1946 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
1947 exemptUids[numUids] = rules.keyAt(i);
1948 numUids++;
1949 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001950 }
1951 }
1952 // Normally, whitelist chains only contain deny rules, so numUids == exemptUids.length.
1953 // But the code does not guarantee this in any way, and at least in one case - if we add
1954 // a UID rule to the firewall, and then disable the firewall - the chains can contain
1955 // the wrong type of rule. In this case, don't close connections that we shouldn't.
1956 //
1957 // TODO: tighten up this code by ensuring we never set the wrong type of rule, and
1958 // fix setFirewallEnabled to grab mQuotaLock and clear rules.
1959 if (numUids != exemptUids.length) {
1960 exemptUids = Arrays.copyOf(exemptUids, numUids);
1961 }
1962 } else {
1963 // Close sockets for every UID that has a deny rule...
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001964 synchronized (mRulesLock) {
1965 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1966 ranges = new UidRange[rules.size()];
1967 for (int i = 0; i < ranges.length; i++) {
1968 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_DENY) {
1969 int uid = rules.keyAt(i);
1970 ranges[numUids] = new UidRange(uid, uid);
1971 numUids++;
1972 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001973 }
1974 }
1975 // As above; usually numUids == ranges.length, but not always.
1976 if (numUids != ranges.length) {
1977 ranges = Arrays.copyOf(ranges, numUids);
1978 }
1979 // ... with no exceptions.
1980 exemptUids = new int[0];
1981 }
1982
1983 try {
1984 mNetdService.socketDestroy(ranges, exemptUids);
1985 } catch(RemoteException | ServiceSpecificException e) {
1986 Slog.e(TAG, "Error closing sockets after enabling chain " + chainName + ": " + e);
1987 }
1988 }
1989
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001990 @Override
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001991 public void setFirewallChainEnabled(int chain, boolean enable) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001992 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001993 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001994 synchronized (mRulesLock) {
1995 if (getFirewallChainState(chain) == enable) {
1996 // All is the same, nothing to do. This relies on the fact that netd has child
1997 // chains default detached.
1998 return;
1999 }
2000 setFirewallChainState(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002001 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002002
Luke Huang615e1022018-10-25 11:54:05 +09002003 final String chainName = getFirewallChainName(chain);
Luke Huanga241db92018-07-31 20:15:24 +08002004 if (chain == FIREWALL_CHAIN_NONE) {
Luke Huang615e1022018-10-25 11:54:05 +09002005 throw new IllegalArgumentException("Bad child chain: " + chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002006 }
2007
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002008 try {
Luke Huanga241db92018-07-31 20:15:24 +08002009 mNetdService.firewallEnableChildChain(chain, enable);
2010 } catch (RemoteException | ServiceSpecificException e) {
2011 throw new IllegalStateException(e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002012 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002013
2014 // Close any sockets that were opened by the affected UIDs. This has to be done after
2015 // disabling network connectivity, in case they react to the socket close by reopening
2016 // the connection and race with the iptables commands that enable the firewall. All
2017 // whitelist and blacklist chains allow RSTs through.
2018 if (enable) {
Luke Huang615e1022018-10-25 11:54:05 +09002019 closeSocketsForFirewallChainLocked(chain, chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002020 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002021 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002022 }
2023
Luke Huanga241db92018-07-31 20:15:24 +08002024 private String getFirewallChainName(int chain) {
2025 switch (chain) {
2026 case FIREWALL_CHAIN_STANDBY:
2027 return FIREWALL_CHAIN_NAME_STANDBY;
2028 case FIREWALL_CHAIN_DOZABLE:
2029 return FIREWALL_CHAIN_NAME_DOZABLE;
2030 case FIREWALL_CHAIN_POWERSAVE:
2031 return FIREWALL_CHAIN_NAME_POWERSAVE;
2032 default:
2033 throw new IllegalArgumentException("Bad child chain: " + chain);
2034 }
2035 }
2036
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002037 private int getFirewallType(int chain) {
2038 switch (chain) {
2039 case FIREWALL_CHAIN_STANDBY:
2040 return FIREWALL_TYPE_BLACKLIST;
2041 case FIREWALL_CHAIN_DOZABLE:
2042 return FIREWALL_TYPE_WHITELIST;
Felipe Leme011b98f2016-02-10 17:28:31 -08002043 case FIREWALL_CHAIN_POWERSAVE:
2044 return FIREWALL_TYPE_WHITELIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002045 default:
2046 return isFirewallEnabled() ? FIREWALL_TYPE_WHITELIST : FIREWALL_TYPE_BLACKLIST;
2047 }
2048 }
2049
2050 @Override
2051 public void setFirewallUidRules(int chain, int[] uids, int[] rules) {
2052 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002053 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002054 synchronized (mRulesLock) {
2055 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
2056 SparseIntArray newRules = new SparseIntArray();
2057 // apply new set of rules
2058 for (int index = uids.length - 1; index >= 0; --index) {
2059 int uid = uids[index];
2060 int rule = rules[index];
2061 updateFirewallUidRuleLocked(chain, uid, rule);
2062 newRules.put(uid, rule);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002063 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002064 // collect the rules to remove.
2065 SparseIntArray rulesToRemove = new SparseIntArray();
2066 for (int index = uidFirewallRules.size() - 1; index >= 0; --index) {
2067 int uid = uidFirewallRules.keyAt(index);
2068 if (newRules.indexOfKey(uid) < 0) {
2069 rulesToRemove.put(uid, FIREWALL_RULE_DEFAULT);
2070 }
2071 }
2072 // remove dead rules
2073 for (int index = rulesToRemove.size() - 1; index >= 0; --index) {
2074 int uid = rulesToRemove.keyAt(index);
2075 updateFirewallUidRuleLocked(chain, uid, FIREWALL_RULE_DEFAULT);
2076 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002077 }
2078 try {
2079 switch (chain) {
2080 case FIREWALL_CHAIN_DOZABLE:
2081 mNetdService.firewallReplaceUidChain("fw_dozable", true, uids);
2082 break;
2083 case FIREWALL_CHAIN_STANDBY:
2084 mNetdService.firewallReplaceUidChain("fw_standby", false, uids);
2085 break;
2086 case FIREWALL_CHAIN_POWERSAVE:
2087 mNetdService.firewallReplaceUidChain("fw_powersave", true, uids);
2088 break;
2089 case FIREWALL_CHAIN_NONE:
2090 default:
2091 Slog.d(TAG, "setFirewallUidRules() called on invalid chain: " + chain);
2092 }
2093 } catch (RemoteException e) {
2094 Slog.w(TAG, "Error flushing firewall chain " + chain, e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002095 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002096 }
2097 }
2098
2099 @Override
2100 public void setFirewallUidRule(int chain, int uid, int rule) {
2101 enforceSystemUid();
Felipe Lemea701cad2016-05-12 09:58:14 -07002102 synchronized (mQuotaLock) {
2103 setFirewallUidRuleLocked(chain, uid, rule);
2104 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002105 }
2106
Felipe Lemea701cad2016-05-12 09:58:14 -07002107 private void setFirewallUidRuleLocked(int chain, int uid, int rule) {
2108 if (updateFirewallUidRuleLocked(chain, uid, rule)) {
Luke Huanga241db92018-07-31 20:15:24 +08002109 final int ruleType = getFirewallRuleType(chain, rule);
Amith Yamasani15e472352015-04-24 19:06:07 -07002110 try {
Luke Huanga241db92018-07-31 20:15:24 +08002111 mNetdService.firewallSetUidRule(chain, uid, ruleType);
2112 } catch (RemoteException | ServiceSpecificException e) {
2113 throw new IllegalStateException(e);
Amith Yamasani15e472352015-04-24 19:06:07 -07002114 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002115 }
2116 }
2117
Felipe Lemea701cad2016-05-12 09:58:14 -07002118 // TODO: now that netd supports batching, NMS should not keep these data structures anymore...
2119 private boolean updateFirewallUidRuleLocked(int chain, int uid, int rule) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002120 synchronized (mRulesLock) {
2121 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Felipe Lemea701cad2016-05-12 09:58:14 -07002122
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002123 final int oldUidFirewallRule = uidFirewallRules.get(uid, FIREWALL_RULE_DEFAULT);
2124 if (DBG) {
2125 Slog.d(TAG, "oldRule = " + oldUidFirewallRule
2126 + ", newRule=" + rule + " for uid=" + uid + " on chain " + chain);
2127 }
2128 if (oldUidFirewallRule == rule) {
2129 if (DBG) Slog.d(TAG, "!!!!! Skipping change");
2130 // TODO: eventually consider throwing
2131 return false;
2132 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002133
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002134 String ruleName = getFirewallRuleName(chain, rule);
2135 String oldRuleName = getFirewallRuleName(chain, oldUidFirewallRule);
Felipe Lemea701cad2016-05-12 09:58:14 -07002136
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002137 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
2138 uidFirewallRules.delete(uid);
2139 } else {
2140 uidFirewallRules.put(uid, rule);
2141 }
2142 return !ruleName.equals(oldRuleName);
Felipe Lemea701cad2016-05-12 09:58:14 -07002143 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002144 }
2145
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002146 private @NonNull String getFirewallRuleName(int chain, int rule) {
2147 String ruleName;
2148 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
2149 if (rule == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
2150 ruleName = "allow";
2151 } else {
2152 ruleName = "deny";
2153 }
2154 } else { // Blacklist mode
2155 if (rule == NetworkPolicyManager.FIREWALL_RULE_DENY) {
2156 ruleName = "deny";
2157 } else {
2158 ruleName = "allow";
2159 }
2160 }
2161 return ruleName;
2162 }
2163
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002164 private @NonNull SparseIntArray getUidFirewallRulesLR(int chain) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002165 switch (chain) {
2166 case FIREWALL_CHAIN_STANDBY:
2167 return mUidFirewallStandbyRules;
2168 case FIREWALL_CHAIN_DOZABLE:
2169 return mUidFirewallDozableRules;
Felipe Leme011b98f2016-02-10 17:28:31 -08002170 case FIREWALL_CHAIN_POWERSAVE:
2171 return mUidFirewallPowerSaveRules;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002172 case FIREWALL_CHAIN_NONE:
2173 return mUidFirewallRules;
2174 default:
2175 throw new IllegalArgumentException("Unknown chain:" + chain);
2176 }
2177 }
2178
Luke Huanga241db92018-07-31 20:15:24 +08002179 private int getFirewallRuleType(int chain, int rule) {
Luke Huang615e1022018-10-25 11:54:05 +09002180 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
2181 return getFirewallType(chain) == FIREWALL_TYPE_WHITELIST
2182 ? INetd.FIREWALL_RULE_DENY : INetd.FIREWALL_RULE_ALLOW;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002183 }
Luke Huang615e1022018-10-25 11:54:05 +09002184 return rule;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002185 }
2186
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07002187 private static void enforceSystemUid() {
2188 final int uid = Binder.getCallingUid();
2189 if (uid != Process.SYSTEM_UID) {
2190 throw new SecurityException("Only available to AID_SYSTEM");
2191 }
2192 }
2193
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002194 @Override
Lorenzo Colitti79751842013-02-28 16:16:03 +09002195 public void startClatd(String interfaceName) throws IllegalStateException {
2196 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2197
2198 try {
Luke Huang69369f32018-08-02 15:51:41 +08002199 mNetdService.clatdStart(interfaceName);
2200 } catch (RemoteException | ServiceSpecificException e) {
2201 throw new IllegalStateException(e);
Lorenzo Colitti79751842013-02-28 16:16:03 +09002202 }
2203 }
2204
2205 @Override
Lorenzo Colitti95439462014-10-09 13:44:48 +09002206 public void stopClatd(String interfaceName) throws IllegalStateException {
Lorenzo Colitti79751842013-02-28 16:16:03 +09002207 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2208
2209 try {
Luke Huang69369f32018-08-02 15:51:41 +08002210 mNetdService.clatdStop(interfaceName);
2211 } catch (RemoteException | ServiceSpecificException e) {
2212 throw new IllegalStateException(e);
Lorenzo Colitti79751842013-02-28 16:16:03 +09002213 }
2214 }
2215
2216 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002217 public void registerNetworkActivityListener(INetworkActivityListener listener) {
2218 mNetworkActivityListeners.register(listener);
2219 }
2220
2221 @Override
2222 public void unregisterNetworkActivityListener(INetworkActivityListener listener) {
2223 mNetworkActivityListeners.unregister(listener);
2224 }
2225
2226 @Override
2227 public boolean isNetworkActive() {
2228 synchronized (mNetworkActivityListeners) {
2229 return mNetworkActive || mActiveIdleTimers.isEmpty();
2230 }
2231 }
2232
2233 private void reportNetworkActive() {
2234 final int length = mNetworkActivityListeners.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002235 try {
2236 for (int i = 0; i < length; i++) {
2237 try {
2238 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
Felipe Leme03e689d2016-03-02 16:17:38 -08002239 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002240 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002241 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002242 } finally {
2243 mNetworkActivityListeners.finishBroadcast();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002244 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002245 }
2246
Mattias Falk8b47b362011-08-23 14:15:13 +02002247 /** {@inheritDoc} */
Jeff Sharkey7b4596f2013-02-25 10:55:29 -08002248 @Override
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002249 public void monitor() {
2250 if (mConnector != null) {
2251 mConnector.monitor();
2252 }
2253 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002254
2255 @Override
2256 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002257 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002258
Robert Greenwalt470fd722012-01-18 12:51:15 -08002259 pw.println("NetworkManagementService NativeDaemonConnector Log:");
2260 mConnector.dump(fd, pw, args);
2261 pw.println();
2262
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07002263 pw.print("mMobileActivityFromRadio="); pw.print(mMobileActivityFromRadio);
2264 pw.print(" mLastPowerStateFromRadio="); pw.println(mLastPowerStateFromRadio);
2265 pw.print("mNetworkActive="); pw.println(mNetworkActive);
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002266
2267 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07002268 pw.print("Active quota ifaces: "); pw.println(mActiveQuotas.toString());
2269 pw.print("Active alert ifaces: "); pw.println(mActiveAlerts.toString());
Felipe Leme65be3022016-03-22 14:53:13 -07002270 pw.print("Data saver mode: "); pw.println(mDataSaverMode);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002271 synchronized (mRulesLock) {
2272 dumpUidRuleOnQuotaLocked(pw, "blacklist", mUidRejectOnMetered);
2273 dumpUidRuleOnQuotaLocked(pw, "whitelist", mUidAllowOnMetered);
2274 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002275 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002276
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002277 synchronized (mRulesLock) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002278 dumpUidFirewallRule(pw, "", mUidFirewallRules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002279
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002280 pw.print("UID firewall standby chain enabled: "); pw.println(
2281 getFirewallChainState(FIREWALL_CHAIN_STANDBY));
Felipe Leme011b98f2016-02-10 17:28:31 -08002282 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_STANDBY, mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002283
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002284 pw.print("UID firewall dozable chain enabled: "); pw.println(
2285 getFirewallChainState(FIREWALL_CHAIN_DOZABLE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002286 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_DOZABLE, mUidFirewallDozableRules);
Felipe Leme011b98f2016-02-10 17:28:31 -08002287
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002288 pw.println("UID firewall powersave chain enabled: " +
2289 getFirewallChainState(FIREWALL_CHAIN_POWERSAVE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002290 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_POWERSAVE, mUidFirewallPowerSaveRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002291 }
2292
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002293 synchronized (mIdleTimerLock) {
2294 pw.println("Idle timers:");
2295 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
2296 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
2297 IdleTimerParams params = ent.getValue();
2298 pw.print(" timeout="); pw.print(params.timeout);
2299 pw.print(" type="); pw.print(params.type);
2300 pw.print(" networkCount="); pw.println(params.networkCount);
2301 }
2302 }
2303
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002304 pw.print("Firewall enabled: "); pw.println(mFirewallEnabled);
Felipe Leme65be3022016-03-22 14:53:13 -07002305 pw.print("Netd service status: " );
2306 if (mNetdService == null) {
2307 pw.println("disconnected");
2308 } else {
2309 try {
2310 final boolean alive = mNetdService.isAlive();
2311 pw.println(alive ? "alive": "dead");
2312 } catch (RemoteException e) {
2313 pw.println("unreachable");
2314 }
2315 }
2316 }
2317
2318 private void dumpUidRuleOnQuotaLocked(PrintWriter pw, String name, SparseBooleanArray list) {
2319 pw.print("UID bandwith control ");
2320 pw.print(name);
2321 pw.print(" rule: [");
2322 final int size = list.size();
2323 for (int i = 0; i < size; i++) {
2324 pw.print(list.keyAt(i));
2325 if (i < size - 1) pw.print(",");
2326 }
2327 pw.println("]");
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002328 }
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002329
Felipe Leme011b98f2016-02-10 17:28:31 -08002330 private void dumpUidFirewallRule(PrintWriter pw, String name, SparseIntArray rules) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002331 pw.print("UID firewall ");
Felipe Leme011b98f2016-02-10 17:28:31 -08002332 pw.print(name);
2333 pw.print(" rule: [");
2334 final int size = rules.size();
2335 for (int i = 0; i < size; i++) {
2336 pw.print(rules.keyAt(i));
2337 pw.print(":");
2338 pw.print(rules.valueAt(i));
2339 if (i < size - 1) pw.print(",");
2340 }
2341 pw.println("]");
2342 }
2343
Robert Greenwalt568891d2014-04-04 13:38:00 -07002344 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002345 public void createPhysicalNetwork(int netId, int permission) {
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002346 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2347
2348 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002349 mNetdService.networkCreatePhysical(netId, permission);
2350 } catch (RemoteException | ServiceSpecificException e) {
2351 throw new IllegalStateException(e);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002352 }
2353 }
2354
Robert Greenwalt568891d2014-04-04 13:38:00 -07002355 @Override
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07002356 public void createVirtualNetwork(int netId, boolean hasDNS, boolean secure) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002357 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2358
2359 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002360 mNetdService.networkCreateVpn(netId, hasDNS, secure);
2361 } catch (RemoteException | ServiceSpecificException e) {
2362 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002363 }
2364 }
2365
2366 @Override
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002367 public void removeNetwork(int netId) {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002368 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002369
2370 try {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002371 mNetdService.networkDestroy(netId);
2372 } catch (ServiceSpecificException e) {
2373 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2374 throw e;
2375 } catch (RemoteException e) {
2376 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2377 throw e.rethrowAsRuntimeException();
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002378 }
2379 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002380
2381 @Override
Paul Jensen992f2522014-04-28 10:33:11 -04002382 public void addInterfaceToNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002383 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, netId, iface);
Paul Jensen992f2522014-04-28 10:33:11 -04002384 }
2385
2386 @Override
2387 public void removeInterfaceFromNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002388 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, netId, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002389 }
Paul Jensen992f2522014-04-28 10:33:11 -04002390
Luke Huang8a462ec2018-08-24 20:33:16 +08002391 private void modifyInterfaceInNetwork(boolean add, int netId, String iface) {
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002392 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Paul Jensen992f2522014-04-28 10:33:11 -04002393 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002394 if (add) {
2395 mNetdService.networkAddInterface(netId, iface);
2396 } else {
2397 mNetdService.networkRemoveInterface(netId, iface);
2398 }
2399 } catch (RemoteException | ServiceSpecificException e) {
2400 throw new IllegalStateException(e);
Paul Jensen992f2522014-04-28 10:33:11 -04002401 }
2402 }
2403
2404 @Override
Robert Greenwalt913c8952014-04-07 17:36:35 -07002405 public void addLegacyRouteForNetId(int netId, RouteInfo routeInfo, int uid) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002406 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2407
Sreeram Ramachandrancc91c7b2014-06-03 18:41:43 -07002408 final LinkAddress la = routeInfo.getDestinationLinkAddress();
Luke Huang8a462ec2018-08-24 20:33:16 +08002409 final String ifName = routeInfo.getInterface();
2410 final String dst = la.toString();
2411 final String nextHop;
Robert Greenwalt568891d2014-04-04 13:38:00 -07002412
Luke Huang8a462ec2018-08-24 20:33:16 +08002413 if (routeInfo.hasGateway()) {
2414 nextHop = routeInfo.getGateway().getHostAddress();
2415 } else {
2416 nextHop = "";
2417 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002418 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002419 mNetdService.networkAddLegacyRoute(netId, ifName, dst, nextHop, uid);
2420 } catch (RemoteException | ServiceSpecificException e) {
2421 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002422 }
2423 }
2424
2425 @Override
Sreeram Ramachandranf047f2a2014-04-15 16:04:26 -07002426 public void setDefaultNetId(int netId) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002427 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2428
2429 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002430 mNetdService.networkSetDefault(netId);
2431 } catch (RemoteException | ServiceSpecificException e) {
2432 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002433 }
2434 }
2435
2436 @Override
2437 public void clearDefaultNetId() {
2438 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2439
2440 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002441 mNetdService.networkClearDefault();
2442 } catch (RemoteException | ServiceSpecificException e) {
2443 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002444 }
2445 }
2446
2447 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002448 public void setNetworkPermission(int netId, int permission) {
Paul Jensen487ffe72015-07-24 15:57:11 -04002449 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2450
2451 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002452 mNetdService.networkSetPermissionForNetwork(netId, permission);
2453 } catch (RemoteException | ServiceSpecificException e) {
2454 throw new IllegalStateException(e);
Paul Jensen487ffe72015-07-24 15:57:11 -04002455 }
2456 }
2457
Luke Huang8a462ec2018-08-24 20:33:16 +08002458 private int parsePermission(String permission) {
2459 if (permission.equals("NETWORK")) {
2460 return INetd.PERMISSION_NETWORK;
2461 }
2462 if (permission.equals("SYSTEM")) {
2463 return INetd.PERMISSION_SYSTEM;
2464 }
2465 return INetd.PERMISSION_NONE;
2466 }
Paul Jensen487ffe72015-07-24 15:57:11 -04002467
2468 @Override
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002469 public void setPermission(String permission, int[] uids) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002470 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2471
Luke Huang8a462ec2018-08-24 20:33:16 +08002472 try {
2473 mNetdService.networkSetPermissionForUser(parsePermission(permission), uids);
2474 } catch (RemoteException | ServiceSpecificException e) {
2475 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002476 }
2477 }
2478
2479 @Override
2480 public void clearPermission(int[] uids) {
2481 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2482
Luke Huang8a462ec2018-08-24 20:33:16 +08002483 try {
2484 mNetdService.networkClearPermissionForUser(uids);
2485 } catch (RemoteException | ServiceSpecificException e) {
2486 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002487 }
2488 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002489
2490 @Override
2491 public void allowProtect(int uid) {
2492 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2493
2494 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002495 mNetdService.networkSetProtectAllow(uid);
2496 } catch (RemoteException | ServiceSpecificException e) {
2497 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002498 }
2499 }
2500
2501 @Override
2502 public void denyProtect(int uid) {
2503 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2504
2505 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002506 mNetdService.networkSetProtectDeny(uid);
2507 } catch (RemoteException | ServiceSpecificException e) {
2508 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002509 }
2510 }
2511
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002512 @Override
2513 public void addInterfaceToLocalNetwork(String iface, List<RouteInfo> routes) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002514 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002515
2516 for (RouteInfo route : routes) {
2517 if (!route.isDefaultRoute()) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002518 modifyRoute(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID, route);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002519 }
2520 }
2521 }
2522
2523 @Override
2524 public void removeInterfaceFromLocalNetwork(String iface) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002525 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, INetd.LOCAL_NET_ID, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002526 }
Erik Kline6599ee82016-07-17 21:28:39 +09002527
2528 @Override
2529 public int removeRoutesFromLocalNetwork(List<RouteInfo> routes) {
2530 int failures = 0;
2531
2532 for (RouteInfo route : routes) {
2533 try {
Luke Huang706d7ab2018-10-16 15:42:15 +08002534 modifyRoute(MODIFY_OPERATION_REMOVE, INetd.LOCAL_NET_ID, route);
Erik Kline6599ee82016-07-17 21:28:39 +09002535 } catch (IllegalStateException e) {
2536 failures++;
2537 }
2538 }
2539
2540 return failures;
2541 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002542
Sudheer Shankab8f23162017-08-04 13:30:10 -07002543 @Override
2544 public boolean isNetworkRestricted(int uid) {
2545 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2546 return isNetworkRestrictedInternal(uid);
2547 }
2548
2549 private boolean isNetworkRestrictedInternal(int uid) {
2550 synchronized (mRulesLock) {
2551 if (getFirewallChainState(FIREWALL_CHAIN_STANDBY)
2552 && mUidFirewallStandbyRules.get(uid) == FIREWALL_RULE_DENY) {
2553 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of app standby mode");
2554 return true;
2555 }
2556 if (getFirewallChainState(FIREWALL_CHAIN_DOZABLE)
2557 && mUidFirewallDozableRules.get(uid) != FIREWALL_RULE_ALLOW) {
2558 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of device idle mode");
2559 return true;
2560 }
2561 if (getFirewallChainState(FIREWALL_CHAIN_POWERSAVE)
2562 && mUidFirewallPowerSaveRules.get(uid) != FIREWALL_RULE_ALLOW) {
2563 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of power saver mode");
2564 return true;
2565 }
2566 if (mUidRejectOnMetered.get(uid)) {
2567 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of no metered data"
2568 + " in the background");
2569 return true;
2570 }
2571 if (mDataSaverMode && !mUidAllowOnMetered.get(uid)) {
2572 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of data saver mode");
2573 return true;
2574 }
2575 return false;
2576 }
2577 }
2578
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002579 private void setFirewallChainState(int chain, boolean state) {
2580 synchronized (mRulesLock) {
2581 mFirewallChainStates.put(chain, state);
2582 }
2583 }
2584
2585 private boolean getFirewallChainState(int chain) {
2586 synchronized (mRulesLock) {
2587 return mFirewallChainStates.get(chain);
2588 }
2589 }
2590
2591 @VisibleForTesting
2592 class LocalService extends NetworkManagementInternal {
2593 @Override
2594 public boolean isNetworkRestrictedForUid(int uid) {
Sudheer Shankab8f23162017-08-04 13:30:10 -07002595 return isNetworkRestrictedInternal(uid);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002596 }
2597 }
2598
2599 @VisibleForTesting
2600 Injector getInjector() {
2601 return new Injector();
2602 }
2603
2604 @VisibleForTesting
2605 class Injector {
2606 void setDataSaverMode(boolean dataSaverMode) {
2607 mDataSaverMode = dataSaverMode;
2608 }
2609
2610 void setFirewallChainState(int chain, boolean state) {
2611 NetworkManagementService.this.setFirewallChainState(chain, state);
2612 }
2613
2614 void setFirewallRule(int chain, int uid, int rule) {
2615 synchronized (mRulesLock) {
2616 getUidFirewallRulesLR(chain).put(uid, rule);
2617 }
2618 }
2619
2620 void setUidOnMeteredNetworkList(boolean blacklist, int uid, boolean enable) {
2621 synchronized (mRulesLock) {
2622 if (blacklist) {
2623 mUidRejectOnMetered.put(uid, enable);
2624 } else {
2625 mUidAllowOnMetered.put(uid, enable);
2626 }
2627 }
2628 }
2629
2630 void reset() {
2631 synchronized (mRulesLock) {
2632 setDataSaverMode(false);
2633 final int[] chains = {
2634 FIREWALL_CHAIN_DOZABLE,
2635 FIREWALL_CHAIN_STANDBY,
2636 FIREWALL_CHAIN_POWERSAVE
2637 };
2638 for (int chain : chains) {
2639 setFirewallChainState(chain, false);
2640 getUidFirewallRulesLR(chain).clear();
2641 }
2642 mUidAllowOnMetered.clear();
2643 mUidRejectOnMetered.clear();
2644 }
2645 }
2646 }
San Mehat873f2142010-01-14 10:25:07 -08002647}