blob: a16c158f0e989cf567ca686e2af3b583fe4a79ff [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
Luke Huang4a32bf42018-08-21 19:09:45 +0800163 private static final String[] EMPTY_STRING_ARRAY = new String[0];
164
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700165 /**
166 * Name representing {@link #setGlobalAlert(long)} limit when delivered to
167 * {@link INetworkManagementEventObserver#limitReached(String, String)}.
168 */
169 public static final String LIMIT_GLOBAL_ALERT = "globalAlert";
170
Andrew Scull45f533c2017-05-19 15:37:20 +0100171 static class NetdResponseCode {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -0700172 /* Keep in sync with system/netd/server/ResponseCode.h */
San Mehat873f2142010-01-14 10:25:07 -0800173 public static final int InterfaceListResult = 110;
174 public static final int TetherInterfaceListResult = 111;
175 public static final int TetherDnsFwdTgtListResult = 112;
San Mehat72759df2010-01-19 13:50:37 -0800176 public static final int TtyListResult = 113;
Jeff Sharkeye4984be2013-09-10 21:03:27 -0700177 public static final int TetheringStatsListResult = 114;
San Mehat873f2142010-01-14 10:25:07 -0800178
179 public static final int TetherStatusResult = 210;
180 public static final int IpFwdStatusResult = 211;
San Mehated4fc8a2010-01-22 12:28:36 -0800181 public static final int InterfaceGetCfgResult = 213;
Robert Greenwalte3253922010-02-18 09:23:25 -0800182 public static final int SoftapStatusResult = 214;
San Mehat91cac642010-03-31 14:31:36 -0700183 public static final int InterfaceRxCounterResult = 216;
184 public static final int InterfaceTxCounterResult = 217;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700185 public static final int QuotaCounterResult = 220;
186 public static final int TetheringStatsResult = 221;
Selim Gurun84c00c62012-02-27 15:42:38 -0800187 public static final int DnsProxyQueryResult = 222;
Lorenzo Colitti79751842013-02-28 16:16:03 +0900188 public static final int ClatdStatusResult = 223;
Robert Greenwalte3253922010-02-18 09:23:25 -0800189
190 public static final int InterfaceChange = 600;
JP Abgrall12b933d2011-07-14 18:09:22 -0700191 public static final int BandwidthControl = 601;
Haoyu Bai6b7358d2012-07-17 16:36:50 -0700192 public static final int InterfaceClassActivity = 613;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900193 public static final int InterfaceAddressChange = 614;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900194 public static final int InterfaceDnsServerInfo = 615;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900195 public static final int RouteChange = 616;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800196 public static final int StrictCleartext = 617;
San Mehat873f2142010-01-14 10:25:07 -0800197 }
198
Rebecca Silbersteine2ec94f2016-03-24 13:29:00 -0700199 /**
200 * String indicating a softap command.
201 */
202 static final String SOFT_AP_COMMAND = "softap";
203
204 /**
205 * String passed back to netd connector indicating softap command success.
206 */
207 static final String SOFT_AP_COMMAND_SUCCESS = "Ok";
208
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700209 static final int DAEMON_MSG_MOBILE_CONN_REAL_TIME_INFO = 1;
210
Luke Huang8a462ec2018-08-24 20:33:16 +0800211 static final boolean MODIFY_OPERATION_ADD = true;
212 static final boolean MODIFY_OPERATION_REMOVE = false;
213
San Mehat873f2142010-01-14 10:25:07 -0800214 /**
215 * Binder context for this service
216 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700217 private final Context mContext;
San Mehat873f2142010-01-14 10:25:07 -0800218
219 /**
220 * connector object for communicating with netd
221 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700222 private final NativeDaemonConnector mConnector;
San Mehat873f2142010-01-14 10:25:07 -0800223
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700224 private final Handler mFgHandler;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700225 private final Handler mDaemonHandler;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700226
Lorenzo Colittia0868002017-07-11 02:29:28 +0900227 private final SystemServices mServices;
228
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900229 private INetd mNetdService;
230
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800231 private IBatteryStats mBatteryStats;
232
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700233 private final Thread mThread;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700234 private CountDownLatch mConnectedSignal = new CountDownLatch(1);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700235
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800236 private final RemoteCallbackList<INetworkManagementEventObserver> mObservers =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700237 new RemoteCallbackList<>();
San Mehat4d02d002010-01-22 16:07:46 -0800238
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700239 private final NetworkStatsFactory mStatsFactory = new NetworkStatsFactory();
240
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900241 @GuardedBy("mTetheringStatsProviders")
242 private final HashMap<ITetheringStatsProvider, String>
243 mTetheringStatsProviders = Maps.newHashMap();
244
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700245 /**
246 * If both locks need to be held, then they should be obtained in the order:
247 * first {@link #mQuotaLock} and then {@link #mRulesLock}.
248 */
Andrew Scull45f533c2017-05-19 15:37:20 +0100249 private final Object mQuotaLock = new Object();
Andrew Scull519291f2017-05-23 13:11:03 +0100250 private final Object mRulesLock = new Object();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800251
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700252 /** Set of interfaces with active quotas. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800253 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700254 private HashMap<String, Long> mActiveQuotas = Maps.newHashMap();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700255 /** Set of interfaces with active alerts. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800256 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700257 private HashMap<String, Long> mActiveAlerts = Maps.newHashMap();
Felipe Leme65be3022016-03-22 14:53:13 -0700258 /** Set of UIDs blacklisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700259 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700260 private SparseBooleanArray mUidRejectOnMetered = new SparseBooleanArray();
261 /** Set of UIDs whitelisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700262 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700263 private SparseBooleanArray mUidAllowOnMetered = new SparseBooleanArray();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800264 /** Set of UIDs with cleartext penalties. */
265 @GuardedBy("mQuotaLock")
266 private SparseIntArray mUidCleartextPolicy = new SparseIntArray();
Amith Yamasani15e472352015-04-24 19:06:07 -0700267 /** Set of UIDs that are to be blocked/allowed by firewall controller. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700268 @GuardedBy("mRulesLock")
Amith Yamasani15e472352015-04-24 19:06:07 -0700269 private SparseIntArray mUidFirewallRules = new SparseIntArray();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700270 /**
271 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
272 * to application idles.
273 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700274 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700275 private SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
276 /**
277 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
278 * to device idles.
279 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700280 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700281 private SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800282 /**
283 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
284 * to device on power-save mode.
285 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700286 @GuardedBy("mRulesLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800287 private SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700288 /** Set of states for the child firewall chains. True if the chain is active. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700289 @GuardedBy("mRulesLock")
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700290 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700291
Felipe Leme65be3022016-03-22 14:53:13 -0700292 @GuardedBy("mQuotaLock")
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700293 private volatile boolean mDataSaverMode;
Felipe Leme65be3022016-03-22 14:53:13 -0700294
Andrew Scull45f533c2017-05-19 15:37:20 +0100295 private final Object mIdleTimerLock = new Object();
Haoyu Bai04124232012-06-28 15:26:19 -0700296 /** Set of interfaces with active idle timers. */
297 private static class IdleTimerParams {
298 public final int timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800299 public final int type;
Haoyu Bai04124232012-06-28 15:26:19 -0700300 public int networkCount;
301
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800302 IdleTimerParams(int timeout, int type) {
Haoyu Bai04124232012-06-28 15:26:19 -0700303 this.timeout = timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800304 this.type = type;
Haoyu Bai04124232012-06-28 15:26:19 -0700305 this.networkCount = 1;
306 }
307 }
308 private HashMap<String, IdleTimerParams> mActiveIdleTimers = Maps.newHashMap();
309
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700310 private volatile boolean mFirewallEnabled;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800311 private volatile boolean mStrictEnabled;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700312
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700313 private boolean mMobileActivityFromRadio = false;
314 private int mLastPowerStateFromRadio = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Adam Lesinskie08af192015-03-25 16:42:59 -0700315 private int mLastPowerStateFromWifi = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700316
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800317 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700318 new RemoteCallbackList<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800319 private boolean mNetworkActive;
320
San Mehat873f2142010-01-14 10:25:07 -0800321 /**
322 * Constructs a new NetworkManagementService instance
323 *
324 * @param context Binder context for this service
325 */
Lorenzo Colittia0868002017-07-11 02:29:28 +0900326 private NetworkManagementService(
327 Context context, String socket, SystemServices services) {
San Mehat873f2142010-01-14 10:25:07 -0800328 mContext = context;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900329 mServices = services;
San Mehat4d02d002010-01-22 16:07:46 -0800330
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700331 // make sure this is on the same looper as our NativeDaemonConnector for sync purposes
332 mFgHandler = new Handler(FgThread.get().getLooper());
333
Dianne Hackborn4590e522014-03-24 13:36:46 -0700334 // Don't need this wake lock, since we now have a time stamp for when
335 // the network actually went inactive. (It might be nice to still do this,
336 // but I don't want to do it through the power manager because that pollutes the
337 // battery stats history with pointless noise.)
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700338 //PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
Dianne Hackborn4590e522014-03-24 13:36:46 -0700339 PowerManager.WakeLock wl = null; //pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NETD_TAG);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800340
San Mehat873f2142010-01-14 10:25:07 -0800341 mConnector = new NativeDaemonConnector(
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700342 new NetdCallbackReceiver(), socket, 10, NETD_TAG, 160, wl,
343 FgThread.get().getLooper());
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700344 mThread = new Thread(mConnector, NETD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700345
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700346 mDaemonHandler = new Handler(FgThread.get().getLooper());
Wink Saville67e07892014-06-18 16:43:14 -0700347
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700348 // Add ourself to the Watchdog monitors.
349 Watchdog.getInstance().addMonitor(this);
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700350
Lorenzo Colittia0868002017-07-11 02:29:28 +0900351 mServices.registerLocalService(new LocalService());
Lorenzo Colitti8228eb32017-07-19 06:17:33 +0900352
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900353 synchronized (mTetheringStatsProviders) {
354 mTetheringStatsProviders.put(new NetdTetheringStatsProvider(), "netd");
355 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700356 }
357
358 @VisibleForTesting
359 NetworkManagementService() {
360 mConnector = null;
361 mContext = null;
362 mDaemonHandler = null;
363 mFgHandler = null;
364 mThread = null;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900365 mServices = null;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700366 }
367
Lorenzo Colittia0868002017-07-11 02:29:28 +0900368 static NetworkManagementService create(Context context, String socket, SystemServices services)
Felipe Leme03e689d2016-03-02 16:17:38 -0800369 throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900370 final NetworkManagementService service =
371 new NetworkManagementService(context, socket, services);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700372 final CountDownLatch connectedSignal = service.mConnectedSignal;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700373 if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
374 service.mThread.start();
375 if (DBG) Slog.d(TAG, "Awaiting socket connection");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700376 connectedSignal.await();
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700377 if (DBG) Slog.d(TAG, "Connected");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900378 if (DBG) Slog.d(TAG, "Connecting native netd service");
bohu07cc3bb2016-05-03 15:58:01 -0700379 service.connectNativeNetdService();
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900380 if (DBG) Slog.d(TAG, "Connected");
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700381 return service;
San Mehat873f2142010-01-14 10:25:07 -0800382 }
383
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900384 public static NetworkManagementService create(Context context) throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900385 return create(context, NETD_SERVICE_NAME, new SystemServices());
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900386 }
387
Jeff Sharkey350083e2011-06-29 10:45:16 -0700388 public void systemReady() {
Felipe Leme03e689d2016-03-02 16:17:38 -0800389 if (DBG) {
390 final long start = System.currentTimeMillis();
391 prepareNativeDaemon();
392 final long delta = System.currentTimeMillis() - start;
393 Slog.d(TAG, "Prepared in " + delta + "ms");
394 return;
395 } else {
396 prepareNativeDaemon();
397 }
Jeff Sharkey350083e2011-06-29 10:45:16 -0700398 }
399
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800400 private IBatteryStats getBatteryStats() {
401 synchronized (this) {
402 if (mBatteryStats != null) {
403 return mBatteryStats;
404 }
Lorenzo Colittia0868002017-07-11 02:29:28 +0900405 mBatteryStats =
406 IBatteryStats.Stub.asInterface(mServices.getService(BatteryStats.SERVICE_NAME));
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800407 return mBatteryStats;
408 }
409 }
410
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800411 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800412 public void registerObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800413 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800414 mObservers.register(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800415 }
416
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800417 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800418 public void unregisterObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800419 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800420 mObservers.unregister(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800421 }
422
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900423 @FunctionalInterface
424 private interface NetworkManagementEventCallback {
425 public void sendCallback(INetworkManagementEventObserver o) throws RemoteException;
426 }
427
428 private void invokeForAllObservers(NetworkManagementEventCallback eventCallback) {
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800429 final int length = mObservers.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700430 try {
431 for (int i = 0; i < length; i++) {
432 try {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900433 eventCallback.sendCallback(mObservers.getBroadcastItem(i));
Felipe Leme03e689d2016-03-02 16:17:38 -0800434 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700435 }
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700436 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700437 } finally {
438 mObservers.finishBroadcast();
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700439 }
440 }
441
442 /**
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900443 * Notify our observers of an interface status change
444 */
445 private void notifyInterfaceStatusChanged(String iface, boolean up) {
446 invokeForAllObservers(o -> o.interfaceStatusChanged(iface, up));
447 }
448
449 /**
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700450 * Notify our observers of an interface link state change
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700451 * (typically, an Ethernet cable has been plugged-in or unplugged).
452 */
453 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900454 invokeForAllObservers(o -> o.interfaceLinkStateChanged(iface, up));
San Mehat4d02d002010-01-22 16:07:46 -0800455 }
456
457 /**
458 * Notify our observers of an interface addition.
459 */
460 private void notifyInterfaceAdded(String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900461 invokeForAllObservers(o -> o.interfaceAdded(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800462 }
463
464 /**
465 * Notify our observers of an interface removal.
466 */
467 private void notifyInterfaceRemoved(String iface) {
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700468 // netd already clears out quota and alerts for removed ifaces; update
469 // our sanity-checking state.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700470 mActiveAlerts.remove(iface);
471 mActiveQuotas.remove(iface);
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700472
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900473 invokeForAllObservers(o -> o.interfaceRemoved(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800474 }
475
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700476 /**
JP Abgrall12b933d2011-07-14 18:09:22 -0700477 * Notify our observers of a limit reached.
478 */
479 private void notifyLimitReached(String limitName, String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900480 invokeForAllObservers(o -> o.limitReached(limitName, iface));
JP Abgrall12b933d2011-07-14 18:09:22 -0700481 }
482
483 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700484 * Notify our observers of a change in the data activity state of the interface
485 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700486 private void notifyInterfaceClassActivity(int type, int powerState, long tsNanos,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700487 int uid, boolean fromRadio) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700488 final boolean isMobile = ConnectivityManager.isNetworkTypeMobile(type);
489 if (isMobile) {
490 if (!fromRadio) {
491 if (mMobileActivityFromRadio) {
492 // If this call is not coming from a report from the radio itself, but we
493 // have previously received reports from the radio, then we will take the
494 // power state to just be whatever the radio last reported.
495 powerState = mLastPowerStateFromRadio;
496 }
497 } else {
498 mMobileActivityFromRadio = true;
499 }
500 if (mLastPowerStateFromRadio != powerState) {
501 mLastPowerStateFromRadio = powerState;
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700502 try {
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700503 getBatteryStats().noteMobileRadioPowerState(powerState, tsNanos, uid);
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700504 } catch (RemoteException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700505 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700506 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700507 }
508
Adam Lesinskie08af192015-03-25 16:42:59 -0700509 if (ConnectivityManager.isNetworkTypeWifi(type)) {
510 if (mLastPowerStateFromWifi != powerState) {
511 mLastPowerStateFromWifi = powerState;
512 try {
Adam Lesinski5f056f62016-07-14 16:56:08 -0700513 getBatteryStats().noteWifiRadioPowerState(powerState, tsNanos, uid);
Adam Lesinskie08af192015-03-25 16:42:59 -0700514 } catch (RemoteException e) {
515 }
516 }
517 }
518
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700519 boolean isActive = powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
520 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
521
522 if (!isMobile || fromRadio || !mMobileActivityFromRadio) {
523 // Report the change in data activity. We don't do this if this is a change
524 // on the mobile network, that is not coming from the radio itself, and we
525 // have previously seen change reports from the radio. In that case only
526 // the radio is the authority for the current state.
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900527 final boolean active = isActive;
528 invokeForAllObservers(o -> o.interfaceClassDataActivityChanged(
529 Integer.toString(type), active, tsNanos));
Haoyu Baidb3c8672012-06-20 14:29:57 -0700530 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800531
532 boolean report = false;
533 synchronized (mIdleTimerLock) {
534 if (mActiveIdleTimers.isEmpty()) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700535 // If there are no idle timers, we are not monitoring activity, so we
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800536 // are always considered active.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700537 isActive = true;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800538 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700539 if (mNetworkActive != isActive) {
540 mNetworkActive = isActive;
541 report = isActive;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800542 }
543 }
544 if (report) {
545 reportNetworkActive();
546 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700547 }
548
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900549 @Override
550 public void registerTetheringStatsProvider(ITetheringStatsProvider provider, String name) {
551 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
552 Preconditions.checkNotNull(provider);
553 synchronized(mTetheringStatsProviders) {
554 mTetheringStatsProviders.put(provider, name);
555 }
556 }
557
558 @Override
559 public void unregisterTetheringStatsProvider(ITetheringStatsProvider provider) {
560 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
561 synchronized(mTetheringStatsProviders) {
562 mTetheringStatsProviders.remove(provider);
563 }
564 }
565
Lorenzo Colitti9f0baa92017-08-15 19:25:51 +0900566 @Override
567 public void tetherLimitReached(ITetheringStatsProvider provider) {
568 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
569 synchronized(mTetheringStatsProviders) {
570 if (!mTetheringStatsProviders.containsKey(provider)) {
571 return;
572 }
573 // No current code examines the interface parameter in a global alert. Just pass null.
574 notifyLimitReached(LIMIT_GLOBAL_ALERT, null);
575 }
576 }
577
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900578 // Sync the state of the given chain with the native daemon.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700579 private void syncFirewallChainLocked(int chain, String name) {
580 SparseIntArray rules;
581 synchronized (mRulesLock) {
582 final SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900583 // Make a copy of the current rules, and then clear them. This is because
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700584 // setFirewallUidRuleInternal only pushes down rules to the native daemon if they
585 // are different from the current rules stored in the mUidFirewall*Rules array for
586 // the specified chain. If we don't clear the rules, setFirewallUidRuleInternal
587 // will do nothing.
588 rules = uidFirewallRules.clone();
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900589 uidFirewallRules.clear();
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700590 }
591 if (rules.size() > 0) {
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900592 // Now push the rules. setFirewallUidRuleInternal will push each of these down to the
593 // native daemon, and also add them to the mUidFirewall*Rules array for the specified
594 // chain.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700595 if (DBG) Slog.d(TAG, "Pushing " + rules.size() + " active firewall "
596 + name + "UID rules");
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900597 for (int i = 0; i < rules.size(); i++) {
Felipe Lemea701cad2016-05-12 09:58:14 -0700598 setFirewallUidRuleLocked(chain, rules.keyAt(i), rules.valueAt(i));
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900599 }
600 }
601 }
602
bohu07cc3bb2016-05-03 15:58:01 -0700603 private void connectNativeNetdService() {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900604 mNetdService = mServices.getNetd();
bohu07cc3bb2016-05-03 15:58:01 -0700605 }
606
607 /**
608 * Prepare native daemon once connected, enabling modules and pushing any
609 * existing in-memory rules.
610 */
611 private void prepareNativeDaemon() {
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900612
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700613 // push any existing quota or UID rules
614 synchronized (mQuotaLock) {
Felipe Leme65be3022016-03-22 14:53:13 -0700615
Luke Huang56a03a02018-09-07 12:02:16 +0800616 // Netd unconditionally enable bandwidth control
617 SystemProperties.set(PROP_QTAGUID_ENABLED, "1");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900618
Luke Huang473eb872018-07-26 17:33:14 +0800619 mStrictEnabled = true;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900620
Felipe Leme65be3022016-03-22 14:53:13 -0700621 setDataSaverModeEnabled(mDataSaverMode);
622
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700623 int size = mActiveQuotas.size();
624 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800625 if (DBG) Slog.d(TAG, "Pushing " + size + " active quota rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700626 final HashMap<String, Long> activeQuotas = mActiveQuotas;
627 mActiveQuotas = Maps.newHashMap();
628 for (Map.Entry<String, Long> entry : activeQuotas.entrySet()) {
629 setInterfaceQuota(entry.getKey(), entry.getValue());
630 }
631 }
632
633 size = mActiveAlerts.size();
634 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800635 if (DBG) Slog.d(TAG, "Pushing " + size + " active alert rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700636 final HashMap<String, Long> activeAlerts = mActiveAlerts;
637 mActiveAlerts = Maps.newHashMap();
638 for (Map.Entry<String, Long> entry : activeAlerts.entrySet()) {
639 setInterfaceAlert(entry.getKey(), entry.getValue());
640 }
641 }
642
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700643 SparseBooleanArray uidRejectOnQuota = null;
644 SparseBooleanArray uidAcceptOnQuota = null;
645 synchronized (mRulesLock) {
646 size = mUidRejectOnMetered.size();
647 if (size > 0) {
648 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered blacklist rules");
649 uidRejectOnQuota = mUidRejectOnMetered;
650 mUidRejectOnMetered = new SparseBooleanArray();
651 }
652
653 size = mUidAllowOnMetered.size();
654 if (size > 0) {
655 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered whitelist rules");
656 uidAcceptOnQuota = mUidAllowOnMetered;
657 mUidAllowOnMetered = new SparseBooleanArray();
658 }
659 }
660 if (uidRejectOnQuota != null) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700661 for (int i = 0; i < uidRejectOnQuota.size(); i++) {
Felipe Leme65be3022016-03-22 14:53:13 -0700662 setUidMeteredNetworkBlacklist(uidRejectOnQuota.keyAt(i),
663 uidRejectOnQuota.valueAt(i));
664 }
665 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700666 if (uidAcceptOnQuota != null) {
Felipe Leme65be3022016-03-22 14:53:13 -0700667 for (int i = 0; i < uidAcceptOnQuota.size(); i++) {
668 setUidMeteredNetworkWhitelist(uidAcceptOnQuota.keyAt(i),
669 uidAcceptOnQuota.valueAt(i));
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700670 }
671 }
Jeff Sharkey605eb792014-11-04 13:34:06 -0800672
673 size = mUidCleartextPolicy.size();
674 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800675 if (DBG) Slog.d(TAG, "Pushing " + size + " active UID cleartext policies");
Jeff Sharkey605eb792014-11-04 13:34:06 -0800676 final SparseIntArray local = mUidCleartextPolicy;
677 mUidCleartextPolicy = new SparseIntArray();
678 for (int i = 0; i < local.size(); i++) {
679 setUidCleartextNetworkPolicy(local.keyAt(i), local.valueAt(i));
680 }
681 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700682
Robin Leec3736bc2017-03-10 16:19:54 +0000683 setFirewallEnabled(mFirewallEnabled);
Amith Yamasani15e472352015-04-24 19:06:07 -0700684
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700685 syncFirewallChainLocked(FIREWALL_CHAIN_NONE, "");
686 syncFirewallChainLocked(FIREWALL_CHAIN_STANDBY, "standby ");
687 syncFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, "dozable ");
688 syncFirewallChainLocked(FIREWALL_CHAIN_POWERSAVE, "powersave ");
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700689
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700690 final int[] chains =
691 {FIREWALL_CHAIN_STANDBY, FIREWALL_CHAIN_DOZABLE, FIREWALL_CHAIN_POWERSAVE};
692 for (int chain : chains) {
693 if (getFirewallChainState(chain)) {
694 setFirewallChainEnabled(chain, true);
695 }
Felipe Leme011b98f2016-02-10 17:28:31 -0800696 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700697 }
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900698
Luke Huang56a03a02018-09-07 12:02:16 +0800699
700 try {
701 getBatteryStats().noteNetworkStatsEnabled();
702 } catch (RemoteException e) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900703 }
704
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700705 }
San Mehat4d02d002010-01-22 16:07:46 -0800706
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900707 /**
708 * Notify our observers of a new or updated interface address.
709 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900710 private void notifyAddressUpdated(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900711 invokeForAllObservers(o -> o.addressUpdated(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900712 }
713
714 /**
715 * Notify our observers of a deleted interface address.
716 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900717 private void notifyAddressRemoved(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900718 invokeForAllObservers(o -> o.addressRemoved(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900719 }
720
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900721 /**
722 * Notify our observers of DNS server information received.
723 */
724 private void notifyInterfaceDnsServerInfo(String iface, long lifetime, String[] addresses) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900725 invokeForAllObservers(o -> o.interfaceDnsServerInfo(iface, lifetime, addresses));
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900726 }
727
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900728 /**
729 * Notify our observers of a route change.
730 */
731 private void notifyRouteChange(String action, RouteInfo route) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900732 if (action.equals("updated")) {
733 invokeForAllObservers(o -> o.routeUpdated(route));
734 } else {
735 invokeForAllObservers(o -> o.routeRemoved(route));
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900736 }
737 }
738
San Mehat873f2142010-01-14 10:25:07 -0800739 //
740 // Netd Callback handling
741 //
742
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700743 private class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
744 @Override
San Mehat873f2142010-01-14 10:25:07 -0800745 public void onDaemonConnected() {
Felipe Leme65be3022016-03-22 14:53:13 -0700746 Slog.i(TAG, "onDaemonConnected()");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700747 // event is dispatched from internal NDC thread, so we prepare the
748 // daemon back on main thread.
749 if (mConnectedSignal != null) {
bohu07cc3bb2016-05-03 15:58:01 -0700750 // The system is booting and we're connecting to netd for the first time.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700751 mConnectedSignal.countDown();
752 mConnectedSignal = null;
753 } else {
bohu07cc3bb2016-05-03 15:58:01 -0700754 // We're reconnecting to netd after the socket connection
755 // was interrupted (e.g., if it crashed).
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700756 mFgHandler.post(new Runnable() {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700757 @Override
758 public void run() {
bohu07cc3bb2016-05-03 15:58:01 -0700759 connectNativeNetdService();
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700760 prepareNativeDaemon();
761 }
762 });
763 }
San Mehat873f2142010-01-14 10:25:07 -0800764 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700765
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700766 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800767 public boolean onCheckHoldWakeLock(int code) {
768 return code == NetdResponseCode.InterfaceClassActivity;
769 }
770
771 @Override
San Mehat873f2142010-01-14 10:25:07 -0800772 public boolean onEvent(int code, String raw, String[] cooked) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900773 String errorMessage = String.format("Invalid event from daemon (%s)", raw);
JP Abgrall12b933d2011-07-14 18:09:22 -0700774 switch (code) {
775 case NetdResponseCode.InterfaceChange:
776 /*
777 * a network interface change occured
778 * Format: "NNN Iface added <name>"
779 * "NNN Iface removed <name>"
780 * "NNN Iface changed <name> <up/down>"
781 * "NNN Iface linkstatus <name> <up/down>"
782 */
783 if (cooked.length < 4 || !cooked[1].equals("Iface")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900784 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700785 }
786 if (cooked[2].equals("added")) {
787 notifyInterfaceAdded(cooked[3]);
788 return true;
789 } else if (cooked[2].equals("removed")) {
790 notifyInterfaceRemoved(cooked[3]);
791 return true;
792 } else if (cooked[2].equals("changed") && cooked.length == 5) {
793 notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
794 return true;
795 } else if (cooked[2].equals("linkstate") && cooked.length == 5) {
796 notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
797 return true;
798 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900799 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700800 // break;
801 case NetdResponseCode.BandwidthControl:
802 /*
803 * Bandwidth control needs some attention
804 * Format: "NNN limit alert <alertName> <ifaceName>"
805 */
806 if (cooked.length < 5 || !cooked[1].equals("limit")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900807 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700808 }
809 if (cooked[2].equals("alert")) {
810 notifyLimitReached(cooked[3], cooked[4]);
811 return true;
812 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900813 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700814 // break;
Haoyu Baidb3c8672012-06-20 14:29:57 -0700815 case NetdResponseCode.InterfaceClassActivity:
816 /*
817 * An network interface class state changed (active/idle)
818 * Format: "NNN IfaceClass <active/idle> <label>"
819 */
820 if (cooked.length < 4 || !cooked[1].equals("IfaceClass")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900821 throw new IllegalStateException(errorMessage);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700822 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700823 long timestampNanos = 0;
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700824 int processUid = -1;
825 if (cooked.length >= 5) {
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700826 try {
827 timestampNanos = Long.parseLong(cooked[4]);
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700828 if (cooked.length == 6) {
829 processUid = Integer.parseInt(cooked[5]);
830 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700831 } catch(NumberFormatException ne) {}
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700832 } else {
833 timestampNanos = SystemClock.elapsedRealtimeNanos();
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700834 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700835 boolean isActive = cooked[2].equals("active");
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700836 notifyInterfaceClassActivity(Integer.parseInt(cooked[3]),
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700837 isActive ? DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700838 : DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
839 timestampNanos, processUid, false);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700840 return true;
841 // break;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900842 case NetdResponseCode.InterfaceAddressChange:
843 /*
844 * A network address change occurred
845 * Format: "NNN Address updated <addr> <iface> <flags> <scope>"
846 * "NNN Address removed <addr> <iface> <flags> <scope>"
847 */
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900848 if (cooked.length < 7 || !cooked[1].equals("Address")) {
849 throw new IllegalStateException(errorMessage);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900850 }
851
Lorenzo Colitti64483942013-11-15 18:43:52 +0900852 String iface = cooked[4];
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900853 LinkAddress address;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900854 try {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900855 int flags = Integer.parseInt(cooked[5]);
856 int scope = Integer.parseInt(cooked[6]);
857 address = new LinkAddress(cooked[3], flags, scope);
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900858 } catch(NumberFormatException e) { // Non-numeric lifetime or scope.
859 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti64483942013-11-15 18:43:52 +0900860 } catch(IllegalArgumentException e) { // Malformed/invalid IP address.
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900861 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900862 }
863
864 if (cooked[2].equals("updated")) {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900865 notifyAddressUpdated(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900866 } else {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900867 notifyAddressRemoved(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900868 }
869 return true;
870 // break;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900871 case NetdResponseCode.InterfaceDnsServerInfo:
872 /*
873 * Information about available DNS servers has been received.
874 * Format: "NNN DnsInfo servers <interface> <lifetime> <servers>"
875 */
876 long lifetime; // Actually a 32-bit unsigned integer.
877
878 if (cooked.length == 6 &&
879 cooked[1].equals("DnsInfo") &&
880 cooked[2].equals("servers")) {
881 try {
882 lifetime = Long.parseLong(cooked[4]);
883 } catch (NumberFormatException e) {
884 throw new IllegalStateException(errorMessage);
885 }
886 String[] servers = cooked[5].split(",");
887 notifyInterfaceDnsServerInfo(cooked[3], lifetime, servers);
888 }
889 return true;
890 // break;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900891 case NetdResponseCode.RouteChange:
892 /*
893 * A route has been updated or removed.
894 * Format: "NNN Route <updated|removed> <dst> [via <gateway] [dev <iface>]"
895 */
896 if (!cooked[1].equals("Route") || cooked.length < 6) {
897 throw new IllegalStateException(errorMessage);
898 }
899
900 String via = null;
901 String dev = null;
902 boolean valid = true;
903 for (int i = 4; (i + 1) < cooked.length && valid; i += 2) {
904 if (cooked[i].equals("dev")) {
905 if (dev == null) {
906 dev = cooked[i+1];
907 } else {
908 valid = false; // Duplicate interface.
909 }
910 } else if (cooked[i].equals("via")) {
911 if (via == null) {
912 via = cooked[i+1];
913 } else {
914 valid = false; // Duplicate gateway.
915 }
916 } else {
917 valid = false; // Unknown syntax.
918 }
919 }
920 if (valid) {
921 try {
922 // InetAddress.parseNumericAddress(null) inexplicably returns ::1.
923 InetAddress gateway = null;
924 if (via != null) gateway = InetAddress.parseNumericAddress(via);
925 RouteInfo route = new RouteInfo(new IpPrefix(cooked[3]), gateway, dev);
926 notifyRouteChange(cooked[2], route);
927 return true;
928 } catch (IllegalArgumentException e) {}
929 }
930 throw new IllegalStateException(errorMessage);
931 // break;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800932 case NetdResponseCode.StrictCleartext:
933 final int uid = Integer.parseInt(cooked[1]);
934 final byte[] firstPacket = HexDump.hexStringToByteArray(cooked[2]);
935 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800936 ActivityManager.getService().notifyCleartextNetwork(uid, firstPacket);
Jeff Sharkey605eb792014-11-04 13:34:06 -0800937 } catch (RemoteException ignored) {
938 }
939 break;
JP Abgrall12b933d2011-07-14 18:09:22 -0700940 default: break;
Robert Greenwalte3253922010-02-18 09:23:25 -0800941 }
942 return false;
San Mehat873f2142010-01-14 10:25:07 -0800943 }
944 }
945
San Mehated4fc8a2010-01-22 12:28:36 -0800946
San Mehat873f2142010-01-14 10:25:07 -0800947 //
948 // INetworkManagementService members
949 //
Erik Kline4e37b702016-07-05 11:34:21 +0900950 @Override
951 public INetd getNetdService() throws RemoteException {
952 final CountDownLatch connectedSignal = mConnectedSignal;
953 if (connectedSignal != null) {
954 try {
955 connectedSignal.await();
956 } catch (InterruptedException ignored) {}
957 }
958
959 return mNetdService;
960 }
San Mehat873f2142010-01-14 10:25:07 -0800961
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800962 @Override
963 public String[] listInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800964 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700965 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800966 return NativeDaemonEvent.filterMessageList(
967 mConnector.executeForList("interface", "list"), InterfaceListResult);
Kenny Roota80ce062010-06-01 13:23:53 -0700968 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800969 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700970 }
San Mehated4fc8a2010-01-22 12:28:36 -0800971 }
972
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800973 @Override
974 public InterfaceConfiguration getInterfaceConfig(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800975 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800976
977 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -0700978 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800979 event = mConnector.execute("interface", "getcfg", iface);
Kenny Roota80ce062010-06-01 13:23:53 -0700980 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800981 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700982 }
San Mehated4fc8a2010-01-22 12:28:36 -0800983
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800984 event.checkCode(InterfaceGetCfgResult);
985
986 // Rsp: 213 xx:xx:xx:xx:xx:xx yyy.yyy.yyy.yyy zzz flag1 flag2 flag3
987 final StringTokenizer st = new StringTokenizer(event.getMessage());
San Mehated4fc8a2010-01-22 12:28:36 -0800988
Kenny Roota80ce062010-06-01 13:23:53 -0700989 InterfaceConfiguration cfg;
San Mehated4fc8a2010-01-22 12:28:36 -0800990 try {
Kenny Roota80ce062010-06-01 13:23:53 -0700991 cfg = new InterfaceConfiguration();
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800992 cfg.setHardwareAddress(st.nextToken(" "));
Robert Greenwalted126402011-01-28 15:34:55 -0800993 InetAddress addr = null;
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800994 int prefixLength = 0;
Kenny Roota80ce062010-06-01 13:23:53 -0700995 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800996 addr = NetworkUtils.numericToInetAddress(st.nextToken());
Robert Greenwalte5903732011-02-22 16:00:42 -0800997 } catch (IllegalArgumentException iae) {
998 Slog.e(TAG, "Failed to parse ipaddr", iae);
Kenny Roota80ce062010-06-01 13:23:53 -0700999 }
1000
1001 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001002 prefixLength = Integer.parseInt(st.nextToken());
Robert Greenwalt2d2afd12011-02-01 15:30:46 -08001003 } catch (NumberFormatException nfe) {
1004 Slog.e(TAG, "Failed to parse prefixLength", nfe);
Kenny Roota80ce062010-06-01 13:23:53 -07001005 }
Robert Greenwalt04808c22010-12-13 17:01:41 -08001006
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001007 cfg.setLinkAddress(new LinkAddress(addr, prefixLength));
1008 while (st.hasMoreTokens()) {
1009 cfg.setFlag(st.nextToken());
1010 }
Kenny Roota80ce062010-06-01 13:23:53 -07001011 } catch (NoSuchElementException nsee) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001012 throw new IllegalStateException("Invalid response from daemon: " + event);
San Mehated4fc8a2010-01-22 12:28:36 -08001013 }
San Mehated4fc8a2010-01-22 12:28:36 -08001014 return cfg;
1015 }
1016
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001017 @Override
1018 public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001019 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001020 LinkAddress linkAddr = cfg.getLinkAddress();
Robert Greenwalt2d2afd12011-02-01 15:30:46 -08001021 if (linkAddr == null || linkAddr.getAddress() == null) {
1022 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -08001023 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001024
1025 final Command cmd = new Command("interface", "setcfg", iface,
Robert Greenwalt2d2afd12011-02-01 15:30:46 -08001026 linkAddr.getAddress().getHostAddress(),
Lorenzo Colitti7dc78cf2014-06-09 22:58:46 +09001027 linkAddr.getPrefixLength());
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001028 for (String flag : cfg.getFlags()) {
1029 cmd.appendArg(flag);
1030 }
1031
Kenny Roota80ce062010-06-01 13:23:53 -07001032 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001033 mConnector.execute(cmd);
Kenny Roota80ce062010-06-01 13:23:53 -07001034 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001035 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001036 }
San Mehat873f2142010-01-14 10:25:07 -08001037 }
1038
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001039 @Override
1040 public void setInterfaceDown(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001041 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001042 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001043 ifcg.setInterfaceDown();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001044 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001045 }
1046
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001047 @Override
1048 public void setInterfaceUp(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.setInterfaceUp();
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 setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001057 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sheriff73293612011-09-14 12:31:56 -07001058 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001059 mConnector.execute(
1060 "interface", "ipv6privacyextensions", iface, enable ? "enable" : "disable");
Irfan Sheriff73293612011-09-14 12:31:56 -07001061 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001062 throw e.rethrowAsParcelableException();
Irfan Sheriff73293612011-09-14 12:31:56 -07001063 }
1064 }
1065
Irfan Sherifff5600612011-06-16 10:26:28 -07001066 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
1067 IPv6 addresses on interface down, but we need to do full clean up here */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001068 @Override
1069 public void clearInterfaceAddresses(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001070 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sherifff5600612011-06-16 10:26:28 -07001071 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001072 mConnector.execute("interface", "clearaddrs", iface);
Irfan Sherifff5600612011-06-16 10:26:28 -07001073 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001074 throw e.rethrowAsParcelableException();
Irfan Sherifff5600612011-06-16 10:26:28 -07001075 }
1076 }
1077
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001078 @Override
1079 public void enableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001080 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001081 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001082 mConnector.execute("interface", "ipv6", iface, "enable");
repo sync7960d9f2011-09-29 12:40:02 -07001083 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001084 throw e.rethrowAsParcelableException();
repo sync7960d9f2011-09-29 12:40:02 -07001085 }
1086 }
1087
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001088 @Override
Joel Scherpelz2db10742017-06-07 15:38:38 +09001089 public void setIPv6AddrGenMode(String iface, int mode) throws ServiceSpecificException {
1090 try {
1091 mNetdService.setIPv6AddrGenMode(iface, mode);
1092 } catch (RemoteException e) {
1093 throw e.rethrowAsRuntimeException();
1094 }
1095 }
1096
1097 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001098 public void disableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001099 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001100 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001101 mConnector.execute("interface", "ipv6", iface, "disable");
repo sync7960d9f2011-09-29 12:40:02 -07001102 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001103 throw e.rethrowAsParcelableException();
repo sync7960d9f2011-09-29 12:40:02 -07001104 }
1105 }
1106
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001107 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001108 public void addRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001109 modifyRoute(MODIFY_OPERATION_ADD, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001110 }
1111
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001112 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001113 public void removeRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001114 modifyRoute(MODIFY_OPERATION_REMOVE, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001115 }
1116
Luke Huang8a462ec2018-08-24 20:33:16 +08001117 private void modifyRoute(boolean add, int netId, RouteInfo route) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001118 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001119
Luke Huang8a462ec2018-08-24 20:33:16 +08001120 final String ifName = route.getInterface();
1121 final String dst = route.getDestination().toString();
1122 final String nextHop;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001123
1124 switch (route.getType()) {
1125 case RouteInfo.RTN_UNICAST:
1126 if (route.hasGateway()) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001127 nextHop = route.getGateway().getHostAddress();
1128 } else {
1129 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001130 }
1131 break;
1132 case RouteInfo.RTN_UNREACHABLE:
Luke Huang8a462ec2018-08-24 20:33:16 +08001133 nextHop = INetd.NEXTHOP_UNREACHABLE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001134 break;
1135 case RouteInfo.RTN_THROW:
Luke Huang8a462ec2018-08-24 20:33:16 +08001136 nextHop = INetd.NEXTHOP_THROW;
1137 break;
1138 default:
1139 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001140 break;
Sreeram Ramachandran1fbcb272014-05-22 16:30:48 -07001141 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001142 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08001143 if (add) {
1144 mNetdService.networkAddRoute(netId, ifName, dst, nextHop);
1145 } else {
1146 mNetdService.networkRemoveRoute(netId, ifName, dst, nextHop);
1147 }
1148 } catch (RemoteException | ServiceSpecificException e) {
1149 throw new IllegalStateException(e);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001150 }
1151 }
1152
1153 private ArrayList<String> readRouteList(String filename) {
1154 FileInputStream fstream = null;
Christopher Wiley212b95f2016-08-02 11:38:57 -07001155 ArrayList<String> list = new ArrayList<>();
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001156
1157 try {
1158 fstream = new FileInputStream(filename);
1159 DataInputStream in = new DataInputStream(fstream);
1160 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1161 String s;
1162
1163 // throw away the title line
1164
1165 while (((s = br.readLine()) != null) && (s.length() != 0)) {
1166 list.add(s);
1167 }
1168 } catch (IOException ex) {
1169 // return current list, possibly empty
1170 } finally {
1171 if (fstream != null) {
1172 try {
1173 fstream.close();
1174 } catch (IOException ex) {}
1175 }
1176 }
1177
1178 return list;
1179 }
1180
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001181 @Override
sy.yun9d9b74a2013-09-02 05:24:09 +09001182 public void setMtu(String iface, int mtu) {
1183 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1184
1185 final NativeDaemonEvent event;
1186 try {
1187 event = mConnector.execute("interface", "setmtu", iface, mtu);
1188 } catch (NativeDaemonConnectorException e) {
1189 throw e.rethrowAsParcelableException();
1190 }
1191 }
1192
1193 @Override
San Mehat873f2142010-01-14 10:25:07 -08001194 public void shutdown() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001195 // TODO: remove from aidl if nobody calls externally
1196 mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001197
Felipe Leme03e689d2016-03-02 16:17:38 -08001198 Slog.i(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -08001199 }
1200
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001201 @Override
San Mehat873f2142010-01-14 10:25:07 -08001202 public boolean getIpForwardingEnabled() throws IllegalStateException{
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001203 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001204
Kenny Roota80ce062010-06-01 13:23:53 -07001205 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001206 final boolean isEnabled = mNetdService.ipfwdEnabled();
1207 return isEnabled;
1208 } catch (RemoteException | ServiceSpecificException e) {
1209 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001210 }
San Mehat873f2142010-01-14 10:25:07 -08001211 }
1212
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001213 @Override
1214 public void setIpForwardingEnabled(boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001215 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001216 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001217 if (enable) {
1218 mNetdService.ipfwdEnableForwarding("tethering");
1219 } else {
1220 mNetdService.ipfwdDisableForwarding("tethering");
1221 }
1222 } catch (RemoteException | ServiceSpecificException e) {
1223 throw new IllegalStateException(e);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001224 }
San Mehat873f2142010-01-14 10:25:07 -08001225 }
1226
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001227 @Override
1228 public void startTethering(String[] dhcpRange) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001229 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -07001230 // an odd number of addrs will fail
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001231
Kenny Roota80ce062010-06-01 13:23:53 -07001232 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001233 mNetdService.tetherStart(dhcpRange);
1234 } catch (RemoteException | ServiceSpecificException e) {
1235 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001236 }
San Mehat873f2142010-01-14 10:25:07 -08001237 }
1238
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001239 @Override
1240 public void stopTethering() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001241 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001242 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001243 mNetdService.tetherStop();
1244 } catch (RemoteException | ServiceSpecificException e) {
1245 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001246 }
San Mehat873f2142010-01-14 10:25:07 -08001247 }
1248
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001249 @Override
1250 public boolean isTetheringStarted() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001251 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001252
Kenny Roota80ce062010-06-01 13:23:53 -07001253 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001254 final boolean isEnabled = mNetdService.tetherIsEnabled();
1255 return isEnabled;
1256 } catch (RemoteException | ServiceSpecificException e) {
1257 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001258 }
San Mehat873f2142010-01-14 10:25:07 -08001259 }
Matthew Xiefe19f122012-07-12 16:03:32 -07001260
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001261 @Override
1262 public void tetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001263 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001264 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001265 mNetdService.tetherInterfaceAdd(iface);
1266 } catch (RemoteException | ServiceSpecificException e) {
1267 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001268 }
Christopher Wiley212b95f2016-08-02 11:38:57 -07001269 List<RouteInfo> routes = new ArrayList<>();
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07001270 // The RouteInfo constructor truncates the LinkAddress to a network prefix, thus making it
1271 // suitable to use as a route destination.
1272 routes.add(new RouteInfo(getInterfaceConfig(iface).getLinkAddress(), null, iface));
1273 addInterfaceToLocalNetwork(iface, routes);
San Mehat873f2142010-01-14 10:25:07 -08001274 }
1275
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001276 @Override
San Mehat873f2142010-01-14 10:25:07 -08001277 public void untetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001278 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001279 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001280 mNetdService.tetherInterfaceRemove(iface);
1281 } catch (RemoteException | ServiceSpecificException e) {
1282 throw new IllegalStateException(e);
Erik Kline1f4278a2016-08-16 16:46:33 +09001283 } finally {
1284 removeInterfaceFromLocalNetwork(iface);
Kenny Roota80ce062010-06-01 13:23:53 -07001285 }
San Mehat873f2142010-01-14 10:25:07 -08001286 }
1287
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001288 @Override
1289 public String[] listTetheredInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001290 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001291 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001292 final List<String> result = mNetdService.tetherInterfaceList();
1293 return result.toArray(EMPTY_STRING_ARRAY);
1294 } catch (RemoteException | ServiceSpecificException e) {
1295 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001296 }
San Mehat873f2142010-01-14 10:25:07 -08001297 }
1298
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001299 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001300 public void setDnsForwarders(Network network, String[] dns) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001301 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001302
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001303 int netId = (network != null) ? network.netId : ConnectivityManager.NETID_UNSET;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001304
San Mehat873f2142010-01-14 10:25:07 -08001305 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001306 mNetdService.tetherDnsSet(netId, dns);
1307 } catch (RemoteException | ServiceSpecificException e) {
1308 throw new IllegalStateException(e);
San Mehat873f2142010-01-14 10:25:07 -08001309 }
1310 }
1311
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001312 @Override
1313 public String[] getDnsForwarders() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001314 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001315 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001316 final List<String> result = mNetdService.tetherDnsList();
1317 return result.toArray(EMPTY_STRING_ARRAY);
1318 } catch (RemoteException | ServiceSpecificException e) {
1319 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001320 }
San Mehat873f2142010-01-14 10:25:07 -08001321 }
1322
jiaguo1da35f72014-01-09 16:39:59 +08001323 private List<InterfaceAddress> excludeLinkLocal(List<InterfaceAddress> addresses) {
Christopher Wiley212b95f2016-08-02 11:38:57 -07001324 ArrayList<InterfaceAddress> filtered = new ArrayList<>(addresses.size());
jiaguo1da35f72014-01-09 16:39:59 +08001325 for (InterfaceAddress ia : addresses) {
1326 if (!ia.getAddress().isLinkLocalAddress())
1327 filtered.add(ia);
1328 }
1329 return filtered;
1330 }
1331
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001332 private void modifyInterfaceForward(boolean add, String fromIface, String toIface) {
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001333 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001334 if (add) {
1335 mNetdService.ipfwdAddInterfaceForward(fromIface, toIface);
1336 } else {
1337 mNetdService.ipfwdRemoveInterfaceForward(fromIface, toIface);
1338 }
1339 } catch (RemoteException | ServiceSpecificException e) {
1340 throw new IllegalStateException(e);
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001341 }
1342 }
1343
1344 @Override
1345 public void startInterfaceForwarding(String fromIface, String toIface) {
1346 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1347 modifyInterfaceForward(true, fromIface, toIface);
1348 }
1349
1350 @Override
1351 public void stopInterfaceForwarding(String fromIface, String toIface) {
1352 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1353 modifyInterfaceForward(false, fromIface, toIface);
1354 }
1355
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001356 private void modifyNat(String action, String internalInterface, String externalInterface)
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001357 throws SocketException {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001358 final Command cmd = new Command("nat", action, internalInterface, externalInterface);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001359
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001360 final NetworkInterface internalNetworkInterface = NetworkInterface.getByName(
1361 internalInterface);
Robert Greenwalte83d1812011-11-21 14:44:39 -08001362 if (internalNetworkInterface == null) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001363 cmd.appendArg("0");
Robert Greenwalte83d1812011-11-21 14:44:39 -08001364 } else {
jiaguo1da35f72014-01-09 16:39:59 +08001365 // Don't touch link-local routes, as link-local addresses aren't routable,
1366 // kernel creates link-local routes on all interfaces automatically
1367 List<InterfaceAddress> interfaceAddresses = excludeLinkLocal(
1368 internalNetworkInterface.getInterfaceAddresses());
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001369 cmd.appendArg(interfaceAddresses.size());
Robert Greenwalte83d1812011-11-21 14:44:39 -08001370 for (InterfaceAddress ia : interfaceAddresses) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001371 InetAddress addr = NetworkUtils.getNetworkPart(
1372 ia.getAddress(), ia.getNetworkPrefixLength());
1373 cmd.appendArg(addr.getHostAddress() + "/" + ia.getNetworkPrefixLength());
Robert Greenwalte83d1812011-11-21 14:44:39 -08001374 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001375 }
1376
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001377 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001378 mConnector.execute(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001379 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001380 throw e.rethrowAsParcelableException();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001381 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001382 }
1383
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001384 @Override
1385 public void enableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001386 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001387 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001388 modifyNat("enable", internalInterface, externalInterface);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001389 } catch (SocketException e) {
1390 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001391 }
San Mehat873f2142010-01-14 10:25:07 -08001392 }
1393
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001394 @Override
1395 public void disableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001396 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001397 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001398 modifyNat("disable", internalInterface, externalInterface);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001399 } catch (SocketException e) {
1400 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001401 }
San Mehat873f2142010-01-14 10:25:07 -08001402 }
San Mehat72759df2010-01-19 13:50:37 -08001403
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001404 @Override
1405 public String[] listTtys() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001406 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001407 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001408 return NativeDaemonEvent.filterMessageList(
1409 mConnector.executeForList("list_ttys"), TtyListResult);
Kenny Roota80ce062010-06-01 13:23:53 -07001410 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001411 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001412 }
San Mehat72759df2010-01-19 13:50:37 -08001413 }
1414
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001415 @Override
1416 public void attachPppd(
1417 String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001418 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat72759df2010-01-19 13:50:37 -08001419 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001420 mConnector.execute("pppd", "attach", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -08001421 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
1422 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
1423 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001424 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress());
Kenny Roota80ce062010-06-01 13:23:53 -07001425 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001426 throw e.rethrowAsParcelableException();
San Mehat72759df2010-01-19 13:50:37 -08001427 }
1428 }
1429
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001430 @Override
1431 public void detachPppd(String tty) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001432 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001433 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001434 mConnector.execute("pppd", "detach", tty);
Kenny Roota80ce062010-06-01 13:23:53 -07001435 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001436 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001437 }
San Mehat72759df2010-01-19 13:50:37 -08001438 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -08001439
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001440 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001441 public void addIdleTimer(String iface, int timeout, final int type) {
Haoyu Bai04124232012-06-28 15:26:19 -07001442 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1443
1444 if (DBG) Slog.d(TAG, "Adding idletimer");
1445
1446 synchronized (mIdleTimerLock) {
1447 IdleTimerParams params = mActiveIdleTimers.get(iface);
1448 if (params != null) {
1449 // the interface already has idletimer, update network count
1450 params.networkCount++;
1451 return;
1452 }
1453
1454 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001455 mNetdService.idletimerAddInterface(iface, timeout, Integer.toString(type));
1456 } catch (RemoteException | ServiceSpecificException e) {
1457 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001458 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001459 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
1460
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001461 // Networks start up.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001462 if (ConnectivityManager.isNetworkTypeMobile(type)) {
1463 mNetworkActive = false;
1464 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001465 mDaemonHandler.post(new Runnable() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001466 @Override public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001467 notifyInterfaceClassActivity(type,
1468 DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07001469 SystemClock.elapsedRealtimeNanos(), -1, false);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001470 }
1471 });
Haoyu Bai04124232012-06-28 15:26:19 -07001472 }
1473 }
1474
1475 @Override
1476 public void removeIdleTimer(String iface) {
1477 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1478
1479 if (DBG) Slog.d(TAG, "Removing idletimer");
1480
1481 synchronized (mIdleTimerLock) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001482 final IdleTimerParams params = mActiveIdleTimers.get(iface);
Haoyu Bai04124232012-06-28 15:26:19 -07001483 if (params == null || --(params.networkCount) > 0) {
1484 return;
1485 }
1486
1487 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001488 mNetdService.idletimerRemoveInterface(iface,
1489 params.timeout, Integer.toString(params.type));
1490 } catch (RemoteException | ServiceSpecificException e) {
1491 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001492 }
1493 mActiveIdleTimers.remove(iface);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001494 mDaemonHandler.post(new Runnable() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001495 @Override public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001496 notifyInterfaceClassActivity(params.type,
1497 DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07001498 SystemClock.elapsedRealtimeNanos(), -1, false);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001499 }
1500 });
Haoyu Bai04124232012-06-28 15:26:19 -07001501 }
1502 }
1503
1504 @Override
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001505 public NetworkStats getNetworkStatsSummaryDev() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001506 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001507 try {
1508 return mStatsFactory.readNetworkStatsSummaryDev();
1509 } catch (IOException e) {
1510 throw new IllegalStateException(e);
1511 }
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001512 }
1513
1514 @Override
1515 public NetworkStats getNetworkStatsSummaryXt() {
1516 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001517 try {
1518 return mStatsFactory.readNetworkStatsSummaryXt();
1519 } catch (IOException e) {
1520 throw new IllegalStateException(e);
1521 }
Jeff Sharkeyae2c1812011-10-04 13:11:40 -07001522 }
1523
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001524 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001525 public NetworkStats getNetworkStatsDetail() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001526 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001527 try {
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08001528 return mStatsFactory.readNetworkStatsDetail(UID_ALL, null, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001529 } catch (IOException e) {
1530 throw new IllegalStateException(e);
1531 }
San Mehat91cac642010-03-31 14:31:36 -07001532 }
1533
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001534 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001535 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001536 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001537
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001538 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001539 if (mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001540 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001541 }
1542
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001543 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001544 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001545 mNetdService.bandwidthSetInterfaceQuota(iface, quotaBytes);
1546
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001547 mActiveQuotas.put(iface, quotaBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001548 } catch (RemoteException | ServiceSpecificException e) {
1549 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001550 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001551
1552 synchronized (mTetheringStatsProviders) {
1553 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1554 try {
1555 provider.setInterfaceQuota(iface, quotaBytes);
1556 } catch (RemoteException e) {
1557 Log.e(TAG, "Problem setting tethering data limit on provider " +
1558 mTetheringStatsProviders.get(provider) + ": " + e);
1559 }
1560 }
1561 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001562 }
1563 }
1564
1565 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001566 public void removeInterfaceQuota(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001567 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001568
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001569 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001570 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001571 // TODO: eventually consider throwing
1572 return;
1573 }
1574
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001575 mActiveQuotas.remove(iface);
1576 mActiveAlerts.remove(iface);
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001577
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001578 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001579 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001580 mNetdService.bandwidthRemoveInterfaceQuota(iface);
1581 } catch (RemoteException | ServiceSpecificException e) {
1582 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001583 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001584
1585 synchronized (mTetheringStatsProviders) {
1586 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1587 try {
1588 provider.setInterfaceQuota(iface, ITetheringStatsProvider.QUOTA_UNLIMITED);
1589 } catch (RemoteException e) {
1590 Log.e(TAG, "Problem removing tethering data limit on provider " +
1591 mTetheringStatsProviders.get(provider) + ": " + e);
1592 }
1593 }
1594 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001595 }
1596 }
1597
1598 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001599 public void setInterfaceAlert(String iface, long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001600 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001601
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001602 // quick sanity check
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001603 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001604 throw new IllegalStateException("setting alert requires existing quota on iface");
1605 }
1606
1607 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001608 if (mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001609 throw new IllegalStateException("iface " + iface + " already has alert");
1610 }
1611
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001612 try {
1613 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001614 mNetdService.bandwidthSetInterfaceAlert(iface, alertBytes);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001615 mActiveAlerts.put(iface, alertBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001616 } catch (RemoteException | ServiceSpecificException e) {
1617 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001618 }
1619 }
1620 }
1621
1622 @Override
1623 public void removeInterfaceAlert(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001624 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001625
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001626 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001627 if (!mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001628 // TODO: eventually consider throwing
1629 return;
1630 }
1631
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001632 try {
1633 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001634 mNetdService.bandwidthRemoveInterfaceAlert(iface);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001635 mActiveAlerts.remove(iface);
Luke Huangc7bea8662018-08-07 16:04:26 +08001636 } catch (RemoteException | ServiceSpecificException e) {
1637 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001638 }
1639 }
1640 }
1641
1642 @Override
1643 public void setGlobalAlert(long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001644 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001645
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001646 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001647 mNetdService.bandwidthSetGlobalAlert(alertBytes);
1648 } catch (RemoteException | ServiceSpecificException e) {
1649 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001650 }
1651 }
1652
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001653 private void setUidOnMeteredNetworkList(int uid, boolean blacklist, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001654 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001655
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001656 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001657 boolean oldEnable;
1658 SparseBooleanArray quotaList;
1659 synchronized (mRulesLock) {
1660 quotaList = blacklist ? mUidRejectOnMetered : mUidAllowOnMetered;
1661 oldEnable = quotaList.get(uid, false);
1662 }
Felipe Leme65be3022016-03-22 14:53:13 -07001663 if (oldEnable == enable) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001664 // TODO: eventually consider throwing
1665 return;
1666 }
1667
Felipe Leme29e72ea2016-09-08 13:26:55 -07001668 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "inetd bandwidth");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001669 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001670 if (blacklist) {
1671 if (enable) {
1672 mNetdService.bandwidthAddNaughtyApp(uid);
1673 } else {
1674 mNetdService.bandwidthRemoveNaughtyApp(uid);
1675 }
1676 } else {
1677 if (enable) {
1678 mNetdService.bandwidthAddNiceApp(uid);
1679 } else {
1680 mNetdService.bandwidthRemoveNiceApp(uid);
1681 }
1682 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001683 synchronized (mRulesLock) {
1684 if (enable) {
1685 quotaList.put(uid, true);
1686 } else {
1687 quotaList.delete(uid);
1688 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001689 }
Luke Huangc7bea8662018-08-07 16:04:26 +08001690 } catch (RemoteException | ServiceSpecificException e) {
1691 throw new IllegalStateException(e);
Felipe Leme29e72ea2016-09-08 13:26:55 -07001692 } finally {
1693 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001694 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001695 }
1696 }
1697
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001698 @Override
Felipe Leme65be3022016-03-22 14:53:13 -07001699 public void setUidMeteredNetworkBlacklist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001700 setUidOnMeteredNetworkList(uid, true, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001701 }
1702
1703 @Override
1704 public void setUidMeteredNetworkWhitelist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001705 setUidOnMeteredNetworkList(uid, false, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001706 }
1707
1708 @Override
1709 public boolean setDataSaverModeEnabled(boolean enable) {
Sehee Parka9139bc2017-12-22 13:54:05 +09001710 mContext.enforceCallingOrSelfPermission(NETWORK_SETTINGS, TAG);
1711
Felipe Leme65be3022016-03-22 14:53:13 -07001712 if (DBG) Log.d(TAG, "setDataSaverMode: " + enable);
1713 synchronized (mQuotaLock) {
1714 if (mDataSaverMode == enable) {
1715 Log.w(TAG, "setDataSaverMode(): already " + mDataSaverMode);
1716 return true;
1717 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07001718 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "bandwidthEnableDataSaver");
Felipe Leme65be3022016-03-22 14:53:13 -07001719 try {
1720 final boolean changed = mNetdService.bandwidthEnableDataSaver(enable);
1721 if (changed) {
1722 mDataSaverMode = enable;
1723 } else {
1724 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command silently failed");
1725 }
1726 return changed;
1727 } catch (RemoteException e) {
1728 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command failed", e);
1729 return false;
Felipe Leme29e72ea2016-09-08 13:26:55 -07001730 } finally {
1731 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme65be3022016-03-22 14:53:13 -07001732 }
1733 }
1734 }
1735
1736 @Override
Robin Lee17e61832016-05-09 13:46:28 +01001737 public void setAllowOnlyVpnForUids(boolean add, UidRange[] uidRanges)
1738 throws ServiceSpecificException {
Rubin Xu2ea6c552018-01-11 10:59:19 +00001739 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
1740
Robin Lee17e61832016-05-09 13:46:28 +01001741 try {
1742 mNetdService.networkRejectNonSecureVpn(add, uidRanges);
1743 } catch (ServiceSpecificException e) {
1744 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1745 + ": netd command failed", e);
1746 throw e;
1747 } catch (RemoteException e) {
1748 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1749 + ": netd command failed", e);
1750 throw e.rethrowAsRuntimeException();
1751 }
1752 }
1753
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001754 private void applyUidCleartextNetworkPolicy(int uid, int policy) {
Luke Huang473eb872018-07-26 17:33:14 +08001755 final int policyValue;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001756 switch (policy) {
1757 case StrictMode.NETWORK_POLICY_ACCEPT:
Luke Huang473eb872018-07-26 17:33:14 +08001758 policyValue = INetd.PENALTY_POLICY_ACCEPT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001759 break;
1760 case StrictMode.NETWORK_POLICY_LOG:
Luke Huang473eb872018-07-26 17:33:14 +08001761 policyValue = INetd.PENALTY_POLICY_LOG;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001762 break;
1763 case StrictMode.NETWORK_POLICY_REJECT:
Luke Huang473eb872018-07-26 17:33:14 +08001764 policyValue = INetd.PENALTY_POLICY_REJECT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001765 break;
1766 default:
1767 throw new IllegalArgumentException("Unknown policy " + policy);
1768 }
1769
1770 try {
Luke Huang473eb872018-07-26 17:33:14 +08001771 mNetdService.strictUidCleartextPenalty(uid, policyValue);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001772 mUidCleartextPolicy.put(uid, policy);
Luke Huang473eb872018-07-26 17:33:14 +08001773 } catch (RemoteException | ServiceSpecificException e) {
1774 throw new IllegalStateException(e);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001775 }
1776 }
1777
Robin Lee17e61832016-05-09 13:46:28 +01001778 @Override
Jeff Sharkey605eb792014-11-04 13:34:06 -08001779 public void setUidCleartextNetworkPolicy(int uid, int policy) {
1780 if (Binder.getCallingUid() != uid) {
1781 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1782 }
1783
1784 synchronized (mQuotaLock) {
1785 final int oldPolicy = mUidCleartextPolicy.get(uid, StrictMode.NETWORK_POLICY_ACCEPT);
1786 if (oldPolicy == policy) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001787 // This also ensures we won't needlessly apply an ACCEPT policy if we've just
1788 // enabled strict and the underlying iptables rules are empty.
Jeff Sharkey605eb792014-11-04 13:34:06 -08001789 return;
1790 }
1791
Luke Huang473eb872018-07-26 17:33:14 +08001792 // TODO: remove this code after removing prepareNativeDaemon()
Jeff Sharkey605eb792014-11-04 13:34:06 -08001793 if (!mStrictEnabled) {
1794 // Module isn't enabled yet; stash the requested policy away to
1795 // apply later once the daemon is connected.
1796 mUidCleartextPolicy.put(uid, policy);
1797 return;
1798 }
1799
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001800 // netd does not keep state on strict mode policies, and cannot replace a non-accept
1801 // policy without deleting it first. Rather than add state to netd, just always send
1802 // it an accept policy when switching between two non-accept policies.
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001803 // TODO: consider keeping state in netd so we can simplify this code.
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001804 if (oldPolicy != StrictMode.NETWORK_POLICY_ACCEPT &&
1805 policy != StrictMode.NETWORK_POLICY_ACCEPT) {
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001806 applyUidCleartextNetworkPolicy(uid, StrictMode.NETWORK_POLICY_ACCEPT);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001807 }
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001808
1809 applyUidCleartextNetworkPolicy(uid, policy);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001810 }
1811 }
1812
1813 @Override
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001814 public boolean isBandwidthControlEnabled() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001815 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang56a03a02018-09-07 12:02:16 +08001816 return true;
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001817 }
1818
1819 @Override
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001820 public NetworkStats getNetworkStatsUidDetail(int uid, String[] ifaces) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001821 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001822 try {
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001823 return mStatsFactory.readNetworkStatsDetail(uid, ifaces, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001824 } catch (IOException e) {
1825 throw new IllegalStateException(e);
1826 }
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001827 }
1828
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001829 private class NetdTetheringStatsProvider extends ITetheringStatsProvider.Stub {
1830 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001831 public NetworkStats getTetherStats(int how) {
1832 // We only need to return per-UID stats. Per-device stats are already counted by
1833 // interface counters.
1834 if (how != STATS_PER_UID) {
1835 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
1836 }
1837
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001838 final PersistableBundle bundle;
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001839 try {
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001840 bundle = mNetdService.tetherGetStats();
1841 } catch (RemoteException | ServiceSpecificException e) {
1842 throw new IllegalStateException("problem parsing tethering stats: ", e);
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001843 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001844
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001845 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(),
1846 bundle.size());
1847 final NetworkStats.Entry entry = new NetworkStats.Entry();
1848
1849 for (String iface : bundle.keySet()) {
1850 long[] statsArray = bundle.getLongArray(iface);
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001851 try {
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001852 entry.iface = iface;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001853 entry.uid = UID_TETHERING;
1854 entry.set = SET_DEFAULT;
1855 entry.tag = TAG_NONE;
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001856 entry.rxBytes = statsArray[INetd.TETHER_STATS_RX_BYTES];
1857 entry.rxPackets = statsArray[INetd.TETHER_STATS_RX_PACKETS];
1858 entry.txBytes = statsArray[INetd.TETHER_STATS_TX_BYTES];
1859 entry.txPackets = statsArray[INetd.TETHER_STATS_TX_PACKETS];
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001860 stats.combineValues(entry);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001861 } catch (ArrayIndexOutOfBoundsException e) {
1862 throw new IllegalStateException("invalid tethering stats for " + iface, e);
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001863 }
1864 }
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001865
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001866 return stats;
1867 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001868
1869 @Override
1870 public void setInterfaceQuota(String iface, long quotaBytes) {
1871 // Do nothing. netd is already informed of quota changes in setInterfaceQuota.
1872 }
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001873 }
1874
1875 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001876 public NetworkStats getNetworkStatsTethering(int how) {
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001877 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1878
1879 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1880 synchronized (mTetheringStatsProviders) {
1881 for (ITetheringStatsProvider provider: mTetheringStatsProviders.keySet()) {
1882 try {
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001883 stats.combineAllValues(provider.getTetherStats(how));
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001884 } catch (RemoteException e) {
1885 Log.e(TAG, "Problem reading tethering stats from " +
1886 mTetheringStatsProviders.get(provider) + ": " + e);
1887 }
1888 }
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001889 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001890 return stats;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001891 }
1892
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001893 @Override
Erik Kline1742fe12017-12-13 19:40:49 +09001894 public void setDnsConfigurationForNetwork(int netId, String[] servers, String[] domains,
Erik Klinee5dac902018-03-04 21:01:01 +09001895 int[] params, String tlsHostname, String[] tlsServers) {
Pierre Imai8e48e672016-04-21 13:30:43 +09001896 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1897
Ben Schwartz6ec28df2017-10-02 13:08:06 -04001898 final String[] tlsFingerprints = new String[0];
Pierre Imai8e48e672016-04-21 13:30:43 +09001899 try {
Erik Kline1742fe12017-12-13 19:40:49 +09001900 mNetdService.setResolverConfiguration(
Erik Klinee5dac902018-03-04 21:01:01 +09001901 netId, servers, domains, params, tlsHostname, tlsServers, tlsFingerprints);
Pierre Imai8e48e672016-04-21 13:30:43 +09001902 } catch (RemoteException e) {
1903 throw new RuntimeException(e);
1904 }
1905 }
1906
1907 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001908 public void addVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001909 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001910
1911 try {
1912 mNetdService.networkAddUidRanges(netId, ranges);
1913 } catch (RemoteException | ServiceSpecificException e) {
1914 throw new IllegalStateException(e);
Chad Brubaker3277620a2013-06-12 13:37:30 -07001915 }
1916 }
1917
1918 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001919 public void removeVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001920 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001921 try {
1922 mNetdService.networkRemoveUidRanges(netId, ranges);
1923 } catch (RemoteException | ServiceSpecificException e) {
1924 throw new IllegalStateException(e);
Chad Brubakercca54c42013-06-27 17:41:38 -07001925 }
1926 }
1927
1928 @Override
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001929 public void setFirewallEnabled(boolean enabled) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001930 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001931 try {
Amith Yamasani15e472352015-04-24 19:06:07 -07001932 mConnector.execute("firewall", "enable", enabled ? "whitelist" : "blacklist");
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001933 mFirewallEnabled = enabled;
1934 } catch (NativeDaemonConnectorException e) {
1935 throw e.rethrowAsParcelableException();
1936 }
1937 }
1938
1939 @Override
1940 public boolean isFirewallEnabled() {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001941 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001942 return mFirewallEnabled;
1943 }
1944
1945 @Override
Jeff Sharkey2c092982012-08-24 11:44:40 -07001946 public void setFirewallInterfaceRule(String iface, boolean allow) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001947 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001948 Preconditions.checkState(mFirewallEnabled);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07001949 final String rule = allow ? "allow" : "deny";
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001950 try {
1951 mConnector.execute("firewall", "set_interface_rule", iface, rule);
1952 } catch (NativeDaemonConnectorException e) {
1953 throw e.rethrowAsParcelableException();
1954 }
1955 }
1956
Lorenzo Colitti3fef7232016-04-29 18:00:03 +09001957 private void closeSocketsForFirewallChainLocked(int chain, String chainName) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001958 // UID ranges to close sockets on.
1959 UidRange[] ranges;
1960 // UID ranges whose sockets we won't touch.
1961 int[] exemptUids;
1962
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001963 int numUids = 0;
1964
1965 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
1966 // Close all sockets on all non-system UIDs...
1967 ranges = new UidRange[] {
1968 // TODO: is there a better way of finding all existing users? If so, we could
1969 // specify their ranges here.
1970 new UidRange(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE),
1971 };
1972 // ... except for the UIDs that have allow rules.
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001973 synchronized (mRulesLock) {
1974 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1975 exemptUids = new int[rules.size()];
1976 for (int i = 0; i < exemptUids.length; i++) {
1977 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
1978 exemptUids[numUids] = rules.keyAt(i);
1979 numUids++;
1980 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001981 }
1982 }
1983 // Normally, whitelist chains only contain deny rules, so numUids == exemptUids.length.
1984 // But the code does not guarantee this in any way, and at least in one case - if we add
1985 // a UID rule to the firewall, and then disable the firewall - the chains can contain
1986 // the wrong type of rule. In this case, don't close connections that we shouldn't.
1987 //
1988 // TODO: tighten up this code by ensuring we never set the wrong type of rule, and
1989 // fix setFirewallEnabled to grab mQuotaLock and clear rules.
1990 if (numUids != exemptUids.length) {
1991 exemptUids = Arrays.copyOf(exemptUids, numUids);
1992 }
1993 } else {
1994 // Close sockets for every UID that has a deny rule...
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001995 synchronized (mRulesLock) {
1996 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1997 ranges = new UidRange[rules.size()];
1998 for (int i = 0; i < ranges.length; i++) {
1999 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_DENY) {
2000 int uid = rules.keyAt(i);
2001 ranges[numUids] = new UidRange(uid, uid);
2002 numUids++;
2003 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002004 }
2005 }
2006 // As above; usually numUids == ranges.length, but not always.
2007 if (numUids != ranges.length) {
2008 ranges = Arrays.copyOf(ranges, numUids);
2009 }
2010 // ... with no exceptions.
2011 exemptUids = new int[0];
2012 }
2013
2014 try {
2015 mNetdService.socketDestroy(ranges, exemptUids);
2016 } catch(RemoteException | ServiceSpecificException e) {
2017 Slog.e(TAG, "Error closing sockets after enabling chain " + chainName + ": " + e);
2018 }
2019 }
2020
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002021 @Override
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002022 public void setFirewallChainEnabled(int chain, boolean enable) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07002023 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002024 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002025 synchronized (mRulesLock) {
2026 if (getFirewallChainState(chain) == enable) {
2027 // All is the same, nothing to do. This relies on the fact that netd has child
2028 // chains default detached.
2029 return;
2030 }
2031 setFirewallChainState(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002032 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002033
2034 final String operation = enable ? "enable_chain" : "disable_chain";
Lorenzo Colitti3fef7232016-04-29 18:00:03 +09002035 final String chainName;
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002036 switch(chain) {
2037 case FIREWALL_CHAIN_STANDBY:
2038 chainName = FIREWALL_CHAIN_NAME_STANDBY;
2039 break;
2040 case FIREWALL_CHAIN_DOZABLE:
2041 chainName = FIREWALL_CHAIN_NAME_DOZABLE;
2042 break;
2043 case FIREWALL_CHAIN_POWERSAVE:
2044 chainName = FIREWALL_CHAIN_NAME_POWERSAVE;
2045 break;
2046 default:
2047 throw new IllegalArgumentException("Bad child chain: " + chain);
2048 }
2049
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002050 try {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002051 mConnector.execute("firewall", operation, chainName);
2052 } catch (NativeDaemonConnectorException e) {
2053 throw e.rethrowAsParcelableException();
2054 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002055
2056 // Close any sockets that were opened by the affected UIDs. This has to be done after
2057 // disabling network connectivity, in case they react to the socket close by reopening
2058 // the connection and race with the iptables commands that enable the firewall. All
2059 // whitelist and blacklist chains allow RSTs through.
2060 if (enable) {
2061 if (DBG) Slog.d(TAG, "Closing sockets after enabling chain " + chainName);
Lorenzo Colitti3fef7232016-04-29 18:00:03 +09002062 closeSocketsForFirewallChainLocked(chain, chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002063 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002064 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002065 }
2066
2067 private int getFirewallType(int chain) {
2068 switch (chain) {
2069 case FIREWALL_CHAIN_STANDBY:
2070 return FIREWALL_TYPE_BLACKLIST;
2071 case FIREWALL_CHAIN_DOZABLE:
2072 return FIREWALL_TYPE_WHITELIST;
Felipe Leme011b98f2016-02-10 17:28:31 -08002073 case FIREWALL_CHAIN_POWERSAVE:
2074 return FIREWALL_TYPE_WHITELIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002075 default:
2076 return isFirewallEnabled() ? FIREWALL_TYPE_WHITELIST : FIREWALL_TYPE_BLACKLIST;
2077 }
2078 }
2079
2080 @Override
2081 public void setFirewallUidRules(int chain, int[] uids, int[] rules) {
2082 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002083 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002084 synchronized (mRulesLock) {
2085 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
2086 SparseIntArray newRules = new SparseIntArray();
2087 // apply new set of rules
2088 for (int index = uids.length - 1; index >= 0; --index) {
2089 int uid = uids[index];
2090 int rule = rules[index];
2091 updateFirewallUidRuleLocked(chain, uid, rule);
2092 newRules.put(uid, rule);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002093 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002094 // collect the rules to remove.
2095 SparseIntArray rulesToRemove = new SparseIntArray();
2096 for (int index = uidFirewallRules.size() - 1; index >= 0; --index) {
2097 int uid = uidFirewallRules.keyAt(index);
2098 if (newRules.indexOfKey(uid) < 0) {
2099 rulesToRemove.put(uid, FIREWALL_RULE_DEFAULT);
2100 }
2101 }
2102 // remove dead rules
2103 for (int index = rulesToRemove.size() - 1; index >= 0; --index) {
2104 int uid = rulesToRemove.keyAt(index);
2105 updateFirewallUidRuleLocked(chain, uid, FIREWALL_RULE_DEFAULT);
2106 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002107 }
2108 try {
2109 switch (chain) {
2110 case FIREWALL_CHAIN_DOZABLE:
2111 mNetdService.firewallReplaceUidChain("fw_dozable", true, uids);
2112 break;
2113 case FIREWALL_CHAIN_STANDBY:
2114 mNetdService.firewallReplaceUidChain("fw_standby", false, uids);
2115 break;
2116 case FIREWALL_CHAIN_POWERSAVE:
2117 mNetdService.firewallReplaceUidChain("fw_powersave", true, uids);
2118 break;
2119 case FIREWALL_CHAIN_NONE:
2120 default:
2121 Slog.d(TAG, "setFirewallUidRules() called on invalid chain: " + chain);
2122 }
2123 } catch (RemoteException e) {
2124 Slog.w(TAG, "Error flushing firewall chain " + chain, e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002125 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002126 }
2127 }
2128
2129 @Override
2130 public void setFirewallUidRule(int chain, int uid, int rule) {
2131 enforceSystemUid();
Felipe Lemea701cad2016-05-12 09:58:14 -07002132 synchronized (mQuotaLock) {
2133 setFirewallUidRuleLocked(chain, uid, rule);
2134 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002135 }
2136
Felipe Lemea701cad2016-05-12 09:58:14 -07002137 private void setFirewallUidRuleLocked(int chain, int uid, int rule) {
2138 if (updateFirewallUidRuleLocked(chain, uid, rule)) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002139 try {
Felipe Lemea701cad2016-05-12 09:58:14 -07002140 mConnector.execute("firewall", "set_uid_rule", getFirewallChainName(chain), uid,
2141 getFirewallRuleName(chain, rule));
Amith Yamasani15e472352015-04-24 19:06:07 -07002142 } catch (NativeDaemonConnectorException e) {
2143 throw e.rethrowAsParcelableException();
2144 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002145 }
2146 }
2147
Felipe Lemea701cad2016-05-12 09:58:14 -07002148 // TODO: now that netd supports batching, NMS should not keep these data structures anymore...
2149 private boolean updateFirewallUidRuleLocked(int chain, int uid, int rule) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002150 synchronized (mRulesLock) {
2151 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Felipe Lemea701cad2016-05-12 09:58:14 -07002152
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002153 final int oldUidFirewallRule = uidFirewallRules.get(uid, FIREWALL_RULE_DEFAULT);
2154 if (DBG) {
2155 Slog.d(TAG, "oldRule = " + oldUidFirewallRule
2156 + ", newRule=" + rule + " for uid=" + uid + " on chain " + chain);
2157 }
2158 if (oldUidFirewallRule == rule) {
2159 if (DBG) Slog.d(TAG, "!!!!! Skipping change");
2160 // TODO: eventually consider throwing
2161 return false;
2162 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002163
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002164 String ruleName = getFirewallRuleName(chain, rule);
2165 String oldRuleName = getFirewallRuleName(chain, oldUidFirewallRule);
Felipe Lemea701cad2016-05-12 09:58:14 -07002166
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002167 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
2168 uidFirewallRules.delete(uid);
2169 } else {
2170 uidFirewallRules.put(uid, rule);
2171 }
2172 return !ruleName.equals(oldRuleName);
Felipe Lemea701cad2016-05-12 09:58:14 -07002173 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002174 }
2175
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002176 private @NonNull String getFirewallRuleName(int chain, int rule) {
2177 String ruleName;
2178 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
2179 if (rule == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
2180 ruleName = "allow";
2181 } else {
2182 ruleName = "deny";
2183 }
2184 } else { // Blacklist mode
2185 if (rule == NetworkPolicyManager.FIREWALL_RULE_DENY) {
2186 ruleName = "deny";
2187 } else {
2188 ruleName = "allow";
2189 }
2190 }
2191 return ruleName;
2192 }
2193
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002194 private @NonNull SparseIntArray getUidFirewallRulesLR(int chain) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002195 switch (chain) {
2196 case FIREWALL_CHAIN_STANDBY:
2197 return mUidFirewallStandbyRules;
2198 case FIREWALL_CHAIN_DOZABLE:
2199 return mUidFirewallDozableRules;
Felipe Leme011b98f2016-02-10 17:28:31 -08002200 case FIREWALL_CHAIN_POWERSAVE:
2201 return mUidFirewallPowerSaveRules;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002202 case FIREWALL_CHAIN_NONE:
2203 return mUidFirewallRules;
2204 default:
2205 throw new IllegalArgumentException("Unknown chain:" + chain);
2206 }
2207 }
2208
2209 public @NonNull String getFirewallChainName(int chain) {
2210 switch (chain) {
2211 case FIREWALL_CHAIN_STANDBY:
2212 return FIREWALL_CHAIN_NAME_STANDBY;
2213 case FIREWALL_CHAIN_DOZABLE:
2214 return FIREWALL_CHAIN_NAME_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -08002215 case FIREWALL_CHAIN_POWERSAVE:
2216 return FIREWALL_CHAIN_NAME_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002217 case FIREWALL_CHAIN_NONE:
2218 return FIREWALL_CHAIN_NAME_NONE;
2219 default:
2220 throw new IllegalArgumentException("Unknown chain:" + chain);
2221 }
2222 }
2223
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07002224 private static void enforceSystemUid() {
2225 final int uid = Binder.getCallingUid();
2226 if (uid != Process.SYSTEM_UID) {
2227 throw new SecurityException("Only available to AID_SYSTEM");
2228 }
2229 }
2230
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002231 @Override
Lorenzo Colitti79751842013-02-28 16:16:03 +09002232 public void startClatd(String interfaceName) throws IllegalStateException {
2233 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2234
2235 try {
Luke Huang69369f32018-08-02 15:51:41 +08002236 mNetdService.clatdStart(interfaceName);
2237 } catch (RemoteException | ServiceSpecificException e) {
2238 throw new IllegalStateException(e);
Lorenzo Colitti79751842013-02-28 16:16:03 +09002239 }
2240 }
2241
2242 @Override
Lorenzo Colitti95439462014-10-09 13:44:48 +09002243 public void stopClatd(String interfaceName) throws IllegalStateException {
Lorenzo Colitti79751842013-02-28 16:16:03 +09002244 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2245
2246 try {
Luke Huang69369f32018-08-02 15:51:41 +08002247 mNetdService.clatdStop(interfaceName);
2248 } catch (RemoteException | ServiceSpecificException e) {
2249 throw new IllegalStateException(e);
Lorenzo Colitti79751842013-02-28 16:16:03 +09002250 }
2251 }
2252
2253 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002254 public void registerNetworkActivityListener(INetworkActivityListener listener) {
2255 mNetworkActivityListeners.register(listener);
2256 }
2257
2258 @Override
2259 public void unregisterNetworkActivityListener(INetworkActivityListener listener) {
2260 mNetworkActivityListeners.unregister(listener);
2261 }
2262
2263 @Override
2264 public boolean isNetworkActive() {
2265 synchronized (mNetworkActivityListeners) {
2266 return mNetworkActive || mActiveIdleTimers.isEmpty();
2267 }
2268 }
2269
2270 private void reportNetworkActive() {
2271 final int length = mNetworkActivityListeners.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002272 try {
2273 for (int i = 0; i < length; i++) {
2274 try {
2275 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
Felipe Leme03e689d2016-03-02 16:17:38 -08002276 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002277 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002278 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002279 } finally {
2280 mNetworkActivityListeners.finishBroadcast();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002281 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002282 }
2283
Mattias Falk8b47b362011-08-23 14:15:13 +02002284 /** {@inheritDoc} */
Jeff Sharkey7b4596f2013-02-25 10:55:29 -08002285 @Override
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002286 public void monitor() {
2287 if (mConnector != null) {
2288 mConnector.monitor();
2289 }
2290 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002291
2292 @Override
2293 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002294 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002295
Robert Greenwalt470fd722012-01-18 12:51:15 -08002296 pw.println("NetworkManagementService NativeDaemonConnector Log:");
2297 mConnector.dump(fd, pw, args);
2298 pw.println();
2299
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07002300 pw.print("mMobileActivityFromRadio="); pw.print(mMobileActivityFromRadio);
2301 pw.print(" mLastPowerStateFromRadio="); pw.println(mLastPowerStateFromRadio);
2302 pw.print("mNetworkActive="); pw.println(mNetworkActive);
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002303
2304 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07002305 pw.print("Active quota ifaces: "); pw.println(mActiveQuotas.toString());
2306 pw.print("Active alert ifaces: "); pw.println(mActiveAlerts.toString());
Felipe Leme65be3022016-03-22 14:53:13 -07002307 pw.print("Data saver mode: "); pw.println(mDataSaverMode);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002308 synchronized (mRulesLock) {
2309 dumpUidRuleOnQuotaLocked(pw, "blacklist", mUidRejectOnMetered);
2310 dumpUidRuleOnQuotaLocked(pw, "whitelist", mUidAllowOnMetered);
2311 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002312 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002313
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002314 synchronized (mRulesLock) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002315 dumpUidFirewallRule(pw, "", mUidFirewallRules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002316
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002317 pw.print("UID firewall standby chain enabled: "); pw.println(
2318 getFirewallChainState(FIREWALL_CHAIN_STANDBY));
Felipe Leme011b98f2016-02-10 17:28:31 -08002319 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_STANDBY, mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002320
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002321 pw.print("UID firewall dozable chain enabled: "); pw.println(
2322 getFirewallChainState(FIREWALL_CHAIN_DOZABLE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002323 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_DOZABLE, mUidFirewallDozableRules);
Felipe Leme011b98f2016-02-10 17:28:31 -08002324
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002325 pw.println("UID firewall powersave chain enabled: " +
2326 getFirewallChainState(FIREWALL_CHAIN_POWERSAVE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002327 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_POWERSAVE, mUidFirewallPowerSaveRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002328 }
2329
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002330 synchronized (mIdleTimerLock) {
2331 pw.println("Idle timers:");
2332 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
2333 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
2334 IdleTimerParams params = ent.getValue();
2335 pw.print(" timeout="); pw.print(params.timeout);
2336 pw.print(" type="); pw.print(params.type);
2337 pw.print(" networkCount="); pw.println(params.networkCount);
2338 }
2339 }
2340
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002341 pw.print("Firewall enabled: "); pw.println(mFirewallEnabled);
Felipe Leme65be3022016-03-22 14:53:13 -07002342 pw.print("Netd service status: " );
2343 if (mNetdService == null) {
2344 pw.println("disconnected");
2345 } else {
2346 try {
2347 final boolean alive = mNetdService.isAlive();
2348 pw.println(alive ? "alive": "dead");
2349 } catch (RemoteException e) {
2350 pw.println("unreachable");
2351 }
2352 }
2353 }
2354
2355 private void dumpUidRuleOnQuotaLocked(PrintWriter pw, String name, SparseBooleanArray list) {
2356 pw.print("UID bandwith control ");
2357 pw.print(name);
2358 pw.print(" rule: [");
2359 final int size = list.size();
2360 for (int i = 0; i < size; i++) {
2361 pw.print(list.keyAt(i));
2362 if (i < size - 1) pw.print(",");
2363 }
2364 pw.println("]");
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002365 }
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002366
Felipe Leme011b98f2016-02-10 17:28:31 -08002367 private void dumpUidFirewallRule(PrintWriter pw, String name, SparseIntArray rules) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002368 pw.print("UID firewall ");
Felipe Leme011b98f2016-02-10 17:28:31 -08002369 pw.print(name);
2370 pw.print(" rule: [");
2371 final int size = rules.size();
2372 for (int i = 0; i < size; i++) {
2373 pw.print(rules.keyAt(i));
2374 pw.print(":");
2375 pw.print(rules.valueAt(i));
2376 if (i < size - 1) pw.print(",");
2377 }
2378 pw.println("]");
2379 }
2380
Robert Greenwalt568891d2014-04-04 13:38:00 -07002381 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002382 public void createPhysicalNetwork(int netId, int permission) {
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002383 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2384
2385 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002386 mNetdService.networkCreatePhysical(netId, permission);
2387 } catch (RemoteException | ServiceSpecificException e) {
2388 throw new IllegalStateException(e);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002389 }
2390 }
2391
Robert Greenwalt568891d2014-04-04 13:38:00 -07002392 @Override
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07002393 public void createVirtualNetwork(int netId, boolean hasDNS, boolean secure) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002394 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2395
2396 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002397 mNetdService.networkCreateVpn(netId, hasDNS, secure);
2398 } catch (RemoteException | ServiceSpecificException e) {
2399 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002400 }
2401 }
2402
2403 @Override
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002404 public void removeNetwork(int netId) {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002405 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002406
2407 try {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002408 mNetdService.networkDestroy(netId);
2409 } catch (ServiceSpecificException e) {
2410 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2411 throw e;
2412 } catch (RemoteException e) {
2413 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2414 throw e.rethrowAsRuntimeException();
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002415 }
2416 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002417
2418 @Override
Paul Jensen992f2522014-04-28 10:33:11 -04002419 public void addInterfaceToNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002420 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, netId, iface);
Paul Jensen992f2522014-04-28 10:33:11 -04002421 }
2422
2423 @Override
2424 public void removeInterfaceFromNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002425 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, netId, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002426 }
Paul Jensen992f2522014-04-28 10:33:11 -04002427
Luke Huang8a462ec2018-08-24 20:33:16 +08002428 private void modifyInterfaceInNetwork(boolean add, int netId, String iface) {
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002429 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Paul Jensen992f2522014-04-28 10:33:11 -04002430 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002431 if (add) {
2432 mNetdService.networkAddInterface(netId, iface);
2433 } else {
2434 mNetdService.networkRemoveInterface(netId, iface);
2435 }
2436 } catch (RemoteException | ServiceSpecificException e) {
2437 throw new IllegalStateException(e);
Paul Jensen992f2522014-04-28 10:33:11 -04002438 }
2439 }
2440
2441 @Override
Robert Greenwalt913c8952014-04-07 17:36:35 -07002442 public void addLegacyRouteForNetId(int netId, RouteInfo routeInfo, int uid) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002443 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2444
Sreeram Ramachandrancc91c7b2014-06-03 18:41:43 -07002445 final LinkAddress la = routeInfo.getDestinationLinkAddress();
Luke Huang8a462ec2018-08-24 20:33:16 +08002446 final String ifName = routeInfo.getInterface();
2447 final String dst = la.toString();
2448 final String nextHop;
Robert Greenwalt568891d2014-04-04 13:38:00 -07002449
Luke Huang8a462ec2018-08-24 20:33:16 +08002450 if (routeInfo.hasGateway()) {
2451 nextHop = routeInfo.getGateway().getHostAddress();
2452 } else {
2453 nextHop = "";
2454 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002455 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002456 mNetdService.networkAddLegacyRoute(netId, ifName, dst, nextHop, uid);
2457 } catch (RemoteException | ServiceSpecificException e) {
2458 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002459 }
2460 }
2461
2462 @Override
Sreeram Ramachandranf047f2a2014-04-15 16:04:26 -07002463 public void setDefaultNetId(int netId) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002464 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2465
2466 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002467 mNetdService.networkSetDefault(netId);
2468 } catch (RemoteException | ServiceSpecificException e) {
2469 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002470 }
2471 }
2472
2473 @Override
2474 public void clearDefaultNetId() {
2475 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2476
2477 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002478 mNetdService.networkClearDefault();
2479 } catch (RemoteException | ServiceSpecificException e) {
2480 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002481 }
2482 }
2483
2484 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002485 public void setNetworkPermission(int netId, int permission) {
Paul Jensen487ffe72015-07-24 15:57:11 -04002486 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2487
2488 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002489 mNetdService.networkSetPermissionForNetwork(netId, permission);
2490 } catch (RemoteException | ServiceSpecificException e) {
2491 throw new IllegalStateException(e);
Paul Jensen487ffe72015-07-24 15:57:11 -04002492 }
2493 }
2494
Luke Huang8a462ec2018-08-24 20:33:16 +08002495 private int parsePermission(String permission) {
2496 if (permission.equals("NETWORK")) {
2497 return INetd.PERMISSION_NETWORK;
2498 }
2499 if (permission.equals("SYSTEM")) {
2500 return INetd.PERMISSION_SYSTEM;
2501 }
2502 return INetd.PERMISSION_NONE;
2503 }
Paul Jensen487ffe72015-07-24 15:57:11 -04002504
2505 @Override
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002506 public void setPermission(String permission, int[] uids) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002507 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2508
Luke Huang8a462ec2018-08-24 20:33:16 +08002509 try {
2510 mNetdService.networkSetPermissionForUser(parsePermission(permission), uids);
2511 } catch (RemoteException | ServiceSpecificException e) {
2512 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002513 }
2514 }
2515
2516 @Override
2517 public void clearPermission(int[] uids) {
2518 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2519
Luke Huang8a462ec2018-08-24 20:33:16 +08002520 try {
2521 mNetdService.networkClearPermissionForUser(uids);
2522 } catch (RemoteException | ServiceSpecificException e) {
2523 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002524 }
2525 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002526
2527 @Override
2528 public void allowProtect(int uid) {
2529 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2530
2531 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002532 mNetdService.networkSetProtectAllow(uid);
2533 } catch (RemoteException | ServiceSpecificException e) {
2534 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002535 }
2536 }
2537
2538 @Override
2539 public void denyProtect(int uid) {
2540 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2541
2542 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002543 mNetdService.networkSetProtectDeny(uid);
2544 } catch (RemoteException | ServiceSpecificException e) {
2545 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002546 }
2547 }
2548
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002549 @Override
2550 public void addInterfaceToLocalNetwork(String iface, List<RouteInfo> routes) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002551 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, INetd.NETID_LOCAL, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002552
2553 for (RouteInfo route : routes) {
2554 if (!route.isDefaultRoute()) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002555 modifyRoute(MODIFY_OPERATION_ADD, INetd.NETID_LOCAL, route);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002556 }
2557 }
2558 }
2559
2560 @Override
2561 public void removeInterfaceFromLocalNetwork(String iface) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002562 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, INetd.NETID_LOCAL, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002563 }
Erik Kline6599ee82016-07-17 21:28:39 +09002564
2565 @Override
2566 public int removeRoutesFromLocalNetwork(List<RouteInfo> routes) {
2567 int failures = 0;
2568
2569 for (RouteInfo route : routes) {
2570 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002571 modifyRoute(MODIFY_OPERATION_REMOVE, INetd.NETID_LOCAL, route);
Erik Kline6599ee82016-07-17 21:28:39 +09002572 } catch (IllegalStateException e) {
2573 failures++;
2574 }
2575 }
2576
2577 return failures;
2578 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002579
Sudheer Shankab8f23162017-08-04 13:30:10 -07002580 @Override
2581 public boolean isNetworkRestricted(int uid) {
2582 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2583 return isNetworkRestrictedInternal(uid);
2584 }
2585
2586 private boolean isNetworkRestrictedInternal(int uid) {
2587 synchronized (mRulesLock) {
2588 if (getFirewallChainState(FIREWALL_CHAIN_STANDBY)
2589 && mUidFirewallStandbyRules.get(uid) == FIREWALL_RULE_DENY) {
2590 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of app standby mode");
2591 return true;
2592 }
2593 if (getFirewallChainState(FIREWALL_CHAIN_DOZABLE)
2594 && mUidFirewallDozableRules.get(uid) != FIREWALL_RULE_ALLOW) {
2595 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of device idle mode");
2596 return true;
2597 }
2598 if (getFirewallChainState(FIREWALL_CHAIN_POWERSAVE)
2599 && mUidFirewallPowerSaveRules.get(uid) != FIREWALL_RULE_ALLOW) {
2600 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of power saver mode");
2601 return true;
2602 }
2603 if (mUidRejectOnMetered.get(uid)) {
2604 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of no metered data"
2605 + " in the background");
2606 return true;
2607 }
2608 if (mDataSaverMode && !mUidAllowOnMetered.get(uid)) {
2609 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of data saver mode");
2610 return true;
2611 }
2612 return false;
2613 }
2614 }
2615
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002616 private void setFirewallChainState(int chain, boolean state) {
2617 synchronized (mRulesLock) {
2618 mFirewallChainStates.put(chain, state);
2619 }
2620 }
2621
2622 private boolean getFirewallChainState(int chain) {
2623 synchronized (mRulesLock) {
2624 return mFirewallChainStates.get(chain);
2625 }
2626 }
2627
2628 @VisibleForTesting
2629 class LocalService extends NetworkManagementInternal {
2630 @Override
2631 public boolean isNetworkRestrictedForUid(int uid) {
Sudheer Shankab8f23162017-08-04 13:30:10 -07002632 return isNetworkRestrictedInternal(uid);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002633 }
2634 }
2635
2636 @VisibleForTesting
2637 Injector getInjector() {
2638 return new Injector();
2639 }
2640
2641 @VisibleForTesting
2642 class Injector {
2643 void setDataSaverMode(boolean dataSaverMode) {
2644 mDataSaverMode = dataSaverMode;
2645 }
2646
2647 void setFirewallChainState(int chain, boolean state) {
2648 NetworkManagementService.this.setFirewallChainState(chain, state);
2649 }
2650
2651 void setFirewallRule(int chain, int uid, int rule) {
2652 synchronized (mRulesLock) {
2653 getUidFirewallRulesLR(chain).put(uid, rule);
2654 }
2655 }
2656
2657 void setUidOnMeteredNetworkList(boolean blacklist, int uid, boolean enable) {
2658 synchronized (mRulesLock) {
2659 if (blacklist) {
2660 mUidRejectOnMetered.put(uid, enable);
2661 } else {
2662 mUidAllowOnMetered.put(uid, enable);
2663 }
2664 }
2665 }
2666
2667 void reset() {
2668 synchronized (mRulesLock) {
2669 setDataSaverMode(false);
2670 final int[] chains = {
2671 FIREWALL_CHAIN_DOZABLE,
2672 FIREWALL_CHAIN_STANDBY,
2673 FIREWALL_CHAIN_POWERSAVE
2674 };
2675 for (int chain : chains) {
2676 setFirewallChainState(chain, false);
2677 getUidFirewallRulesLR(chain).clear();
2678 }
2679 mUidAllowOnMetered.clear();
2680 mUidRejectOnMetered.clear();
2681 }
2682 }
2683 }
San Mehat873f2142010-01-14 10:25:07 -08002684}