blob: c79cf7112109eba89591e2d0b44ff1bad12e1dca [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;
San Mehat4d02d002010-01-22 16:07:46 -080060import android.net.INetworkManagementEventObserver;
Lorenzo Colitti07f13042017-07-10 19:06:57 +090061import android.net.ITetheringStatsProvider;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070062import android.net.InterfaceConfiguration;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +090063import android.net.IpPrefix;
Robert Greenwalted126402011-01-28 15:34:55 -080064import android.net.LinkAddress;
Lorenzo Colittib57edc52014-08-22 17:10:50 -070065import android.net.Network;
Amith Yamasani15e472352015-04-24 19:06:07 -070066import android.net.NetworkPolicyManager;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070067import android.net.NetworkStats;
Robert Greenwalted126402011-01-28 15:34:55 -080068import android.net.NetworkUtils;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070069import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040070import android.net.UidRange;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +090071import android.net.util.NetdService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080072import android.net.wifi.WifiConfiguration;
73import android.net.wifi.WifiConfiguration.KeyMgmt;
Dianne Hackborn91268cf2013-06-13 19:06:50 -070074import android.os.BatteryStats;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070075import android.os.Binder;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -070076import android.os.Handler;
Lorenzo Colittia0868002017-07-11 02:29:28 +090077import android.os.IBinder;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080078import android.os.INetworkActivityListener;
San Mehat873f2142010-01-14 10:25:07 -080079import android.os.INetworkManagementService;
Lorenzo Colitti563dc452017-09-01 17:12:34 +090080import android.os.PersistableBundle;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080081import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070082import android.os.Process;
Jeff Sharkey3df273e2011-12-15 15:47:12 -080083import android.os.RemoteCallbackList;
84import android.os.RemoteException;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070085import android.os.ServiceManager;
Lorenzo Colitti4cb42402016-04-24 12:52:00 +090086import android.os.ServiceSpecificException;
Jeff Sharkey605eb792014-11-04 13:34:06 -080087import android.os.StrictMode;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070088import android.os.SystemClock;
Marco Nelissen62dbb222010-02-18 10:56:30 -080089import android.os.SystemProperties;
Felipe Leme29e72ea2016-09-08 13:26:55 -070090import android.os.Trace;
Pierre Imai8e48e672016-04-21 13:30:43 +090091import android.provider.Settings;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070092import android.telephony.DataConnectionRealTimeInfo;
93import android.telephony.PhoneStateListener;
Wink Savillefb40dd42014-06-12 17:02:31 -070094import android.telephony.SubscriptionManager;
Wink Saville67e07892014-06-18 16:43:14 -070095import android.telephony.TelephonyManager;
Erik Kline4d092232017-10-30 15:29:44 +090096import android.text.TextUtils;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080097import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080098import android.util.Slog;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070099import android.util.SparseBooleanArray;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800100import android.util.SparseIntArray;
San Mehat873f2142010-01-14 10:25:07 -0800101
Jeff Sharkey605eb792014-11-04 13:34:06 -0800102import com.android.internal.annotations.GuardedBy;
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700103import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700104import com.android.internal.app.IBatteryStats;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700105import com.android.internal.net.NetworkStatsFactory;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600106import com.android.internal.util.DumpUtils;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800107import com.android.internal.util.HexDump;
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700108import com.android.internal.util.Preconditions;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800109import com.android.server.NativeDaemonConnector.Command;
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700110import com.android.server.NativeDaemonConnector.SensitiveArg;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700111import com.google.android.collect.Maps;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700112
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700113import java.io.BufferedReader;
114import java.io.DataInputStream;
San Mehat873f2142010-01-14 10:25:07 -0800115import java.io.File;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700116import java.io.FileDescriptor;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700117import java.io.FileInputStream;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700118import java.io.IOException;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700119import java.io.InputStreamReader;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700120import java.io.PrintWriter;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700121import java.net.InetAddress;
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700122import java.net.InterfaceAddress;
123import java.net.NetworkInterface;
124import java.net.SocketException;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700125import java.util.ArrayList;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400126import java.util.Arrays;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700127import java.util.HashMap;
jiaguo1da35f72014-01-09 16:39:59 +0800128import java.util.List;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700129import java.util.Map;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700130import java.util.NoSuchElementException;
131import java.util.StringTokenizer;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700132import java.util.concurrent.CountDownLatch;
San Mehat873f2142010-01-14 10:25:07 -0800133
134/**
135 * @hide
136 */
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700137public class NetworkManagementService extends INetworkManagementService.Stub
138 implements Watchdog.Monitor {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900139
140 /**
141 * Helper class that encapsulates NetworkManagementService dependencies and makes them
142 * easier to mock in unit tests.
143 */
144 static class SystemServices {
145 public IBinder getService(String name) {
146 return ServiceManager.getService(name);
147 }
148 public void registerLocalService(NetworkManagementInternal nmi) {
149 LocalServices.addService(NetworkManagementInternal.class, nmi);
150 }
151 public INetd getNetd() {
152 return NetdService.get();
153 }
154 }
155
Amith Yamasani15e472352015-04-24 19:06:07 -0700156 private static final String TAG = "NetworkManagement";
157 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Kenny Root305bcbf2010-09-03 07:56:38 -0700158 private static final String NETD_TAG = "NetdConnector";
Lorenzo Colittia0868002017-07-11 02:29:28 +0900159 static final String NETD_SERVICE_NAME = "netd";
Kenny Root305bcbf2010-09-03 07:56:38 -0700160
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400161 private static final int MAX_UID_RANGES_PER_COMMAND = 10;
162
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700163 /**
164 * Name representing {@link #setGlobalAlert(long)} limit when delivered to
165 * {@link INetworkManagementEventObserver#limitReached(String, String)}.
166 */
167 public static final String LIMIT_GLOBAL_ALERT = "globalAlert";
168
Paul Jensen487ffe72015-07-24 15:57:11 -0400169 /**
170 * String to pass to netd to indicate that a network is only accessible
171 * to apps that have the CHANGE_NETWORK_STATE permission.
172 */
173 public static final String PERMISSION_NETWORK = "NETWORK";
174
175 /**
176 * String to pass to netd to indicate that a network is only
177 * accessible to system apps and those with the CONNECTIVITY_INTERNAL
178 * permission.
179 */
180 public static final String PERMISSION_SYSTEM = "SYSTEM";
181
Andrew Scull45f533c2017-05-19 15:37:20 +0100182 static class NetdResponseCode {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -0700183 /* Keep in sync with system/netd/server/ResponseCode.h */
San Mehat873f2142010-01-14 10:25:07 -0800184 public static final int InterfaceListResult = 110;
185 public static final int TetherInterfaceListResult = 111;
186 public static final int TetherDnsFwdTgtListResult = 112;
San Mehat72759df2010-01-19 13:50:37 -0800187 public static final int TtyListResult = 113;
Jeff Sharkeye4984be2013-09-10 21:03:27 -0700188 public static final int TetheringStatsListResult = 114;
San Mehat873f2142010-01-14 10:25:07 -0800189
190 public static final int TetherStatusResult = 210;
191 public static final int IpFwdStatusResult = 211;
San Mehated4fc8a2010-01-22 12:28:36 -0800192 public static final int InterfaceGetCfgResult = 213;
Robert Greenwalte3253922010-02-18 09:23:25 -0800193 public static final int SoftapStatusResult = 214;
San Mehat91cac642010-03-31 14:31:36 -0700194 public static final int InterfaceRxCounterResult = 216;
195 public static final int InterfaceTxCounterResult = 217;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700196 public static final int QuotaCounterResult = 220;
197 public static final int TetheringStatsResult = 221;
Selim Gurun84c00c62012-02-27 15:42:38 -0800198 public static final int DnsProxyQueryResult = 222;
Lorenzo Colitti79751842013-02-28 16:16:03 +0900199 public static final int ClatdStatusResult = 223;
Robert Greenwalte3253922010-02-18 09:23:25 -0800200
201 public static final int InterfaceChange = 600;
JP Abgrall12b933d2011-07-14 18:09:22 -0700202 public static final int BandwidthControl = 601;
Haoyu Bai6b7358d2012-07-17 16:36:50 -0700203 public static final int InterfaceClassActivity = 613;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900204 public static final int InterfaceAddressChange = 614;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900205 public static final int InterfaceDnsServerInfo = 615;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900206 public static final int RouteChange = 616;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800207 public static final int StrictCleartext = 617;
San Mehat873f2142010-01-14 10:25:07 -0800208 }
209
Rebecca Silbersteine2ec94f2016-03-24 13:29:00 -0700210 /**
211 * String indicating a softap command.
212 */
213 static final String SOFT_AP_COMMAND = "softap";
214
215 /**
216 * String passed back to netd connector indicating softap command success.
217 */
218 static final String SOFT_AP_COMMAND_SUCCESS = "Ok";
219
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700220 static final int DAEMON_MSG_MOBILE_CONN_REAL_TIME_INFO = 1;
221
San Mehat873f2142010-01-14 10:25:07 -0800222 /**
223 * Binder context for this service
224 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700225 private final Context mContext;
San Mehat873f2142010-01-14 10:25:07 -0800226
227 /**
228 * connector object for communicating with netd
229 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700230 private final NativeDaemonConnector mConnector;
San Mehat873f2142010-01-14 10:25:07 -0800231
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700232 private final Handler mFgHandler;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700233 private final Handler mDaemonHandler;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700234
Lorenzo Colittia0868002017-07-11 02:29:28 +0900235 private final SystemServices mServices;
236
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900237 private INetd mNetdService;
238
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800239 private IBatteryStats mBatteryStats;
240
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700241 private final Thread mThread;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700242 private CountDownLatch mConnectedSignal = new CountDownLatch(1);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700243
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800244 private final RemoteCallbackList<INetworkManagementEventObserver> mObservers =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700245 new RemoteCallbackList<>();
San Mehat4d02d002010-01-22 16:07:46 -0800246
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700247 private final NetworkStatsFactory mStatsFactory = new NetworkStatsFactory();
248
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900249 @GuardedBy("mTetheringStatsProviders")
250 private final HashMap<ITetheringStatsProvider, String>
251 mTetheringStatsProviders = Maps.newHashMap();
252
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700253 /**
254 * If both locks need to be held, then they should be obtained in the order:
255 * first {@link #mQuotaLock} and then {@link #mRulesLock}.
256 */
Andrew Scull45f533c2017-05-19 15:37:20 +0100257 private final Object mQuotaLock = new Object();
Andrew Scull519291f2017-05-23 13:11:03 +0100258 private final Object mRulesLock = new Object();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800259
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700260 /** Set of interfaces with active quotas. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800261 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700262 private HashMap<String, Long> mActiveQuotas = Maps.newHashMap();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700263 /** Set of interfaces with active alerts. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800264 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700265 private HashMap<String, Long> mActiveAlerts = Maps.newHashMap();
Felipe Leme65be3022016-03-22 14:53:13 -0700266 /** Set of UIDs blacklisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700267 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700268 private SparseBooleanArray mUidRejectOnMetered = new SparseBooleanArray();
269 /** Set of UIDs whitelisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700270 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700271 private SparseBooleanArray mUidAllowOnMetered = new SparseBooleanArray();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800272 /** Set of UIDs with cleartext penalties. */
273 @GuardedBy("mQuotaLock")
274 private SparseIntArray mUidCleartextPolicy = new SparseIntArray();
Amith Yamasani15e472352015-04-24 19:06:07 -0700275 /** Set of UIDs that are to be blocked/allowed by firewall controller. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700276 @GuardedBy("mRulesLock")
Amith Yamasani15e472352015-04-24 19:06:07 -0700277 private SparseIntArray mUidFirewallRules = new SparseIntArray();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700278 /**
279 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
280 * to application idles.
281 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700282 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700283 private SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
284 /**
285 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
286 * to device idles.
287 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700288 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700289 private SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800290 /**
291 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
292 * to device on power-save mode.
293 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700294 @GuardedBy("mRulesLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800295 private SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700296 /** Set of states for the child firewall chains. True if the chain is active. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700297 @GuardedBy("mRulesLock")
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700298 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700299
Felipe Leme65be3022016-03-22 14:53:13 -0700300 @GuardedBy("mQuotaLock")
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700301 private volatile boolean mDataSaverMode;
Felipe Leme65be3022016-03-22 14:53:13 -0700302
Andrew Scull45f533c2017-05-19 15:37:20 +0100303 private final Object mIdleTimerLock = new Object();
Haoyu Bai04124232012-06-28 15:26:19 -0700304 /** Set of interfaces with active idle timers. */
305 private static class IdleTimerParams {
306 public final int timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800307 public final int type;
Haoyu Bai04124232012-06-28 15:26:19 -0700308 public int networkCount;
309
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800310 IdleTimerParams(int timeout, int type) {
Haoyu Bai04124232012-06-28 15:26:19 -0700311 this.timeout = timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800312 this.type = type;
Haoyu Bai04124232012-06-28 15:26:19 -0700313 this.networkCount = 1;
314 }
315 }
316 private HashMap<String, IdleTimerParams> mActiveIdleTimers = Maps.newHashMap();
317
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700318 private volatile boolean mFirewallEnabled;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800319 private volatile boolean mStrictEnabled;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700320
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700321 private boolean mMobileActivityFromRadio = false;
322 private int mLastPowerStateFromRadio = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Adam Lesinskie08af192015-03-25 16:42:59 -0700323 private int mLastPowerStateFromWifi = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700324
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800325 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700326 new RemoteCallbackList<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800327 private boolean mNetworkActive;
328
San Mehat873f2142010-01-14 10:25:07 -0800329 /**
330 * Constructs a new NetworkManagementService instance
331 *
332 * @param context Binder context for this service
333 */
Lorenzo Colittia0868002017-07-11 02:29:28 +0900334 private NetworkManagementService(
335 Context context, String socket, SystemServices services) {
San Mehat873f2142010-01-14 10:25:07 -0800336 mContext = context;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900337 mServices = services;
San Mehat4d02d002010-01-22 16:07:46 -0800338
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700339 // make sure this is on the same looper as our NativeDaemonConnector for sync purposes
340 mFgHandler = new Handler(FgThread.get().getLooper());
341
Dianne Hackborn4590e522014-03-24 13:36:46 -0700342 // Don't need this wake lock, since we now have a time stamp for when
343 // the network actually went inactive. (It might be nice to still do this,
344 // but I don't want to do it through the power manager because that pollutes the
345 // battery stats history with pointless noise.)
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700346 //PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
Dianne Hackborn4590e522014-03-24 13:36:46 -0700347 PowerManager.WakeLock wl = null; //pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NETD_TAG);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800348
San Mehat873f2142010-01-14 10:25:07 -0800349 mConnector = new NativeDaemonConnector(
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700350 new NetdCallbackReceiver(), socket, 10, NETD_TAG, 160, wl,
351 FgThread.get().getLooper());
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700352 mThread = new Thread(mConnector, NETD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700353
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700354 mDaemonHandler = new Handler(FgThread.get().getLooper());
Wink Saville67e07892014-06-18 16:43:14 -0700355
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700356 // Add ourself to the Watchdog monitors.
357 Watchdog.getInstance().addMonitor(this);
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700358
Lorenzo Colittia0868002017-07-11 02:29:28 +0900359 mServices.registerLocalService(new LocalService());
Lorenzo Colitti8228eb32017-07-19 06:17:33 +0900360
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900361 synchronized (mTetheringStatsProviders) {
362 mTetheringStatsProviders.put(new NetdTetheringStatsProvider(), "netd");
363 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700364 }
365
366 @VisibleForTesting
367 NetworkManagementService() {
368 mConnector = null;
369 mContext = null;
370 mDaemonHandler = null;
371 mFgHandler = null;
372 mThread = null;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900373 mServices = null;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700374 }
375
Lorenzo Colittia0868002017-07-11 02:29:28 +0900376 static NetworkManagementService create(Context context, String socket, SystemServices services)
Felipe Leme03e689d2016-03-02 16:17:38 -0800377 throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900378 final NetworkManagementService service =
379 new NetworkManagementService(context, socket, services);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700380 final CountDownLatch connectedSignal = service.mConnectedSignal;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700381 if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
382 service.mThread.start();
383 if (DBG) Slog.d(TAG, "Awaiting socket connection");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700384 connectedSignal.await();
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700385 if (DBG) Slog.d(TAG, "Connected");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900386 if (DBG) Slog.d(TAG, "Connecting native netd service");
bohu07cc3bb2016-05-03 15:58:01 -0700387 service.connectNativeNetdService();
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900388 if (DBG) Slog.d(TAG, "Connected");
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700389 return service;
San Mehat873f2142010-01-14 10:25:07 -0800390 }
391
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900392 public static NetworkManagementService create(Context context) throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900393 return create(context, NETD_SERVICE_NAME, new SystemServices());
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900394 }
395
Jeff Sharkey350083e2011-06-29 10:45:16 -0700396 public void systemReady() {
Felipe Leme03e689d2016-03-02 16:17:38 -0800397 if (DBG) {
398 final long start = System.currentTimeMillis();
399 prepareNativeDaemon();
400 final long delta = System.currentTimeMillis() - start;
401 Slog.d(TAG, "Prepared in " + delta + "ms");
402 return;
403 } else {
404 prepareNativeDaemon();
405 }
Jeff Sharkey350083e2011-06-29 10:45:16 -0700406 }
407
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800408 private IBatteryStats getBatteryStats() {
409 synchronized (this) {
410 if (mBatteryStats != null) {
411 return mBatteryStats;
412 }
Lorenzo Colittia0868002017-07-11 02:29:28 +0900413 mBatteryStats =
414 IBatteryStats.Stub.asInterface(mServices.getService(BatteryStats.SERVICE_NAME));
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800415 return mBatteryStats;
416 }
417 }
418
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800419 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800420 public void registerObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800421 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800422 mObservers.register(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800423 }
424
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800425 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800426 public void unregisterObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800427 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800428 mObservers.unregister(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800429 }
430
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900431 @FunctionalInterface
432 private interface NetworkManagementEventCallback {
433 public void sendCallback(INetworkManagementEventObserver o) throws RemoteException;
434 }
435
436 private void invokeForAllObservers(NetworkManagementEventCallback eventCallback) {
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800437 final int length = mObservers.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700438 try {
439 for (int i = 0; i < length; i++) {
440 try {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900441 eventCallback.sendCallback(mObservers.getBroadcastItem(i));
Felipe Leme03e689d2016-03-02 16:17:38 -0800442 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700443 }
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700444 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700445 } finally {
446 mObservers.finishBroadcast();
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700447 }
448 }
449
450 /**
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900451 * Notify our observers of an interface status change
452 */
453 private void notifyInterfaceStatusChanged(String iface, boolean up) {
454 invokeForAllObservers(o -> o.interfaceStatusChanged(iface, up));
455 }
456
457 /**
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700458 * Notify our observers of an interface link state change
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700459 * (typically, an Ethernet cable has been plugged-in or unplugged).
460 */
461 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900462 invokeForAllObservers(o -> o.interfaceLinkStateChanged(iface, up));
San Mehat4d02d002010-01-22 16:07:46 -0800463 }
464
465 /**
466 * Notify our observers of an interface addition.
467 */
468 private void notifyInterfaceAdded(String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900469 invokeForAllObservers(o -> o.interfaceAdded(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800470 }
471
472 /**
473 * Notify our observers of an interface removal.
474 */
475 private void notifyInterfaceRemoved(String iface) {
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700476 // netd already clears out quota and alerts for removed ifaces; update
477 // our sanity-checking state.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700478 mActiveAlerts.remove(iface);
479 mActiveQuotas.remove(iface);
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700480
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900481 invokeForAllObservers(o -> o.interfaceRemoved(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800482 }
483
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700484 /**
JP Abgrall12b933d2011-07-14 18:09:22 -0700485 * Notify our observers of a limit reached.
486 */
487 private void notifyLimitReached(String limitName, String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900488 invokeForAllObservers(o -> o.limitReached(limitName, iface));
JP Abgrall12b933d2011-07-14 18:09:22 -0700489 }
490
491 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700492 * Notify our observers of a change in the data activity state of the interface
493 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700494 private void notifyInterfaceClassActivity(int type, int powerState, long tsNanos,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700495 int uid, boolean fromRadio) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700496 final boolean isMobile = ConnectivityManager.isNetworkTypeMobile(type);
497 if (isMobile) {
498 if (!fromRadio) {
499 if (mMobileActivityFromRadio) {
500 // If this call is not coming from a report from the radio itself, but we
501 // have previously received reports from the radio, then we will take the
502 // power state to just be whatever the radio last reported.
503 powerState = mLastPowerStateFromRadio;
504 }
505 } else {
506 mMobileActivityFromRadio = true;
507 }
508 if (mLastPowerStateFromRadio != powerState) {
509 mLastPowerStateFromRadio = powerState;
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700510 try {
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700511 getBatteryStats().noteMobileRadioPowerState(powerState, tsNanos, uid);
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700512 } catch (RemoteException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700513 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700514 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700515 }
516
Adam Lesinskie08af192015-03-25 16:42:59 -0700517 if (ConnectivityManager.isNetworkTypeWifi(type)) {
518 if (mLastPowerStateFromWifi != powerState) {
519 mLastPowerStateFromWifi = powerState;
520 try {
Adam Lesinski5f056f62016-07-14 16:56:08 -0700521 getBatteryStats().noteWifiRadioPowerState(powerState, tsNanos, uid);
Adam Lesinskie08af192015-03-25 16:42:59 -0700522 } catch (RemoteException e) {
523 }
524 }
525 }
526
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700527 boolean isActive = powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
528 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
529
530 if (!isMobile || fromRadio || !mMobileActivityFromRadio) {
531 // Report the change in data activity. We don't do this if this is a change
532 // on the mobile network, that is not coming from the radio itself, and we
533 // have previously seen change reports from the radio. In that case only
534 // the radio is the authority for the current state.
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900535 final boolean active = isActive;
536 invokeForAllObservers(o -> o.interfaceClassDataActivityChanged(
537 Integer.toString(type), active, tsNanos));
Haoyu Baidb3c8672012-06-20 14:29:57 -0700538 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800539
540 boolean report = false;
541 synchronized (mIdleTimerLock) {
542 if (mActiveIdleTimers.isEmpty()) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700543 // If there are no idle timers, we are not monitoring activity, so we
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800544 // are always considered active.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700545 isActive = true;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800546 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700547 if (mNetworkActive != isActive) {
548 mNetworkActive = isActive;
549 report = isActive;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800550 }
551 }
552 if (report) {
553 reportNetworkActive();
554 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700555 }
556
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900557 @Override
558 public void registerTetheringStatsProvider(ITetheringStatsProvider provider, String name) {
559 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
560 Preconditions.checkNotNull(provider);
561 synchronized(mTetheringStatsProviders) {
562 mTetheringStatsProviders.put(provider, name);
563 }
564 }
565
566 @Override
567 public void unregisterTetheringStatsProvider(ITetheringStatsProvider provider) {
568 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
569 synchronized(mTetheringStatsProviders) {
570 mTetheringStatsProviders.remove(provider);
571 }
572 }
573
Lorenzo Colitti9f0baa92017-08-15 19:25:51 +0900574 @Override
575 public void tetherLimitReached(ITetheringStatsProvider provider) {
576 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
577 synchronized(mTetheringStatsProviders) {
578 if (!mTetheringStatsProviders.containsKey(provider)) {
579 return;
580 }
581 // No current code examines the interface parameter in a global alert. Just pass null.
582 notifyLimitReached(LIMIT_GLOBAL_ALERT, null);
583 }
584 }
585
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900586 // Sync the state of the given chain with the native daemon.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700587 private void syncFirewallChainLocked(int chain, String name) {
588 SparseIntArray rules;
589 synchronized (mRulesLock) {
590 final SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900591 // Make a copy of the current rules, and then clear them. This is because
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700592 // setFirewallUidRuleInternal only pushes down rules to the native daemon if they
593 // are different from the current rules stored in the mUidFirewall*Rules array for
594 // the specified chain. If we don't clear the rules, setFirewallUidRuleInternal
595 // will do nothing.
596 rules = uidFirewallRules.clone();
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900597 uidFirewallRules.clear();
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700598 }
599 if (rules.size() > 0) {
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900600 // Now push the rules. setFirewallUidRuleInternal will push each of these down to the
601 // native daemon, and also add them to the mUidFirewall*Rules array for the specified
602 // chain.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700603 if (DBG) Slog.d(TAG, "Pushing " + rules.size() + " active firewall "
604 + name + "UID rules");
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900605 for (int i = 0; i < rules.size(); i++) {
Felipe Lemea701cad2016-05-12 09:58:14 -0700606 setFirewallUidRuleLocked(chain, rules.keyAt(i), rules.valueAt(i));
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900607 }
608 }
609 }
610
bohu07cc3bb2016-05-03 15:58:01 -0700611 private void connectNativeNetdService() {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900612 mNetdService = mServices.getNetd();
bohu07cc3bb2016-05-03 15:58:01 -0700613 }
614
615 /**
616 * Prepare native daemon once connected, enabling modules and pushing any
617 * existing in-memory rules.
618 */
619 private void prepareNativeDaemon() {
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900620
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700621 // push any existing quota or UID rules
622 synchronized (mQuotaLock) {
Felipe Leme65be3022016-03-22 14:53:13 -0700623
Luke Huang56a03a02018-09-07 12:02:16 +0800624 // Netd unconditionally enable bandwidth control
625 SystemProperties.set(PROP_QTAGUID_ENABLED, "1");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900626
Luke Huang473eb872018-07-26 17:33:14 +0800627 mStrictEnabled = true;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900628
Felipe Leme65be3022016-03-22 14:53:13 -0700629 setDataSaverModeEnabled(mDataSaverMode);
630
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700631 int size = mActiveQuotas.size();
632 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800633 if (DBG) Slog.d(TAG, "Pushing " + size + " active quota rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700634 final HashMap<String, Long> activeQuotas = mActiveQuotas;
635 mActiveQuotas = Maps.newHashMap();
636 for (Map.Entry<String, Long> entry : activeQuotas.entrySet()) {
637 setInterfaceQuota(entry.getKey(), entry.getValue());
638 }
639 }
640
641 size = mActiveAlerts.size();
642 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800643 if (DBG) Slog.d(TAG, "Pushing " + size + " active alert rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700644 final HashMap<String, Long> activeAlerts = mActiveAlerts;
645 mActiveAlerts = Maps.newHashMap();
646 for (Map.Entry<String, Long> entry : activeAlerts.entrySet()) {
647 setInterfaceAlert(entry.getKey(), entry.getValue());
648 }
649 }
650
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700651 SparseBooleanArray uidRejectOnQuota = null;
652 SparseBooleanArray uidAcceptOnQuota = null;
653 synchronized (mRulesLock) {
654 size = mUidRejectOnMetered.size();
655 if (size > 0) {
656 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered blacklist rules");
657 uidRejectOnQuota = mUidRejectOnMetered;
658 mUidRejectOnMetered = new SparseBooleanArray();
659 }
660
661 size = mUidAllowOnMetered.size();
662 if (size > 0) {
663 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered whitelist rules");
664 uidAcceptOnQuota = mUidAllowOnMetered;
665 mUidAllowOnMetered = new SparseBooleanArray();
666 }
667 }
668 if (uidRejectOnQuota != null) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700669 for (int i = 0; i < uidRejectOnQuota.size(); i++) {
Felipe Leme65be3022016-03-22 14:53:13 -0700670 setUidMeteredNetworkBlacklist(uidRejectOnQuota.keyAt(i),
671 uidRejectOnQuota.valueAt(i));
672 }
673 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700674 if (uidAcceptOnQuota != null) {
Felipe Leme65be3022016-03-22 14:53:13 -0700675 for (int i = 0; i < uidAcceptOnQuota.size(); i++) {
676 setUidMeteredNetworkWhitelist(uidAcceptOnQuota.keyAt(i),
677 uidAcceptOnQuota.valueAt(i));
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700678 }
679 }
Jeff Sharkey605eb792014-11-04 13:34:06 -0800680
681 size = mUidCleartextPolicy.size();
682 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800683 if (DBG) Slog.d(TAG, "Pushing " + size + " active UID cleartext policies");
Jeff Sharkey605eb792014-11-04 13:34:06 -0800684 final SparseIntArray local = mUidCleartextPolicy;
685 mUidCleartextPolicy = new SparseIntArray();
686 for (int i = 0; i < local.size(); i++) {
687 setUidCleartextNetworkPolicy(local.keyAt(i), local.valueAt(i));
688 }
689 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700690
Robin Leec3736bc2017-03-10 16:19:54 +0000691 setFirewallEnabled(mFirewallEnabled);
Amith Yamasani15e472352015-04-24 19:06:07 -0700692
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700693 syncFirewallChainLocked(FIREWALL_CHAIN_NONE, "");
694 syncFirewallChainLocked(FIREWALL_CHAIN_STANDBY, "standby ");
695 syncFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, "dozable ");
696 syncFirewallChainLocked(FIREWALL_CHAIN_POWERSAVE, "powersave ");
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700697
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700698 final int[] chains =
699 {FIREWALL_CHAIN_STANDBY, FIREWALL_CHAIN_DOZABLE, FIREWALL_CHAIN_POWERSAVE};
700 for (int chain : chains) {
701 if (getFirewallChainState(chain)) {
702 setFirewallChainEnabled(chain, true);
703 }
Felipe Leme011b98f2016-02-10 17:28:31 -0800704 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700705 }
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900706
Luke Huang56a03a02018-09-07 12:02:16 +0800707
708 try {
709 getBatteryStats().noteNetworkStatsEnabled();
710 } catch (RemoteException e) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900711 }
712
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700713 }
San Mehat4d02d002010-01-22 16:07:46 -0800714
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900715 /**
716 * Notify our observers of a new or updated interface address.
717 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900718 private void notifyAddressUpdated(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900719 invokeForAllObservers(o -> o.addressUpdated(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900720 }
721
722 /**
723 * Notify our observers of a deleted interface address.
724 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900725 private void notifyAddressRemoved(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900726 invokeForAllObservers(o -> o.addressRemoved(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900727 }
728
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900729 /**
730 * Notify our observers of DNS server information received.
731 */
732 private void notifyInterfaceDnsServerInfo(String iface, long lifetime, String[] addresses) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900733 invokeForAllObservers(o -> o.interfaceDnsServerInfo(iface, lifetime, addresses));
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900734 }
735
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900736 /**
737 * Notify our observers of a route change.
738 */
739 private void notifyRouteChange(String action, RouteInfo route) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900740 if (action.equals("updated")) {
741 invokeForAllObservers(o -> o.routeUpdated(route));
742 } else {
743 invokeForAllObservers(o -> o.routeRemoved(route));
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900744 }
745 }
746
San Mehat873f2142010-01-14 10:25:07 -0800747 //
748 // Netd Callback handling
749 //
750
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700751 private class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
752 @Override
San Mehat873f2142010-01-14 10:25:07 -0800753 public void onDaemonConnected() {
Felipe Leme65be3022016-03-22 14:53:13 -0700754 Slog.i(TAG, "onDaemonConnected()");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700755 // event is dispatched from internal NDC thread, so we prepare the
756 // daemon back on main thread.
757 if (mConnectedSignal != null) {
bohu07cc3bb2016-05-03 15:58:01 -0700758 // The system is booting and we're connecting to netd for the first time.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700759 mConnectedSignal.countDown();
760 mConnectedSignal = null;
761 } else {
bohu07cc3bb2016-05-03 15:58:01 -0700762 // We're reconnecting to netd after the socket connection
763 // was interrupted (e.g., if it crashed).
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700764 mFgHandler.post(new Runnable() {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700765 @Override
766 public void run() {
bohu07cc3bb2016-05-03 15:58:01 -0700767 connectNativeNetdService();
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700768 prepareNativeDaemon();
769 }
770 });
771 }
San Mehat873f2142010-01-14 10:25:07 -0800772 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700773
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700774 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800775 public boolean onCheckHoldWakeLock(int code) {
776 return code == NetdResponseCode.InterfaceClassActivity;
777 }
778
779 @Override
San Mehat873f2142010-01-14 10:25:07 -0800780 public boolean onEvent(int code, String raw, String[] cooked) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900781 String errorMessage = String.format("Invalid event from daemon (%s)", raw);
JP Abgrall12b933d2011-07-14 18:09:22 -0700782 switch (code) {
783 case NetdResponseCode.InterfaceChange:
784 /*
785 * a network interface change occured
786 * Format: "NNN Iface added <name>"
787 * "NNN Iface removed <name>"
788 * "NNN Iface changed <name> <up/down>"
789 * "NNN Iface linkstatus <name> <up/down>"
790 */
791 if (cooked.length < 4 || !cooked[1].equals("Iface")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900792 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700793 }
794 if (cooked[2].equals("added")) {
795 notifyInterfaceAdded(cooked[3]);
796 return true;
797 } else if (cooked[2].equals("removed")) {
798 notifyInterfaceRemoved(cooked[3]);
799 return true;
800 } else if (cooked[2].equals("changed") && cooked.length == 5) {
801 notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
802 return true;
803 } else if (cooked[2].equals("linkstate") && cooked.length == 5) {
804 notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
805 return true;
806 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900807 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700808 // break;
809 case NetdResponseCode.BandwidthControl:
810 /*
811 * Bandwidth control needs some attention
812 * Format: "NNN limit alert <alertName> <ifaceName>"
813 */
814 if (cooked.length < 5 || !cooked[1].equals("limit")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900815 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700816 }
817 if (cooked[2].equals("alert")) {
818 notifyLimitReached(cooked[3], cooked[4]);
819 return true;
820 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900821 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700822 // break;
Haoyu Baidb3c8672012-06-20 14:29:57 -0700823 case NetdResponseCode.InterfaceClassActivity:
824 /*
825 * An network interface class state changed (active/idle)
826 * Format: "NNN IfaceClass <active/idle> <label>"
827 */
828 if (cooked.length < 4 || !cooked[1].equals("IfaceClass")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900829 throw new IllegalStateException(errorMessage);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700830 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700831 long timestampNanos = 0;
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700832 int processUid = -1;
833 if (cooked.length >= 5) {
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700834 try {
835 timestampNanos = Long.parseLong(cooked[4]);
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700836 if (cooked.length == 6) {
837 processUid = Integer.parseInt(cooked[5]);
838 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700839 } catch(NumberFormatException ne) {}
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700840 } else {
841 timestampNanos = SystemClock.elapsedRealtimeNanos();
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700842 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700843 boolean isActive = cooked[2].equals("active");
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700844 notifyInterfaceClassActivity(Integer.parseInt(cooked[3]),
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700845 isActive ? DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700846 : DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
847 timestampNanos, processUid, false);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700848 return true;
849 // break;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900850 case NetdResponseCode.InterfaceAddressChange:
851 /*
852 * A network address change occurred
853 * Format: "NNN Address updated <addr> <iface> <flags> <scope>"
854 * "NNN Address removed <addr> <iface> <flags> <scope>"
855 */
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900856 if (cooked.length < 7 || !cooked[1].equals("Address")) {
857 throw new IllegalStateException(errorMessage);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900858 }
859
Lorenzo Colitti64483942013-11-15 18:43:52 +0900860 String iface = cooked[4];
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900861 LinkAddress address;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900862 try {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900863 int flags = Integer.parseInt(cooked[5]);
864 int scope = Integer.parseInt(cooked[6]);
865 address = new LinkAddress(cooked[3], flags, scope);
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900866 } catch(NumberFormatException e) { // Non-numeric lifetime or scope.
867 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti64483942013-11-15 18:43:52 +0900868 } catch(IllegalArgumentException e) { // Malformed/invalid IP address.
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900869 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900870 }
871
872 if (cooked[2].equals("updated")) {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900873 notifyAddressUpdated(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900874 } else {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900875 notifyAddressRemoved(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900876 }
877 return true;
878 // break;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900879 case NetdResponseCode.InterfaceDnsServerInfo:
880 /*
881 * Information about available DNS servers has been received.
882 * Format: "NNN DnsInfo servers <interface> <lifetime> <servers>"
883 */
884 long lifetime; // Actually a 32-bit unsigned integer.
885
886 if (cooked.length == 6 &&
887 cooked[1].equals("DnsInfo") &&
888 cooked[2].equals("servers")) {
889 try {
890 lifetime = Long.parseLong(cooked[4]);
891 } catch (NumberFormatException e) {
892 throw new IllegalStateException(errorMessage);
893 }
894 String[] servers = cooked[5].split(",");
895 notifyInterfaceDnsServerInfo(cooked[3], lifetime, servers);
896 }
897 return true;
898 // break;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900899 case NetdResponseCode.RouteChange:
900 /*
901 * A route has been updated or removed.
902 * Format: "NNN Route <updated|removed> <dst> [via <gateway] [dev <iface>]"
903 */
904 if (!cooked[1].equals("Route") || cooked.length < 6) {
905 throw new IllegalStateException(errorMessage);
906 }
907
908 String via = null;
909 String dev = null;
910 boolean valid = true;
911 for (int i = 4; (i + 1) < cooked.length && valid; i += 2) {
912 if (cooked[i].equals("dev")) {
913 if (dev == null) {
914 dev = cooked[i+1];
915 } else {
916 valid = false; // Duplicate interface.
917 }
918 } else if (cooked[i].equals("via")) {
919 if (via == null) {
920 via = cooked[i+1];
921 } else {
922 valid = false; // Duplicate gateway.
923 }
924 } else {
925 valid = false; // Unknown syntax.
926 }
927 }
928 if (valid) {
929 try {
930 // InetAddress.parseNumericAddress(null) inexplicably returns ::1.
931 InetAddress gateway = null;
932 if (via != null) gateway = InetAddress.parseNumericAddress(via);
933 RouteInfo route = new RouteInfo(new IpPrefix(cooked[3]), gateway, dev);
934 notifyRouteChange(cooked[2], route);
935 return true;
936 } catch (IllegalArgumentException e) {}
937 }
938 throw new IllegalStateException(errorMessage);
939 // break;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800940 case NetdResponseCode.StrictCleartext:
941 final int uid = Integer.parseInt(cooked[1]);
942 final byte[] firstPacket = HexDump.hexStringToByteArray(cooked[2]);
943 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800944 ActivityManager.getService().notifyCleartextNetwork(uid, firstPacket);
Jeff Sharkey605eb792014-11-04 13:34:06 -0800945 } catch (RemoteException ignored) {
946 }
947 break;
JP Abgrall12b933d2011-07-14 18:09:22 -0700948 default: break;
Robert Greenwalte3253922010-02-18 09:23:25 -0800949 }
950 return false;
San Mehat873f2142010-01-14 10:25:07 -0800951 }
952 }
953
San Mehated4fc8a2010-01-22 12:28:36 -0800954
San Mehat873f2142010-01-14 10:25:07 -0800955 //
956 // INetworkManagementService members
957 //
Erik Kline4e37b702016-07-05 11:34:21 +0900958 @Override
959 public INetd getNetdService() throws RemoteException {
960 final CountDownLatch connectedSignal = mConnectedSignal;
961 if (connectedSignal != null) {
962 try {
963 connectedSignal.await();
964 } catch (InterruptedException ignored) {}
965 }
966
967 return mNetdService;
968 }
San Mehat873f2142010-01-14 10:25:07 -0800969
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800970 @Override
971 public String[] listInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800972 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700973 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800974 return NativeDaemonEvent.filterMessageList(
975 mConnector.executeForList("interface", "list"), InterfaceListResult);
Kenny Roota80ce062010-06-01 13:23:53 -0700976 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800977 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700978 }
San Mehated4fc8a2010-01-22 12:28:36 -0800979 }
980
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800981 @Override
982 public InterfaceConfiguration getInterfaceConfig(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800983 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800984
985 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -0700986 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800987 event = mConnector.execute("interface", "getcfg", iface);
Kenny Roota80ce062010-06-01 13:23:53 -0700988 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800989 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700990 }
San Mehated4fc8a2010-01-22 12:28:36 -0800991
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800992 event.checkCode(InterfaceGetCfgResult);
993
994 // Rsp: 213 xx:xx:xx:xx:xx:xx yyy.yyy.yyy.yyy zzz flag1 flag2 flag3
995 final StringTokenizer st = new StringTokenizer(event.getMessage());
San Mehated4fc8a2010-01-22 12:28:36 -0800996
Kenny Roota80ce062010-06-01 13:23:53 -0700997 InterfaceConfiguration cfg;
San Mehated4fc8a2010-01-22 12:28:36 -0800998 try {
Kenny Roota80ce062010-06-01 13:23:53 -0700999 cfg = new InterfaceConfiguration();
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001000 cfg.setHardwareAddress(st.nextToken(" "));
Robert Greenwalted126402011-01-28 15:34:55 -08001001 InetAddress addr = null;
Robert Greenwalt2d2afd12011-02-01 15:30:46 -08001002 int prefixLength = 0;
Kenny Roota80ce062010-06-01 13:23:53 -07001003 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001004 addr = NetworkUtils.numericToInetAddress(st.nextToken());
Robert Greenwalte5903732011-02-22 16:00:42 -08001005 } catch (IllegalArgumentException iae) {
1006 Slog.e(TAG, "Failed to parse ipaddr", iae);
Kenny Roota80ce062010-06-01 13:23:53 -07001007 }
1008
1009 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001010 prefixLength = Integer.parseInt(st.nextToken());
Robert Greenwalt2d2afd12011-02-01 15:30:46 -08001011 } catch (NumberFormatException nfe) {
1012 Slog.e(TAG, "Failed to parse prefixLength", nfe);
Kenny Roota80ce062010-06-01 13:23:53 -07001013 }
Robert Greenwalt04808c22010-12-13 17:01:41 -08001014
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001015 cfg.setLinkAddress(new LinkAddress(addr, prefixLength));
1016 while (st.hasMoreTokens()) {
1017 cfg.setFlag(st.nextToken());
1018 }
Kenny Roota80ce062010-06-01 13:23:53 -07001019 } catch (NoSuchElementException nsee) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001020 throw new IllegalStateException("Invalid response from daemon: " + event);
San Mehated4fc8a2010-01-22 12:28:36 -08001021 }
San Mehated4fc8a2010-01-22 12:28:36 -08001022 return cfg;
1023 }
1024
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001025 @Override
1026 public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001027 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001028 LinkAddress linkAddr = cfg.getLinkAddress();
Robert Greenwalt2d2afd12011-02-01 15:30:46 -08001029 if (linkAddr == null || linkAddr.getAddress() == null) {
1030 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -08001031 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001032
1033 final Command cmd = new Command("interface", "setcfg", iface,
Robert Greenwalt2d2afd12011-02-01 15:30:46 -08001034 linkAddr.getAddress().getHostAddress(),
Lorenzo Colitti7dc78cf2014-06-09 22:58:46 +09001035 linkAddr.getPrefixLength());
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001036 for (String flag : cfg.getFlags()) {
1037 cmd.appendArg(flag);
1038 }
1039
Kenny Roota80ce062010-06-01 13:23:53 -07001040 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001041 mConnector.execute(cmd);
Kenny Roota80ce062010-06-01 13:23:53 -07001042 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001043 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001044 }
San Mehat873f2142010-01-14 10:25:07 -08001045 }
1046
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001047 @Override
1048 public void setInterfaceDown(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001049 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001050 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001051 ifcg.setInterfaceDown();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001052 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001053 }
1054
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001055 @Override
1056 public void setInterfaceUp(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001057 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001058 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001059 ifcg.setInterfaceUp();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001060 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001061 }
1062
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001063 @Override
1064 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001065 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sheriff73293612011-09-14 12:31:56 -07001066 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001067 mConnector.execute(
1068 "interface", "ipv6privacyextensions", iface, enable ? "enable" : "disable");
Irfan Sheriff73293612011-09-14 12:31:56 -07001069 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001070 throw e.rethrowAsParcelableException();
Irfan Sheriff73293612011-09-14 12:31:56 -07001071 }
1072 }
1073
Irfan Sherifff5600612011-06-16 10:26:28 -07001074 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
1075 IPv6 addresses on interface down, but we need to do full clean up here */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001076 @Override
1077 public void clearInterfaceAddresses(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001078 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sherifff5600612011-06-16 10:26:28 -07001079 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001080 mConnector.execute("interface", "clearaddrs", iface);
Irfan Sherifff5600612011-06-16 10:26:28 -07001081 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001082 throw e.rethrowAsParcelableException();
Irfan Sherifff5600612011-06-16 10:26:28 -07001083 }
1084 }
1085
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001086 @Override
1087 public void enableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001088 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001089 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001090 mConnector.execute("interface", "ipv6", iface, "enable");
repo sync7960d9f2011-09-29 12:40:02 -07001091 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001092 throw e.rethrowAsParcelableException();
repo sync7960d9f2011-09-29 12:40:02 -07001093 }
1094 }
1095
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001096 @Override
Joel Scherpelz2db10742017-06-07 15:38:38 +09001097 public void setIPv6AddrGenMode(String iface, int mode) throws ServiceSpecificException {
1098 try {
1099 mNetdService.setIPv6AddrGenMode(iface, mode);
1100 } catch (RemoteException e) {
1101 throw e.rethrowAsRuntimeException();
1102 }
1103 }
1104
1105 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001106 public void disableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001107 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001108 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001109 mConnector.execute("interface", "ipv6", iface, "disable");
repo sync7960d9f2011-09-29 12:40:02 -07001110 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001111 throw e.rethrowAsParcelableException();
repo sync7960d9f2011-09-29 12:40:02 -07001112 }
1113 }
1114
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001115 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001116 public void addRoute(int netId, RouteInfo route) {
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07001117 modifyRoute("add", "" + netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001118 }
1119
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001120 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001121 public void removeRoute(int netId, RouteInfo route) {
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07001122 modifyRoute("remove", "" + netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001123 }
1124
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07001125 private void modifyRoute(String action, String netId, RouteInfo route) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001126 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001127
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001128 final Command cmd = new Command("network", "route", action, netId);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001129
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001130 // create triplet: interface dest-ip-addr/prefixlength gateway-ip-addr
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001131 cmd.appendArg(route.getInterface());
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001132 cmd.appendArg(route.getDestination().toString());
1133
1134 switch (route.getType()) {
1135 case RouteInfo.RTN_UNICAST:
1136 if (route.hasGateway()) {
1137 cmd.appendArg(route.getGateway().getHostAddress());
1138 }
1139 break;
1140 case RouteInfo.RTN_UNREACHABLE:
1141 cmd.appendArg("unreachable");
1142 break;
1143 case RouteInfo.RTN_THROW:
1144 cmd.appendArg("throw");
1145 break;
Sreeram Ramachandran1fbcb272014-05-22 16:30:48 -07001146 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001147
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001148 try {
1149 mConnector.execute(cmd);
1150 } catch (NativeDaemonConnectorException e) {
1151 throw e.rethrowAsParcelableException();
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001152 }
1153 }
1154
1155 private ArrayList<String> readRouteList(String filename) {
1156 FileInputStream fstream = null;
Christopher Wiley212b95f2016-08-02 11:38:57 -07001157 ArrayList<String> list = new ArrayList<>();
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001158
1159 try {
1160 fstream = new FileInputStream(filename);
1161 DataInputStream in = new DataInputStream(fstream);
1162 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1163 String s;
1164
1165 // throw away the title line
1166
1167 while (((s = br.readLine()) != null) && (s.length() != 0)) {
1168 list.add(s);
1169 }
1170 } catch (IOException ex) {
1171 // return current list, possibly empty
1172 } finally {
1173 if (fstream != null) {
1174 try {
1175 fstream.close();
1176 } catch (IOException ex) {}
1177 }
1178 }
1179
1180 return list;
1181 }
1182
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001183 @Override
sy.yun9d9b74a2013-09-02 05:24:09 +09001184 public void setMtu(String iface, int mtu) {
1185 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1186
1187 final NativeDaemonEvent event;
1188 try {
1189 event = mConnector.execute("interface", "setmtu", iface, mtu);
1190 } catch (NativeDaemonConnectorException e) {
1191 throw e.rethrowAsParcelableException();
1192 }
1193 }
1194
1195 @Override
San Mehat873f2142010-01-14 10:25:07 -08001196 public void shutdown() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001197 // TODO: remove from aidl if nobody calls externally
1198 mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001199
Felipe Leme03e689d2016-03-02 16:17:38 -08001200 Slog.i(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -08001201 }
1202
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001203 @Override
San Mehat873f2142010-01-14 10:25:07 -08001204 public boolean getIpForwardingEnabled() throws IllegalStateException{
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001205 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001206
Kenny Roota80ce062010-06-01 13:23:53 -07001207 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001208 final boolean isEnabled = mNetdService.ipfwdEnabled();
1209 return isEnabled;
1210 } catch (RemoteException | ServiceSpecificException e) {
1211 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001212 }
San Mehat873f2142010-01-14 10:25:07 -08001213 }
1214
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001215 @Override
1216 public void setIpForwardingEnabled(boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001217 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001218 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001219 if (enable) {
1220 mNetdService.ipfwdEnableForwarding("tethering");
1221 } else {
1222 mNetdService.ipfwdDisableForwarding("tethering");
1223 }
1224 } catch (RemoteException | ServiceSpecificException e) {
1225 throw new IllegalStateException(e);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001226 }
San Mehat873f2142010-01-14 10:25:07 -08001227 }
1228
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001229 @Override
1230 public void startTethering(String[] dhcpRange) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001231 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -07001232 // cmd is "tether start first_start first_stop second_start second_stop ..."
1233 // an odd number of addrs will fail
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001234
1235 final Command cmd = new Command("tether", "start");
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -07001236 for (String d : dhcpRange) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001237 cmd.appendArg(d);
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -07001238 }
Kenny Roota80ce062010-06-01 13:23:53 -07001239
1240 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001241 mConnector.execute(cmd);
Kenny Roota80ce062010-06-01 13:23:53 -07001242 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001243 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001244 }
San Mehat873f2142010-01-14 10:25:07 -08001245 }
1246
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001247 @Override
1248 public void stopTethering() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001249 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001250 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001251 mConnector.execute("tether", "stop");
Kenny Roota80ce062010-06-01 13:23:53 -07001252 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001253 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001254 }
San Mehat873f2142010-01-14 10:25:07 -08001255 }
1256
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001257 @Override
1258 public boolean isTetheringStarted() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001259 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001260
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001261 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -07001262 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001263 event = mConnector.execute("tether", "status");
Kenny Roota80ce062010-06-01 13:23:53 -07001264 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001265 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001266 }
San Mehat873f2142010-01-14 10:25:07 -08001267
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001268 // 210 Tethering services started
1269 event.checkCode(TetherStatusResult);
1270 return event.getMessage().endsWith("started");
San Mehat873f2142010-01-14 10:25:07 -08001271 }
Matthew Xiefe19f122012-07-12 16:03:32 -07001272
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001273 @Override
1274 public void tetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001275 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001276 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001277 mConnector.execute("tether", "interface", "add", iface);
Kenny Roota80ce062010-06-01 13:23:53 -07001278 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001279 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001280 }
Christopher Wiley212b95f2016-08-02 11:38:57 -07001281 List<RouteInfo> routes = new ArrayList<>();
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07001282 // The RouteInfo constructor truncates the LinkAddress to a network prefix, thus making it
1283 // suitable to use as a route destination.
1284 routes.add(new RouteInfo(getInterfaceConfig(iface).getLinkAddress(), null, iface));
1285 addInterfaceToLocalNetwork(iface, routes);
San Mehat873f2142010-01-14 10:25:07 -08001286 }
1287
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001288 @Override
San Mehat873f2142010-01-14 10:25:07 -08001289 public void untetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001290 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001291 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001292 mConnector.execute("tether", "interface", "remove", iface);
Kenny Roota80ce062010-06-01 13:23:53 -07001293 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001294 throw e.rethrowAsParcelableException();
Erik Kline1f4278a2016-08-16 16:46:33 +09001295 } finally {
1296 removeInterfaceFromLocalNetwork(iface);
Kenny Roota80ce062010-06-01 13:23:53 -07001297 }
San Mehat873f2142010-01-14 10:25:07 -08001298 }
1299
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001300 @Override
1301 public String[] listTetheredInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001302 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001303 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001304 return NativeDaemonEvent.filterMessageList(
1305 mConnector.executeForList("tether", "interface", "list"),
1306 TetherInterfaceListResult);
Kenny Roota80ce062010-06-01 13:23:53 -07001307 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001308 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001309 }
San Mehat873f2142010-01-14 10:25:07 -08001310 }
1311
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001312 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001313 public void setDnsForwarders(Network network, String[] dns) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001314 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001315
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001316 int netId = (network != null) ? network.netId : ConnectivityManager.NETID_UNSET;
1317 final Command cmd = new Command("tether", "dns", "set", netId);
1318
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001319 for (String s : dns) {
1320 cmd.appendArg(NetworkUtils.numericToInetAddress(s).getHostAddress());
1321 }
1322
San Mehat873f2142010-01-14 10:25:07 -08001323 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001324 mConnector.execute(cmd);
1325 } catch (NativeDaemonConnectorException e) {
1326 throw e.rethrowAsParcelableException();
San Mehat873f2142010-01-14 10:25:07 -08001327 }
1328 }
1329
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001330 @Override
1331 public String[] getDnsForwarders() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001332 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001333 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001334 return NativeDaemonEvent.filterMessageList(
1335 mConnector.executeForList("tether", "dns", "list"), TetherDnsFwdTgtListResult);
Kenny Roota80ce062010-06-01 13:23:53 -07001336 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001337 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001338 }
San Mehat873f2142010-01-14 10:25:07 -08001339 }
1340
jiaguo1da35f72014-01-09 16:39:59 +08001341 private List<InterfaceAddress> excludeLinkLocal(List<InterfaceAddress> addresses) {
Christopher Wiley212b95f2016-08-02 11:38:57 -07001342 ArrayList<InterfaceAddress> filtered = new ArrayList<>(addresses.size());
jiaguo1da35f72014-01-09 16:39:59 +08001343 for (InterfaceAddress ia : addresses) {
1344 if (!ia.getAddress().isLinkLocalAddress())
1345 filtered.add(ia);
1346 }
1347 return filtered;
1348 }
1349
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001350 private void modifyInterfaceForward(boolean add, String fromIface, String toIface) {
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001351 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001352 if (add) {
1353 mNetdService.ipfwdAddInterfaceForward(fromIface, toIface);
1354 } else {
1355 mNetdService.ipfwdRemoveInterfaceForward(fromIface, toIface);
1356 }
1357 } catch (RemoteException | ServiceSpecificException e) {
1358 throw new IllegalStateException(e);
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001359 }
1360 }
1361
1362 @Override
1363 public void startInterfaceForwarding(String fromIface, String toIface) {
1364 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1365 modifyInterfaceForward(true, fromIface, toIface);
1366 }
1367
1368 @Override
1369 public void stopInterfaceForwarding(String fromIface, String toIface) {
1370 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1371 modifyInterfaceForward(false, fromIface, toIface);
1372 }
1373
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001374 private void modifyNat(String action, String internalInterface, String externalInterface)
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001375 throws SocketException {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001376 final Command cmd = new Command("nat", action, internalInterface, externalInterface);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001377
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001378 final NetworkInterface internalNetworkInterface = NetworkInterface.getByName(
1379 internalInterface);
Robert Greenwalte83d1812011-11-21 14:44:39 -08001380 if (internalNetworkInterface == null) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001381 cmd.appendArg("0");
Robert Greenwalte83d1812011-11-21 14:44:39 -08001382 } else {
jiaguo1da35f72014-01-09 16:39:59 +08001383 // Don't touch link-local routes, as link-local addresses aren't routable,
1384 // kernel creates link-local routes on all interfaces automatically
1385 List<InterfaceAddress> interfaceAddresses = excludeLinkLocal(
1386 internalNetworkInterface.getInterfaceAddresses());
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001387 cmd.appendArg(interfaceAddresses.size());
Robert Greenwalte83d1812011-11-21 14:44:39 -08001388 for (InterfaceAddress ia : interfaceAddresses) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001389 InetAddress addr = NetworkUtils.getNetworkPart(
1390 ia.getAddress(), ia.getNetworkPrefixLength());
1391 cmd.appendArg(addr.getHostAddress() + "/" + ia.getNetworkPrefixLength());
Robert Greenwalte83d1812011-11-21 14:44:39 -08001392 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001393 }
1394
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001395 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001396 mConnector.execute(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001397 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001398 throw e.rethrowAsParcelableException();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001399 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001400 }
1401
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001402 @Override
1403 public void enableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001404 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001405 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001406 modifyNat("enable", internalInterface, externalInterface);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001407 } catch (SocketException e) {
1408 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001409 }
San Mehat873f2142010-01-14 10:25:07 -08001410 }
1411
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001412 @Override
1413 public void disableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001414 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001415 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001416 modifyNat("disable", internalInterface, externalInterface);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001417 } catch (SocketException e) {
1418 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001419 }
San Mehat873f2142010-01-14 10:25:07 -08001420 }
San Mehat72759df2010-01-19 13:50:37 -08001421
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001422 @Override
1423 public String[] listTtys() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001424 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001425 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001426 return NativeDaemonEvent.filterMessageList(
1427 mConnector.executeForList("list_ttys"), TtyListResult);
Kenny Roota80ce062010-06-01 13:23:53 -07001428 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001429 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001430 }
San Mehat72759df2010-01-19 13:50:37 -08001431 }
1432
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001433 @Override
1434 public void attachPppd(
1435 String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001436 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat72759df2010-01-19 13:50:37 -08001437 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001438 mConnector.execute("pppd", "attach", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -08001439 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
1440 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
1441 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001442 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress());
Kenny Roota80ce062010-06-01 13:23:53 -07001443 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001444 throw e.rethrowAsParcelableException();
San Mehat72759df2010-01-19 13:50:37 -08001445 }
1446 }
1447
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001448 @Override
1449 public void detachPppd(String tty) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001450 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001451 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001452 mConnector.execute("pppd", "detach", tty);
Kenny Roota80ce062010-06-01 13:23:53 -07001453 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001454 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001455 }
San Mehat72759df2010-01-19 13:50:37 -08001456 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -08001457
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001458 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001459 public void addIdleTimer(String iface, int timeout, final int type) {
Haoyu Bai04124232012-06-28 15:26:19 -07001460 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1461
1462 if (DBG) Slog.d(TAG, "Adding idletimer");
1463
1464 synchronized (mIdleTimerLock) {
1465 IdleTimerParams params = mActiveIdleTimers.get(iface);
1466 if (params != null) {
1467 // the interface already has idletimer, update network count
1468 params.networkCount++;
1469 return;
1470 }
1471
1472 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001473 mNetdService.idletimerAddInterface(iface, timeout, Integer.toString(type));
1474 } catch (RemoteException | ServiceSpecificException e) {
1475 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001476 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001477 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
1478
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001479 // Networks start up.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001480 if (ConnectivityManager.isNetworkTypeMobile(type)) {
1481 mNetworkActive = false;
1482 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001483 mDaemonHandler.post(new Runnable() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001484 @Override public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001485 notifyInterfaceClassActivity(type,
1486 DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07001487 SystemClock.elapsedRealtimeNanos(), -1, false);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001488 }
1489 });
Haoyu Bai04124232012-06-28 15:26:19 -07001490 }
1491 }
1492
1493 @Override
1494 public void removeIdleTimer(String iface) {
1495 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1496
1497 if (DBG) Slog.d(TAG, "Removing idletimer");
1498
1499 synchronized (mIdleTimerLock) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001500 final IdleTimerParams params = mActiveIdleTimers.get(iface);
Haoyu Bai04124232012-06-28 15:26:19 -07001501 if (params == null || --(params.networkCount) > 0) {
1502 return;
1503 }
1504
1505 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001506 mNetdService.idletimerRemoveInterface(iface,
1507 params.timeout, Integer.toString(params.type));
1508 } catch (RemoteException | ServiceSpecificException e) {
1509 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001510 }
1511 mActiveIdleTimers.remove(iface);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001512 mDaemonHandler.post(new Runnable() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001513 @Override public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001514 notifyInterfaceClassActivity(params.type,
1515 DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07001516 SystemClock.elapsedRealtimeNanos(), -1, false);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001517 }
1518 });
Haoyu Bai04124232012-06-28 15:26:19 -07001519 }
1520 }
1521
1522 @Override
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001523 public NetworkStats getNetworkStatsSummaryDev() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001524 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001525 try {
1526 return mStatsFactory.readNetworkStatsSummaryDev();
1527 } catch (IOException e) {
1528 throw new IllegalStateException(e);
1529 }
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001530 }
1531
1532 @Override
1533 public NetworkStats getNetworkStatsSummaryXt() {
1534 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001535 try {
1536 return mStatsFactory.readNetworkStatsSummaryXt();
1537 } catch (IOException e) {
1538 throw new IllegalStateException(e);
1539 }
Jeff Sharkeyae2c1812011-10-04 13:11:40 -07001540 }
1541
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001542 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001543 public NetworkStats getNetworkStatsDetail() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001544 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001545 try {
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08001546 return mStatsFactory.readNetworkStatsDetail(UID_ALL, null, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001547 } catch (IOException e) {
1548 throw new IllegalStateException(e);
1549 }
San Mehat91cac642010-03-31 14:31:36 -07001550 }
1551
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001552 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001553 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001554 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001555
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001556 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001557 if (mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001558 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001559 }
1560
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001561 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001562 // TODO: support quota shared across interfaces
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001563 mConnector.execute("bandwidth", "setiquota", iface, quotaBytes);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001564 mActiveQuotas.put(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001565 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001566 throw e.rethrowAsParcelableException();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001567 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001568
1569 synchronized (mTetheringStatsProviders) {
1570 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1571 try {
1572 provider.setInterfaceQuota(iface, quotaBytes);
1573 } catch (RemoteException e) {
1574 Log.e(TAG, "Problem setting tethering data limit on provider " +
1575 mTetheringStatsProviders.get(provider) + ": " + e);
1576 }
1577 }
1578 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001579 }
1580 }
1581
1582 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001583 public void removeInterfaceQuota(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001584 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001585
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001586 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001587 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001588 // TODO: eventually consider throwing
1589 return;
1590 }
1591
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001592 mActiveQuotas.remove(iface);
1593 mActiveAlerts.remove(iface);
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001594
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001595 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001596 // TODO: support quota shared across interfaces
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001597 mConnector.execute("bandwidth", "removeiquota", iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001598 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001599 throw e.rethrowAsParcelableException();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001600 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001601
1602 synchronized (mTetheringStatsProviders) {
1603 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1604 try {
1605 provider.setInterfaceQuota(iface, ITetheringStatsProvider.QUOTA_UNLIMITED);
1606 } catch (RemoteException e) {
1607 Log.e(TAG, "Problem removing tethering data limit on provider " +
1608 mTetheringStatsProviders.get(provider) + ": " + e);
1609 }
1610 }
1611 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001612 }
1613 }
1614
1615 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001616 public void setInterfaceAlert(String iface, long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001617 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001618
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001619 // quick sanity check
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001620 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001621 throw new IllegalStateException("setting alert requires existing quota on iface");
1622 }
1623
1624 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001625 if (mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001626 throw new IllegalStateException("iface " + iface + " already has alert");
1627 }
1628
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001629 try {
1630 // TODO: support alert shared across interfaces
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001631 mConnector.execute("bandwidth", "setinterfacealert", iface, alertBytes);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001632 mActiveAlerts.put(iface, alertBytes);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001633 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001634 throw e.rethrowAsParcelableException();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001635 }
1636 }
1637 }
1638
1639 @Override
1640 public void removeInterfaceAlert(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001641 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001642
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001643 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001644 if (!mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001645 // TODO: eventually consider throwing
1646 return;
1647 }
1648
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001649 try {
1650 // TODO: support alert shared across interfaces
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001651 mConnector.execute("bandwidth", "removeinterfacealert", iface);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001652 mActiveAlerts.remove(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001653 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001654 throw e.rethrowAsParcelableException();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001655 }
1656 }
1657 }
1658
1659 @Override
1660 public void setGlobalAlert(long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001661 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001662
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001663 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001664 mConnector.execute("bandwidth", "setglobalalert", alertBytes);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001665 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001666 throw e.rethrowAsParcelableException();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001667 }
1668 }
1669
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001670 private void setUidOnMeteredNetworkList(int uid, boolean blacklist, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001671 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001672
Felipe Leme65be3022016-03-22 14:53:13 -07001673 final String chain = blacklist ? "naughtyapps" : "niceapps";
1674 final String suffix = enable ? "add" : "remove";
1675
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001676 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001677 boolean oldEnable;
1678 SparseBooleanArray quotaList;
1679 synchronized (mRulesLock) {
1680 quotaList = blacklist ? mUidRejectOnMetered : mUidAllowOnMetered;
1681 oldEnable = quotaList.get(uid, false);
1682 }
Felipe Leme65be3022016-03-22 14:53:13 -07001683 if (oldEnable == enable) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001684 // TODO: eventually consider throwing
1685 return;
1686 }
1687
Felipe Leme29e72ea2016-09-08 13:26:55 -07001688 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "inetd bandwidth");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001689 try {
Felipe Leme65be3022016-03-22 14:53:13 -07001690 mConnector.execute("bandwidth", suffix + chain, uid);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001691 synchronized (mRulesLock) {
1692 if (enable) {
1693 quotaList.put(uid, true);
1694 } else {
1695 quotaList.delete(uid);
1696 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001697 }
1698 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001699 throw e.rethrowAsParcelableException();
Felipe Leme29e72ea2016-09-08 13:26:55 -07001700 } finally {
1701 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001702 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001703 }
1704 }
1705
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001706 @Override
Felipe Leme65be3022016-03-22 14:53:13 -07001707 public void setUidMeteredNetworkBlacklist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001708 setUidOnMeteredNetworkList(uid, true, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001709 }
1710
1711 @Override
1712 public void setUidMeteredNetworkWhitelist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001713 setUidOnMeteredNetworkList(uid, false, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001714 }
1715
1716 @Override
1717 public boolean setDataSaverModeEnabled(boolean enable) {
Sehee Parka9139bc2017-12-22 13:54:05 +09001718 mContext.enforceCallingOrSelfPermission(NETWORK_SETTINGS, TAG);
1719
Felipe Leme65be3022016-03-22 14:53:13 -07001720 if (DBG) Log.d(TAG, "setDataSaverMode: " + enable);
1721 synchronized (mQuotaLock) {
1722 if (mDataSaverMode == enable) {
1723 Log.w(TAG, "setDataSaverMode(): already " + mDataSaverMode);
1724 return true;
1725 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07001726 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "bandwidthEnableDataSaver");
Felipe Leme65be3022016-03-22 14:53:13 -07001727 try {
1728 final boolean changed = mNetdService.bandwidthEnableDataSaver(enable);
1729 if (changed) {
1730 mDataSaverMode = enable;
1731 } else {
1732 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command silently failed");
1733 }
1734 return changed;
1735 } catch (RemoteException e) {
1736 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command failed", e);
1737 return false;
Felipe Leme29e72ea2016-09-08 13:26:55 -07001738 } finally {
1739 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme65be3022016-03-22 14:53:13 -07001740 }
1741 }
1742 }
1743
1744 @Override
Robin Lee17e61832016-05-09 13:46:28 +01001745 public void setAllowOnlyVpnForUids(boolean add, UidRange[] uidRanges)
1746 throws ServiceSpecificException {
Rubin Xu2ea6c552018-01-11 10:59:19 +00001747 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
1748
Robin Lee17e61832016-05-09 13:46:28 +01001749 try {
1750 mNetdService.networkRejectNonSecureVpn(add, uidRanges);
1751 } catch (ServiceSpecificException e) {
1752 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1753 + ": netd command failed", e);
1754 throw e;
1755 } catch (RemoteException e) {
1756 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1757 + ": netd command failed", e);
1758 throw e.rethrowAsRuntimeException();
1759 }
1760 }
1761
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001762 private void applyUidCleartextNetworkPolicy(int uid, int policy) {
Luke Huang473eb872018-07-26 17:33:14 +08001763 final int policyValue;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001764 switch (policy) {
1765 case StrictMode.NETWORK_POLICY_ACCEPT:
Luke Huang473eb872018-07-26 17:33:14 +08001766 policyValue = INetd.PENALTY_POLICY_ACCEPT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001767 break;
1768 case StrictMode.NETWORK_POLICY_LOG:
Luke Huang473eb872018-07-26 17:33:14 +08001769 policyValue = INetd.PENALTY_POLICY_LOG;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001770 break;
1771 case StrictMode.NETWORK_POLICY_REJECT:
Luke Huang473eb872018-07-26 17:33:14 +08001772 policyValue = INetd.PENALTY_POLICY_REJECT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001773 break;
1774 default:
1775 throw new IllegalArgumentException("Unknown policy " + policy);
1776 }
1777
1778 try {
Luke Huang473eb872018-07-26 17:33:14 +08001779 mNetdService.strictUidCleartextPenalty(uid, policyValue);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001780 mUidCleartextPolicy.put(uid, policy);
Luke Huang473eb872018-07-26 17:33:14 +08001781 } catch (RemoteException | ServiceSpecificException e) {
1782 throw new IllegalStateException(e);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001783 }
1784 }
1785
Robin Lee17e61832016-05-09 13:46:28 +01001786 @Override
Jeff Sharkey605eb792014-11-04 13:34:06 -08001787 public void setUidCleartextNetworkPolicy(int uid, int policy) {
1788 if (Binder.getCallingUid() != uid) {
1789 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1790 }
1791
1792 synchronized (mQuotaLock) {
1793 final int oldPolicy = mUidCleartextPolicy.get(uid, StrictMode.NETWORK_POLICY_ACCEPT);
1794 if (oldPolicy == policy) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001795 // This also ensures we won't needlessly apply an ACCEPT policy if we've just
1796 // enabled strict and the underlying iptables rules are empty.
Jeff Sharkey605eb792014-11-04 13:34:06 -08001797 return;
1798 }
1799
Luke Huang473eb872018-07-26 17:33:14 +08001800 // TODO: remove this code after removing prepareNativeDaemon()
Jeff Sharkey605eb792014-11-04 13:34:06 -08001801 if (!mStrictEnabled) {
1802 // Module isn't enabled yet; stash the requested policy away to
1803 // apply later once the daemon is connected.
1804 mUidCleartextPolicy.put(uid, policy);
1805 return;
1806 }
1807
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001808 // netd does not keep state on strict mode policies, and cannot replace a non-accept
1809 // policy without deleting it first. Rather than add state to netd, just always send
1810 // it an accept policy when switching between two non-accept policies.
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001811 // TODO: consider keeping state in netd so we can simplify this code.
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001812 if (oldPolicy != StrictMode.NETWORK_POLICY_ACCEPT &&
1813 policy != StrictMode.NETWORK_POLICY_ACCEPT) {
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001814 applyUidCleartextNetworkPolicy(uid, StrictMode.NETWORK_POLICY_ACCEPT);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001815 }
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001816
1817 applyUidCleartextNetworkPolicy(uid, policy);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001818 }
1819 }
1820
1821 @Override
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001822 public boolean isBandwidthControlEnabled() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001823 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang56a03a02018-09-07 12:02:16 +08001824 return true;
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001825 }
1826
1827 @Override
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001828 public NetworkStats getNetworkStatsUidDetail(int uid, String[] ifaces) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001829 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001830 try {
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001831 return mStatsFactory.readNetworkStatsDetail(uid, ifaces, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001832 } catch (IOException e) {
1833 throw new IllegalStateException(e);
1834 }
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001835 }
1836
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001837 private class NetdTetheringStatsProvider extends ITetheringStatsProvider.Stub {
1838 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001839 public NetworkStats getTetherStats(int how) {
1840 // We only need to return per-UID stats. Per-device stats are already counted by
1841 // interface counters.
1842 if (how != STATS_PER_UID) {
1843 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
1844 }
1845
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001846 final PersistableBundle bundle;
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001847 try {
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001848 bundle = mNetdService.tetherGetStats();
1849 } catch (RemoteException | ServiceSpecificException e) {
1850 throw new IllegalStateException("problem parsing tethering stats: ", e);
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001851 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001852
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001853 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(),
1854 bundle.size());
1855 final NetworkStats.Entry entry = new NetworkStats.Entry();
1856
1857 for (String iface : bundle.keySet()) {
1858 long[] statsArray = bundle.getLongArray(iface);
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001859 try {
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001860 entry.iface = iface;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001861 entry.uid = UID_TETHERING;
1862 entry.set = SET_DEFAULT;
1863 entry.tag = TAG_NONE;
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001864 entry.rxBytes = statsArray[INetd.TETHER_STATS_RX_BYTES];
1865 entry.rxPackets = statsArray[INetd.TETHER_STATS_RX_PACKETS];
1866 entry.txBytes = statsArray[INetd.TETHER_STATS_TX_BYTES];
1867 entry.txPackets = statsArray[INetd.TETHER_STATS_TX_PACKETS];
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001868 stats.combineValues(entry);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001869 } catch (ArrayIndexOutOfBoundsException e) {
1870 throw new IllegalStateException("invalid tethering stats for " + iface, e);
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001871 }
1872 }
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001873
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001874 return stats;
1875 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001876
1877 @Override
1878 public void setInterfaceQuota(String iface, long quotaBytes) {
1879 // Do nothing. netd is already informed of quota changes in setInterfaceQuota.
1880 }
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001881 }
1882
1883 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001884 public NetworkStats getNetworkStatsTethering(int how) {
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001885 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1886
1887 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1888 synchronized (mTetheringStatsProviders) {
1889 for (ITetheringStatsProvider provider: mTetheringStatsProviders.keySet()) {
1890 try {
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001891 stats.combineAllValues(provider.getTetherStats(how));
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001892 } catch (RemoteException e) {
1893 Log.e(TAG, "Problem reading tethering stats from " +
1894 mTetheringStatsProviders.get(provider) + ": " + e);
1895 }
1896 }
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001897 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001898 return stats;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001899 }
1900
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001901 @Override
Erik Kline1742fe12017-12-13 19:40:49 +09001902 public void setDnsConfigurationForNetwork(int netId, String[] servers, String[] domains,
Erik Klinee5dac902018-03-04 21:01:01 +09001903 int[] params, String tlsHostname, String[] tlsServers) {
Pierre Imai8e48e672016-04-21 13:30:43 +09001904 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1905
Ben Schwartz6ec28df2017-10-02 13:08:06 -04001906 final String[] tlsFingerprints = new String[0];
Pierre Imai8e48e672016-04-21 13:30:43 +09001907 try {
Erik Kline1742fe12017-12-13 19:40:49 +09001908 mNetdService.setResolverConfiguration(
Erik Klinee5dac902018-03-04 21:01:01 +09001909 netId, servers, domains, params, tlsHostname, tlsServers, tlsFingerprints);
Pierre Imai8e48e672016-04-21 13:30:43 +09001910 } catch (RemoteException e) {
1911 throw new RuntimeException(e);
1912 }
1913 }
1914
1915 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001916 public void addVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001917 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001918 Object[] argv = new Object[3 + MAX_UID_RANGES_PER_COMMAND];
1919 argv[0] = "users";
1920 argv[1] = "add";
1921 argv[2] = netId;
1922 int argc = 3;
1923 // Avoid overly long commands by limiting number of UID ranges per command.
1924 for (int i = 0; i < ranges.length; i++) {
1925 argv[argc++] = ranges[i].toString();
1926 if (i == (ranges.length - 1) || argc == argv.length) {
1927 try {
1928 mConnector.execute("network", Arrays.copyOf(argv, argc));
1929 } catch (NativeDaemonConnectorException e) {
1930 throw e.rethrowAsParcelableException();
1931 }
1932 argc = 3;
1933 }
Chad Brubaker3277620a2013-06-12 13:37:30 -07001934 }
1935 }
1936
1937 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001938 public void removeVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001939 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001940 Object[] argv = new Object[3 + MAX_UID_RANGES_PER_COMMAND];
1941 argv[0] = "users";
1942 argv[1] = "remove";
1943 argv[2] = netId;
1944 int argc = 3;
1945 // Avoid overly long commands by limiting number of UID ranges per command.
1946 for (int i = 0; i < ranges.length; i++) {
1947 argv[argc++] = ranges[i].toString();
1948 if (i == (ranges.length - 1) || argc == argv.length) {
1949 try {
1950 mConnector.execute("network", Arrays.copyOf(argv, argc));
1951 } catch (NativeDaemonConnectorException e) {
1952 throw e.rethrowAsParcelableException();
1953 }
1954 argc = 3;
1955 }
Chad Brubakercca54c42013-06-27 17:41:38 -07001956 }
1957 }
1958
1959 @Override
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001960 public void setFirewallEnabled(boolean enabled) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001961 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001962 try {
Amith Yamasani15e472352015-04-24 19:06:07 -07001963 mConnector.execute("firewall", "enable", enabled ? "whitelist" : "blacklist");
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001964 mFirewallEnabled = enabled;
1965 } catch (NativeDaemonConnectorException e) {
1966 throw e.rethrowAsParcelableException();
1967 }
1968 }
1969
1970 @Override
1971 public boolean isFirewallEnabled() {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001972 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001973 return mFirewallEnabled;
1974 }
1975
1976 @Override
Jeff Sharkey2c092982012-08-24 11:44:40 -07001977 public void setFirewallInterfaceRule(String iface, boolean allow) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001978 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001979 Preconditions.checkState(mFirewallEnabled);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07001980 final String rule = allow ? "allow" : "deny";
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001981 try {
1982 mConnector.execute("firewall", "set_interface_rule", iface, rule);
1983 } catch (NativeDaemonConnectorException e) {
1984 throw e.rethrowAsParcelableException();
1985 }
1986 }
1987
Lorenzo Colitti3fef7232016-04-29 18:00:03 +09001988 private void closeSocketsForFirewallChainLocked(int chain, String chainName) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001989 // UID ranges to close sockets on.
1990 UidRange[] ranges;
1991 // UID ranges whose sockets we won't touch.
1992 int[] exemptUids;
1993
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001994 int numUids = 0;
1995
1996 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
1997 // Close all sockets on all non-system UIDs...
1998 ranges = new UidRange[] {
1999 // TODO: is there a better way of finding all existing users? If so, we could
2000 // specify their ranges here.
2001 new UidRange(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE),
2002 };
2003 // ... except for the UIDs that have allow rules.
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002004 synchronized (mRulesLock) {
2005 final SparseIntArray rules = getUidFirewallRulesLR(chain);
2006 exemptUids = new int[rules.size()];
2007 for (int i = 0; i < exemptUids.length; i++) {
2008 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
2009 exemptUids[numUids] = rules.keyAt(i);
2010 numUids++;
2011 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002012 }
2013 }
2014 // Normally, whitelist chains only contain deny rules, so numUids == exemptUids.length.
2015 // But the code does not guarantee this in any way, and at least in one case - if we add
2016 // a UID rule to the firewall, and then disable the firewall - the chains can contain
2017 // the wrong type of rule. In this case, don't close connections that we shouldn't.
2018 //
2019 // TODO: tighten up this code by ensuring we never set the wrong type of rule, and
2020 // fix setFirewallEnabled to grab mQuotaLock and clear rules.
2021 if (numUids != exemptUids.length) {
2022 exemptUids = Arrays.copyOf(exemptUids, numUids);
2023 }
2024 } else {
2025 // Close sockets for every UID that has a deny rule...
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002026 synchronized (mRulesLock) {
2027 final SparseIntArray rules = getUidFirewallRulesLR(chain);
2028 ranges = new UidRange[rules.size()];
2029 for (int i = 0; i < ranges.length; i++) {
2030 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_DENY) {
2031 int uid = rules.keyAt(i);
2032 ranges[numUids] = new UidRange(uid, uid);
2033 numUids++;
2034 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002035 }
2036 }
2037 // As above; usually numUids == ranges.length, but not always.
2038 if (numUids != ranges.length) {
2039 ranges = Arrays.copyOf(ranges, numUids);
2040 }
2041 // ... with no exceptions.
2042 exemptUids = new int[0];
2043 }
2044
2045 try {
2046 mNetdService.socketDestroy(ranges, exemptUids);
2047 } catch(RemoteException | ServiceSpecificException e) {
2048 Slog.e(TAG, "Error closing sockets after enabling chain " + chainName + ": " + e);
2049 }
2050 }
2051
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002052 @Override
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002053 public void setFirewallChainEnabled(int chain, boolean enable) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07002054 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002055 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002056 synchronized (mRulesLock) {
2057 if (getFirewallChainState(chain) == enable) {
2058 // All is the same, nothing to do. This relies on the fact that netd has child
2059 // chains default detached.
2060 return;
2061 }
2062 setFirewallChainState(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002063 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002064
2065 final String operation = enable ? "enable_chain" : "disable_chain";
Lorenzo Colitti3fef7232016-04-29 18:00:03 +09002066 final String chainName;
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002067 switch(chain) {
2068 case FIREWALL_CHAIN_STANDBY:
2069 chainName = FIREWALL_CHAIN_NAME_STANDBY;
2070 break;
2071 case FIREWALL_CHAIN_DOZABLE:
2072 chainName = FIREWALL_CHAIN_NAME_DOZABLE;
2073 break;
2074 case FIREWALL_CHAIN_POWERSAVE:
2075 chainName = FIREWALL_CHAIN_NAME_POWERSAVE;
2076 break;
2077 default:
2078 throw new IllegalArgumentException("Bad child chain: " + chain);
2079 }
2080
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002081 try {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002082 mConnector.execute("firewall", operation, chainName);
2083 } catch (NativeDaemonConnectorException e) {
2084 throw e.rethrowAsParcelableException();
2085 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002086
2087 // Close any sockets that were opened by the affected UIDs. This has to be done after
2088 // disabling network connectivity, in case they react to the socket close by reopening
2089 // the connection and race with the iptables commands that enable the firewall. All
2090 // whitelist and blacklist chains allow RSTs through.
2091 if (enable) {
2092 if (DBG) Slog.d(TAG, "Closing sockets after enabling chain " + chainName);
Lorenzo Colitti3fef7232016-04-29 18:00:03 +09002093 closeSocketsForFirewallChainLocked(chain, chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002094 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002095 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002096 }
2097
2098 private int getFirewallType(int chain) {
2099 switch (chain) {
2100 case FIREWALL_CHAIN_STANDBY:
2101 return FIREWALL_TYPE_BLACKLIST;
2102 case FIREWALL_CHAIN_DOZABLE:
2103 return FIREWALL_TYPE_WHITELIST;
Felipe Leme011b98f2016-02-10 17:28:31 -08002104 case FIREWALL_CHAIN_POWERSAVE:
2105 return FIREWALL_TYPE_WHITELIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002106 default:
2107 return isFirewallEnabled() ? FIREWALL_TYPE_WHITELIST : FIREWALL_TYPE_BLACKLIST;
2108 }
2109 }
2110
2111 @Override
2112 public void setFirewallUidRules(int chain, int[] uids, int[] rules) {
2113 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002114 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002115 synchronized (mRulesLock) {
2116 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
2117 SparseIntArray newRules = new SparseIntArray();
2118 // apply new set of rules
2119 for (int index = uids.length - 1; index >= 0; --index) {
2120 int uid = uids[index];
2121 int rule = rules[index];
2122 updateFirewallUidRuleLocked(chain, uid, rule);
2123 newRules.put(uid, rule);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002124 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002125 // collect the rules to remove.
2126 SparseIntArray rulesToRemove = new SparseIntArray();
2127 for (int index = uidFirewallRules.size() - 1; index >= 0; --index) {
2128 int uid = uidFirewallRules.keyAt(index);
2129 if (newRules.indexOfKey(uid) < 0) {
2130 rulesToRemove.put(uid, FIREWALL_RULE_DEFAULT);
2131 }
2132 }
2133 // remove dead rules
2134 for (int index = rulesToRemove.size() - 1; index >= 0; --index) {
2135 int uid = rulesToRemove.keyAt(index);
2136 updateFirewallUidRuleLocked(chain, uid, FIREWALL_RULE_DEFAULT);
2137 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002138 }
2139 try {
2140 switch (chain) {
2141 case FIREWALL_CHAIN_DOZABLE:
2142 mNetdService.firewallReplaceUidChain("fw_dozable", true, uids);
2143 break;
2144 case FIREWALL_CHAIN_STANDBY:
2145 mNetdService.firewallReplaceUidChain("fw_standby", false, uids);
2146 break;
2147 case FIREWALL_CHAIN_POWERSAVE:
2148 mNetdService.firewallReplaceUidChain("fw_powersave", true, uids);
2149 break;
2150 case FIREWALL_CHAIN_NONE:
2151 default:
2152 Slog.d(TAG, "setFirewallUidRules() called on invalid chain: " + chain);
2153 }
2154 } catch (RemoteException e) {
2155 Slog.w(TAG, "Error flushing firewall chain " + chain, e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002156 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002157 }
2158 }
2159
2160 @Override
2161 public void setFirewallUidRule(int chain, int uid, int rule) {
2162 enforceSystemUid();
Felipe Lemea701cad2016-05-12 09:58:14 -07002163 synchronized (mQuotaLock) {
2164 setFirewallUidRuleLocked(chain, uid, rule);
2165 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002166 }
2167
Felipe Lemea701cad2016-05-12 09:58:14 -07002168 private void setFirewallUidRuleLocked(int chain, int uid, int rule) {
2169 if (updateFirewallUidRuleLocked(chain, uid, rule)) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002170 try {
Felipe Lemea701cad2016-05-12 09:58:14 -07002171 mConnector.execute("firewall", "set_uid_rule", getFirewallChainName(chain), uid,
2172 getFirewallRuleName(chain, rule));
Amith Yamasani15e472352015-04-24 19:06:07 -07002173 } catch (NativeDaemonConnectorException e) {
2174 throw e.rethrowAsParcelableException();
2175 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002176 }
2177 }
2178
Felipe Lemea701cad2016-05-12 09:58:14 -07002179 // TODO: now that netd supports batching, NMS should not keep these data structures anymore...
2180 private boolean updateFirewallUidRuleLocked(int chain, int uid, int rule) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002181 synchronized (mRulesLock) {
2182 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Felipe Lemea701cad2016-05-12 09:58:14 -07002183
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002184 final int oldUidFirewallRule = uidFirewallRules.get(uid, FIREWALL_RULE_DEFAULT);
2185 if (DBG) {
2186 Slog.d(TAG, "oldRule = " + oldUidFirewallRule
2187 + ", newRule=" + rule + " for uid=" + uid + " on chain " + chain);
2188 }
2189 if (oldUidFirewallRule == rule) {
2190 if (DBG) Slog.d(TAG, "!!!!! Skipping change");
2191 // TODO: eventually consider throwing
2192 return false;
2193 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002194
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002195 String ruleName = getFirewallRuleName(chain, rule);
2196 String oldRuleName = getFirewallRuleName(chain, oldUidFirewallRule);
Felipe Lemea701cad2016-05-12 09:58:14 -07002197
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002198 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
2199 uidFirewallRules.delete(uid);
2200 } else {
2201 uidFirewallRules.put(uid, rule);
2202 }
2203 return !ruleName.equals(oldRuleName);
Felipe Lemea701cad2016-05-12 09:58:14 -07002204 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002205 }
2206
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002207 private @NonNull String getFirewallRuleName(int chain, int rule) {
2208 String ruleName;
2209 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
2210 if (rule == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
2211 ruleName = "allow";
2212 } else {
2213 ruleName = "deny";
2214 }
2215 } else { // Blacklist mode
2216 if (rule == NetworkPolicyManager.FIREWALL_RULE_DENY) {
2217 ruleName = "deny";
2218 } else {
2219 ruleName = "allow";
2220 }
2221 }
2222 return ruleName;
2223 }
2224
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002225 private @NonNull SparseIntArray getUidFirewallRulesLR(int chain) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002226 switch (chain) {
2227 case FIREWALL_CHAIN_STANDBY:
2228 return mUidFirewallStandbyRules;
2229 case FIREWALL_CHAIN_DOZABLE:
2230 return mUidFirewallDozableRules;
Felipe Leme011b98f2016-02-10 17:28:31 -08002231 case FIREWALL_CHAIN_POWERSAVE:
2232 return mUidFirewallPowerSaveRules;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002233 case FIREWALL_CHAIN_NONE:
2234 return mUidFirewallRules;
2235 default:
2236 throw new IllegalArgumentException("Unknown chain:" + chain);
2237 }
2238 }
2239
2240 public @NonNull String getFirewallChainName(int chain) {
2241 switch (chain) {
2242 case FIREWALL_CHAIN_STANDBY:
2243 return FIREWALL_CHAIN_NAME_STANDBY;
2244 case FIREWALL_CHAIN_DOZABLE:
2245 return FIREWALL_CHAIN_NAME_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -08002246 case FIREWALL_CHAIN_POWERSAVE:
2247 return FIREWALL_CHAIN_NAME_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002248 case FIREWALL_CHAIN_NONE:
2249 return FIREWALL_CHAIN_NAME_NONE;
2250 default:
2251 throw new IllegalArgumentException("Unknown chain:" + chain);
2252 }
2253 }
2254
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07002255 private static void enforceSystemUid() {
2256 final int uid = Binder.getCallingUid();
2257 if (uid != Process.SYSTEM_UID) {
2258 throw new SecurityException("Only available to AID_SYSTEM");
2259 }
2260 }
2261
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002262 @Override
Lorenzo Colitti79751842013-02-28 16:16:03 +09002263 public void startClatd(String interfaceName) throws IllegalStateException {
2264 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2265
2266 try {
Luke Huang69369f32018-08-02 15:51:41 +08002267 mNetdService.clatdStart(interfaceName);
2268 } catch (RemoteException | ServiceSpecificException e) {
2269 throw new IllegalStateException(e);
Lorenzo Colitti79751842013-02-28 16:16:03 +09002270 }
2271 }
2272
2273 @Override
Lorenzo Colitti95439462014-10-09 13:44:48 +09002274 public void stopClatd(String interfaceName) throws IllegalStateException {
Lorenzo Colitti79751842013-02-28 16:16:03 +09002275 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2276
2277 try {
Luke Huang69369f32018-08-02 15:51:41 +08002278 mNetdService.clatdStop(interfaceName);
2279 } catch (RemoteException | ServiceSpecificException e) {
2280 throw new IllegalStateException(e);
Lorenzo Colitti79751842013-02-28 16:16:03 +09002281 }
2282 }
2283
2284 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002285 public void registerNetworkActivityListener(INetworkActivityListener listener) {
2286 mNetworkActivityListeners.register(listener);
2287 }
2288
2289 @Override
2290 public void unregisterNetworkActivityListener(INetworkActivityListener listener) {
2291 mNetworkActivityListeners.unregister(listener);
2292 }
2293
2294 @Override
2295 public boolean isNetworkActive() {
2296 synchronized (mNetworkActivityListeners) {
2297 return mNetworkActive || mActiveIdleTimers.isEmpty();
2298 }
2299 }
2300
2301 private void reportNetworkActive() {
2302 final int length = mNetworkActivityListeners.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002303 try {
2304 for (int i = 0; i < length; i++) {
2305 try {
2306 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
Felipe Leme03e689d2016-03-02 16:17:38 -08002307 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002308 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002309 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002310 } finally {
2311 mNetworkActivityListeners.finishBroadcast();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002312 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002313 }
2314
Mattias Falk8b47b362011-08-23 14:15:13 +02002315 /** {@inheritDoc} */
Jeff Sharkey7b4596f2013-02-25 10:55:29 -08002316 @Override
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002317 public void monitor() {
2318 if (mConnector != null) {
2319 mConnector.monitor();
2320 }
2321 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002322
2323 @Override
2324 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002325 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002326
Robert Greenwalt470fd722012-01-18 12:51:15 -08002327 pw.println("NetworkManagementService NativeDaemonConnector Log:");
2328 mConnector.dump(fd, pw, args);
2329 pw.println();
2330
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07002331 pw.print("mMobileActivityFromRadio="); pw.print(mMobileActivityFromRadio);
2332 pw.print(" mLastPowerStateFromRadio="); pw.println(mLastPowerStateFromRadio);
2333 pw.print("mNetworkActive="); pw.println(mNetworkActive);
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002334
2335 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07002336 pw.print("Active quota ifaces: "); pw.println(mActiveQuotas.toString());
2337 pw.print("Active alert ifaces: "); pw.println(mActiveAlerts.toString());
Felipe Leme65be3022016-03-22 14:53:13 -07002338 pw.print("Data saver mode: "); pw.println(mDataSaverMode);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002339 synchronized (mRulesLock) {
2340 dumpUidRuleOnQuotaLocked(pw, "blacklist", mUidRejectOnMetered);
2341 dumpUidRuleOnQuotaLocked(pw, "whitelist", mUidAllowOnMetered);
2342 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002343 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002344
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002345 synchronized (mRulesLock) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002346 dumpUidFirewallRule(pw, "", mUidFirewallRules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002347
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002348 pw.print("UID firewall standby chain enabled: "); pw.println(
2349 getFirewallChainState(FIREWALL_CHAIN_STANDBY));
Felipe Leme011b98f2016-02-10 17:28:31 -08002350 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_STANDBY, mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002351
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002352 pw.print("UID firewall dozable chain enabled: "); pw.println(
2353 getFirewallChainState(FIREWALL_CHAIN_DOZABLE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002354 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_DOZABLE, mUidFirewallDozableRules);
Felipe Leme011b98f2016-02-10 17:28:31 -08002355
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002356 pw.println("UID firewall powersave chain enabled: " +
2357 getFirewallChainState(FIREWALL_CHAIN_POWERSAVE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002358 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_POWERSAVE, mUidFirewallPowerSaveRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002359 }
2360
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002361 synchronized (mIdleTimerLock) {
2362 pw.println("Idle timers:");
2363 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
2364 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
2365 IdleTimerParams params = ent.getValue();
2366 pw.print(" timeout="); pw.print(params.timeout);
2367 pw.print(" type="); pw.print(params.type);
2368 pw.print(" networkCount="); pw.println(params.networkCount);
2369 }
2370 }
2371
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002372 pw.print("Firewall enabled: "); pw.println(mFirewallEnabled);
Felipe Leme65be3022016-03-22 14:53:13 -07002373 pw.print("Netd service status: " );
2374 if (mNetdService == null) {
2375 pw.println("disconnected");
2376 } else {
2377 try {
2378 final boolean alive = mNetdService.isAlive();
2379 pw.println(alive ? "alive": "dead");
2380 } catch (RemoteException e) {
2381 pw.println("unreachable");
2382 }
2383 }
2384 }
2385
2386 private void dumpUidRuleOnQuotaLocked(PrintWriter pw, String name, SparseBooleanArray list) {
2387 pw.print("UID bandwith control ");
2388 pw.print(name);
2389 pw.print(" rule: [");
2390 final int size = list.size();
2391 for (int i = 0; i < size; i++) {
2392 pw.print(list.keyAt(i));
2393 if (i < size - 1) pw.print(",");
2394 }
2395 pw.println("]");
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002396 }
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002397
Felipe Leme011b98f2016-02-10 17:28:31 -08002398 private void dumpUidFirewallRule(PrintWriter pw, String name, SparseIntArray rules) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002399 pw.print("UID firewall ");
Felipe Leme011b98f2016-02-10 17:28:31 -08002400 pw.print(name);
2401 pw.print(" rule: [");
2402 final int size = rules.size();
2403 for (int i = 0; i < size; i++) {
2404 pw.print(rules.keyAt(i));
2405 pw.print(":");
2406 pw.print(rules.valueAt(i));
2407 if (i < size - 1) pw.print(",");
2408 }
2409 pw.println("]");
2410 }
2411
Robert Greenwalt568891d2014-04-04 13:38:00 -07002412 @Override
Paul Jensen487ffe72015-07-24 15:57:11 -04002413 public void createPhysicalNetwork(int netId, String permission) {
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002414 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2415
2416 try {
Paul Jensen487ffe72015-07-24 15:57:11 -04002417 if (permission != null) {
2418 mConnector.execute("network", "create", netId, permission);
2419 } else {
2420 mConnector.execute("network", "create", netId);
2421 }
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002422 } catch (NativeDaemonConnectorException e) {
2423 throw e.rethrowAsParcelableException();
2424 }
2425 }
2426
Robert Greenwalt568891d2014-04-04 13:38:00 -07002427 @Override
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07002428 public void createVirtualNetwork(int netId, boolean hasDNS, boolean secure) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002429 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2430
2431 try {
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07002432 mConnector.execute("network", "create", netId, "vpn", hasDNS ? "1" : "0",
2433 secure ? "1" : "0");
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002434 } catch (NativeDaemonConnectorException e) {
2435 throw e.rethrowAsParcelableException();
2436 }
2437 }
2438
2439 @Override
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002440 public void removeNetwork(int netId) {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002441 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002442
2443 try {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002444 mNetdService.networkDestroy(netId);
2445 } catch (ServiceSpecificException e) {
2446 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2447 throw e;
2448 } catch (RemoteException e) {
2449 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2450 throw e.rethrowAsRuntimeException();
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002451 }
2452 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002453
2454 @Override
Paul Jensen992f2522014-04-28 10:33:11 -04002455 public void addInterfaceToNetwork(String iface, int netId) {
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002456 modifyInterfaceInNetwork("add", "" + netId, iface);
Paul Jensen992f2522014-04-28 10:33:11 -04002457 }
2458
2459 @Override
2460 public void removeInterfaceFromNetwork(String iface, int netId) {
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002461 modifyInterfaceInNetwork("remove", "" + netId, iface);
2462 }
Paul Jensen992f2522014-04-28 10:33:11 -04002463
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002464 private void modifyInterfaceInNetwork(String action, String netId, String iface) {
2465 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Paul Jensen992f2522014-04-28 10:33:11 -04002466 try {
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002467 mConnector.execute("network", "interface", action, netId, iface);
Paul Jensen992f2522014-04-28 10:33:11 -04002468 } catch (NativeDaemonConnectorException e) {
2469 throw e.rethrowAsParcelableException();
2470 }
2471 }
2472
2473 @Override
Robert Greenwalt913c8952014-04-07 17:36:35 -07002474 public void addLegacyRouteForNetId(int netId, RouteInfo routeInfo, int uid) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002475 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2476
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07002477 final Command cmd = new Command("network", "route", "legacy", uid, "add", netId);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002478
Sreeram Ramachandran1fbcb272014-05-22 16:30:48 -07002479 // create triplet: interface dest-ip-addr/prefixlength gateway-ip-addr
Sreeram Ramachandrancc91c7b2014-06-03 18:41:43 -07002480 final LinkAddress la = routeInfo.getDestinationLinkAddress();
Robert Greenwalt568891d2014-04-04 13:38:00 -07002481 cmd.appendArg(routeInfo.getInterface());
Lorenzo Colitti7dc78cf2014-06-09 22:58:46 +09002482 cmd.appendArg(la.getAddress().getHostAddress() + "/" + la.getPrefixLength());
Sreeram Ramachandran1fbcb272014-05-22 16:30:48 -07002483 if (routeInfo.hasGateway()) {
2484 cmd.appendArg(routeInfo.getGateway().getHostAddress());
2485 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002486
2487 try {
2488 mConnector.execute(cmd);
2489 } catch (NativeDaemonConnectorException e) {
2490 throw e.rethrowAsParcelableException();
2491 }
2492 }
2493
2494 @Override
Sreeram Ramachandranf047f2a2014-04-15 16:04:26 -07002495 public void setDefaultNetId(int netId) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002496 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2497
2498 try {
Sreeram Ramachandranf047f2a2014-04-15 16:04:26 -07002499 mConnector.execute("network", "default", "set", netId);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002500 } catch (NativeDaemonConnectorException e) {
2501 throw e.rethrowAsParcelableException();
2502 }
2503 }
2504
2505 @Override
2506 public void clearDefaultNetId() {
2507 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2508
2509 try {
2510 mConnector.execute("network", "default", "clear");
2511 } catch (NativeDaemonConnectorException e) {
2512 throw e.rethrowAsParcelableException();
2513 }
2514 }
2515
2516 @Override
Paul Jensen487ffe72015-07-24 15:57:11 -04002517 public void setNetworkPermission(int netId, String permission) {
2518 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2519
2520 try {
2521 if (permission != null) {
2522 mConnector.execute("network", "permission", "network", "set", permission, netId);
2523 } else {
2524 mConnector.execute("network", "permission", "network", "clear", netId);
2525 }
2526 } catch (NativeDaemonConnectorException e) {
2527 throw e.rethrowAsParcelableException();
2528 }
2529 }
2530
2531
2532 @Override
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002533 public void setPermission(String permission, int[] uids) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002534 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2535
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002536 Object[] argv = new Object[4 + MAX_UID_RANGES_PER_COMMAND];
2537 argv[0] = "permission";
2538 argv[1] = "user";
2539 argv[2] = "set";
2540 argv[3] = permission;
2541 int argc = 4;
2542 // Avoid overly long commands by limiting number of UIDs per command.
2543 for (int i = 0; i < uids.length; ++i) {
2544 argv[argc++] = uids[i];
2545 if (i == uids.length - 1 || argc == argv.length) {
2546 try {
2547 mConnector.execute("network", Arrays.copyOf(argv, argc));
2548 } catch (NativeDaemonConnectorException e) {
2549 throw e.rethrowAsParcelableException();
2550 }
2551 argc = 4;
2552 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002553 }
2554 }
2555
2556 @Override
2557 public void clearPermission(int[] uids) {
2558 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2559
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002560 Object[] argv = new Object[3 + MAX_UID_RANGES_PER_COMMAND];
2561 argv[0] = "permission";
2562 argv[1] = "user";
2563 argv[2] = "clear";
2564 int argc = 3;
2565 // Avoid overly long commands by limiting number of UIDs per command.
2566 for (int i = 0; i < uids.length; ++i) {
2567 argv[argc++] = uids[i];
2568 if (i == uids.length - 1 || argc == argv.length) {
2569 try {
2570 mConnector.execute("network", Arrays.copyOf(argv, argc));
2571 } catch (NativeDaemonConnectorException e) {
2572 throw e.rethrowAsParcelableException();
2573 }
2574 argc = 3;
2575 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002576 }
2577 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002578
2579 @Override
2580 public void allowProtect(int uid) {
2581 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2582
2583 try {
2584 mConnector.execute("network", "protect", "allow", uid);
2585 } catch (NativeDaemonConnectorException e) {
2586 throw e.rethrowAsParcelableException();
2587 }
2588 }
2589
2590 @Override
2591 public void denyProtect(int uid) {
2592 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2593
2594 try {
2595 mConnector.execute("network", "protect", "deny", uid);
2596 } catch (NativeDaemonConnectorException e) {
2597 throw e.rethrowAsParcelableException();
2598 }
2599 }
2600
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002601 @Override
2602 public void addInterfaceToLocalNetwork(String iface, List<RouteInfo> routes) {
2603 modifyInterfaceInNetwork("add", "local", iface);
2604
2605 for (RouteInfo route : routes) {
2606 if (!route.isDefaultRoute()) {
2607 modifyRoute("add", "local", route);
2608 }
2609 }
2610 }
2611
2612 @Override
2613 public void removeInterfaceFromLocalNetwork(String iface) {
2614 modifyInterfaceInNetwork("remove", "local", iface);
2615 }
Erik Kline6599ee82016-07-17 21:28:39 +09002616
2617 @Override
2618 public int removeRoutesFromLocalNetwork(List<RouteInfo> routes) {
2619 int failures = 0;
2620
2621 for (RouteInfo route : routes) {
2622 try {
2623 modifyRoute("remove", "local", route);
2624 } catch (IllegalStateException e) {
2625 failures++;
2626 }
2627 }
2628
2629 return failures;
2630 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002631
Sudheer Shankab8f23162017-08-04 13:30:10 -07002632 @Override
2633 public boolean isNetworkRestricted(int uid) {
2634 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2635 return isNetworkRestrictedInternal(uid);
2636 }
2637
2638 private boolean isNetworkRestrictedInternal(int uid) {
2639 synchronized (mRulesLock) {
2640 if (getFirewallChainState(FIREWALL_CHAIN_STANDBY)
2641 && mUidFirewallStandbyRules.get(uid) == FIREWALL_RULE_DENY) {
2642 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of app standby mode");
2643 return true;
2644 }
2645 if (getFirewallChainState(FIREWALL_CHAIN_DOZABLE)
2646 && mUidFirewallDozableRules.get(uid) != FIREWALL_RULE_ALLOW) {
2647 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of device idle mode");
2648 return true;
2649 }
2650 if (getFirewallChainState(FIREWALL_CHAIN_POWERSAVE)
2651 && mUidFirewallPowerSaveRules.get(uid) != FIREWALL_RULE_ALLOW) {
2652 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of power saver mode");
2653 return true;
2654 }
2655 if (mUidRejectOnMetered.get(uid)) {
2656 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of no metered data"
2657 + " in the background");
2658 return true;
2659 }
2660 if (mDataSaverMode && !mUidAllowOnMetered.get(uid)) {
2661 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of data saver mode");
2662 return true;
2663 }
2664 return false;
2665 }
2666 }
2667
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002668 private void setFirewallChainState(int chain, boolean state) {
2669 synchronized (mRulesLock) {
2670 mFirewallChainStates.put(chain, state);
2671 }
2672 }
2673
2674 private boolean getFirewallChainState(int chain) {
2675 synchronized (mRulesLock) {
2676 return mFirewallChainStates.get(chain);
2677 }
2678 }
2679
2680 @VisibleForTesting
2681 class LocalService extends NetworkManagementInternal {
2682 @Override
2683 public boolean isNetworkRestrictedForUid(int uid) {
Sudheer Shankab8f23162017-08-04 13:30:10 -07002684 return isNetworkRestrictedInternal(uid);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002685 }
2686 }
2687
2688 @VisibleForTesting
2689 Injector getInjector() {
2690 return new Injector();
2691 }
2692
2693 @VisibleForTesting
2694 class Injector {
2695 void setDataSaverMode(boolean dataSaverMode) {
2696 mDataSaverMode = dataSaverMode;
2697 }
2698
2699 void setFirewallChainState(int chain, boolean state) {
2700 NetworkManagementService.this.setFirewallChainState(chain, state);
2701 }
2702
2703 void setFirewallRule(int chain, int uid, int rule) {
2704 synchronized (mRulesLock) {
2705 getUidFirewallRulesLR(chain).put(uid, rule);
2706 }
2707 }
2708
2709 void setUidOnMeteredNetworkList(boolean blacklist, int uid, boolean enable) {
2710 synchronized (mRulesLock) {
2711 if (blacklist) {
2712 mUidRejectOnMetered.put(uid, enable);
2713 } else {
2714 mUidAllowOnMetered.put(uid, enable);
2715 }
2716 }
2717 }
2718
2719 void reset() {
2720 synchronized (mRulesLock) {
2721 setDataSaverMode(false);
2722 final int[] chains = {
2723 FIREWALL_CHAIN_DOZABLE,
2724 FIREWALL_CHAIN_STANDBY,
2725 FIREWALL_CHAIN_POWERSAVE
2726 };
2727 for (int chain : chains) {
2728 setFirewallChainState(chain, false);
2729 getUidFirewallRulesLR(chain).clear();
2730 }
2731 mUidAllowOnMetered.clear();
2732 mUidRejectOnMetered.clear();
2733 }
2734 }
2735 }
San Mehat873f2142010-01-14 10:25:07 -08002736}