blob: 600a6ae0babdbe4c2c463a36b0d992e9b446ad9a [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;
Sehee Parka9139bc2017-12-22 13:54:05 +090020import static android.Manifest.permission.NETWORK_SETTINGS;
Lorenzo Colitti07f13042017-07-10 19:06:57 +090021import static android.Manifest.permission.NETWORK_STACK;
Jeff Sharkeyaf75c332011-11-18 12:41:12 -080022import static android.Manifest.permission.SHUTDOWN;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070023import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
24import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080025import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070026import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_STANDBY;
27import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NONE;
Felipe Leme011b98f2016-02-10 17:28:31 -080028import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070029import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
Sudheer Shanka62f5c172017-03-17 16:25:55 -070030import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070031import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Sudheer Shanka62f5c172017-03-17 16:25:55 -070032import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070033import static android.net.NetworkPolicyManager.FIREWALL_TYPE_BLACKLIST;
34import static android.net.NetworkPolicyManager.FIREWALL_TYPE_WHITELIST;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -070035import static android.net.NetworkStats.SET_DEFAULT;
Lorenzo Colittif1912ca2017-08-17 19:23:08 +090036import static android.net.NetworkStats.STATS_PER_UID;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080037import static android.net.NetworkStats.TAG_ALL;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070038import static android.net.NetworkStats.TAG_NONE;
39import static android.net.NetworkStats.UID_ALL;
Jeff Sharkeyae2c1812011-10-04 13:11:40 -070040import static android.net.TrafficStats.UID_TETHERING;
Lorenzo Colitti9307ca22019-01-12 01:54:23 +090041
Lorenzo Colitti79751842013-02-28 16:16:03 +090042import static com.android.server.NetworkManagementService.NetdResponseCode.ClatdStatusResult;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -080043import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceGetCfgResult;
44import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceListResult;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -080045import static com.android.server.NetworkManagementService.NetdResponseCode.IpFwdStatusResult;
46import static com.android.server.NetworkManagementService.NetdResponseCode.TetherDnsFwdTgtListResult;
47import static com.android.server.NetworkManagementService.NetdResponseCode.TetherInterfaceListResult;
48import static com.android.server.NetworkManagementService.NetdResponseCode.TetherStatusResult;
Jeff Sharkeye4984be2013-09-10 21:03:27 -070049import static com.android.server.NetworkManagementService.NetdResponseCode.TetheringStatsListResult;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -080050import static com.android.server.NetworkManagementService.NetdResponseCode.TtyListResult;
Jeff Sharkeya63ba592011-07-19 23:47:12 -070051import static com.android.server.NetworkManagementSocketTagger.PROP_QTAGUID_ENABLED;
Erik Klineb2cfdfb2017-01-18 20:54:14 +090052
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070053import android.annotation.NonNull;
Sudheer Shankadc589ac2016-11-10 15:30:17 -080054import android.app.ActivityManager;
San Mehat873f2142010-01-14 10:25:07 -080055import android.content.Context;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080056import android.net.ConnectivityManager;
Lorenzo Colitti58967ba2016-02-02 17:21:21 +090057import android.net.INetd;
San Mehat4d02d002010-01-22 16:07:46 -080058import android.net.INetworkManagementEventObserver;
Lorenzo Colitti07f13042017-07-10 19:06:57 +090059import android.net.ITetheringStatsProvider;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070060import android.net.InterfaceConfiguration;
Luke Huang14f75442018-08-15 19:22:54 +080061import android.net.InterfaceConfigurationParcel;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +090062import android.net.IpPrefix;
Robert Greenwalted126402011-01-28 15:34:55 -080063import android.net.LinkAddress;
Lorenzo Colittib57edc52014-08-22 17:10:50 -070064import android.net.Network;
Amith Yamasani15e472352015-04-24 19:06:07 -070065import android.net.NetworkPolicyManager;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070066import android.net.NetworkStats;
Robert Greenwalted126402011-01-28 15:34:55 -080067import android.net.NetworkUtils;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070068import android.net.RouteInfo;
Lorenzo Colitti9307ca22019-01-12 01:54:23 +090069import android.net.TetherStatsParcel;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040070import android.net.UidRange;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +090071import android.net.util.NetdService;
Dianne Hackborn91268cf2013-06-13 19:06:50 -070072import android.os.BatteryStats;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070073import android.os.Binder;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -070074import android.os.Handler;
Lorenzo Colittia0868002017-07-11 02:29:28 +090075import android.os.IBinder;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080076import android.os.INetworkActivityListener;
San Mehat873f2142010-01-14 10:25:07 -080077import android.os.INetworkManagementService;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080078import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070079import android.os.Process;
Jeff Sharkey3df273e2011-12-15 15:47:12 -080080import android.os.RemoteCallbackList;
81import android.os.RemoteException;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070082import android.os.ServiceManager;
Lorenzo Colitti4cb42402016-04-24 12:52:00 +090083import android.os.ServiceSpecificException;
Jeff Sharkey605eb792014-11-04 13:34:06 -080084import android.os.StrictMode;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070085import android.os.SystemClock;
Marco Nelissen62dbb222010-02-18 10:56:30 -080086import android.os.SystemProperties;
Felipe Leme29e72ea2016-09-08 13:26:55 -070087import android.os.Trace;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070088import android.telephony.DataConnectionRealTimeInfo;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080089import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080090import android.util.Slog;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070091import android.util.SparseBooleanArray;
Jeff Sharkey605eb792014-11-04 13:34:06 -080092import android.util.SparseIntArray;
San Mehat873f2142010-01-14 10:25:07 -080093
Jeff Sharkey605eb792014-11-04 13:34:06 -080094import com.android.internal.annotations.GuardedBy;
Sudheer Shanka62f5c172017-03-17 16:25:55 -070095import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070096import com.android.internal.app.IBatteryStats;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070097import com.android.internal.net.NetworkStatsFactory;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060098import com.android.internal.util.DumpUtils;
Jeff Sharkey605eb792014-11-04 13:34:06 -080099import com.android.internal.util.HexDump;
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700100import com.android.internal.util.Preconditions;
Lorenzo Colitti9307ca22019-01-12 01:54:23 +0900101
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700102import com.google.android.collect.Maps;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700103
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700104import java.io.BufferedReader;
105import java.io.DataInputStream;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700106import java.io.FileDescriptor;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700107import java.io.FileInputStream;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700108import java.io.IOException;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700109import java.io.InputStreamReader;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700110import java.io.PrintWriter;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700111import java.net.InetAddress;
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700112import java.net.InterfaceAddress;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700113import java.util.ArrayList;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400114import java.util.Arrays;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700115import java.util.HashMap;
jiaguo1da35f72014-01-09 16:39:59 +0800116import java.util.List;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700117import java.util.Map;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700118import java.util.concurrent.CountDownLatch;
San Mehat873f2142010-01-14 10:25:07 -0800119
120/**
121 * @hide
122 */
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700123public class NetworkManagementService extends INetworkManagementService.Stub
124 implements Watchdog.Monitor {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900125
126 /**
127 * Helper class that encapsulates NetworkManagementService dependencies and makes them
128 * easier to mock in unit tests.
129 */
130 static class SystemServices {
131 public IBinder getService(String name) {
132 return ServiceManager.getService(name);
133 }
134 public void registerLocalService(NetworkManagementInternal nmi) {
135 LocalServices.addService(NetworkManagementInternal.class, nmi);
136 }
137 public INetd getNetd() {
138 return NetdService.get();
139 }
140 }
141
Amith Yamasani15e472352015-04-24 19:06:07 -0700142 private static final String TAG = "NetworkManagement";
143 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Kenny Root305bcbf2010-09-03 07:56:38 -0700144 private static final String NETD_TAG = "NetdConnector";
Lorenzo Colittia0868002017-07-11 02:29:28 +0900145 static final String NETD_SERVICE_NAME = "netd";
Kenny Root305bcbf2010-09-03 07:56:38 -0700146
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400147 private static final int MAX_UID_RANGES_PER_COMMAND = 10;
148
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700149 /**
150 * Name representing {@link #setGlobalAlert(long)} limit when delivered to
151 * {@link INetworkManagementEventObserver#limitReached(String, String)}.
152 */
153 public static final String LIMIT_GLOBAL_ALERT = "globalAlert";
154
Andrew Scull45f533c2017-05-19 15:37:20 +0100155 static class NetdResponseCode {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -0700156 /* Keep in sync with system/netd/server/ResponseCode.h */
San Mehat873f2142010-01-14 10:25:07 -0800157 public static final int InterfaceListResult = 110;
158 public static final int TetherInterfaceListResult = 111;
159 public static final int TetherDnsFwdTgtListResult = 112;
San Mehat72759df2010-01-19 13:50:37 -0800160 public static final int TtyListResult = 113;
Jeff Sharkeye4984be2013-09-10 21:03:27 -0700161 public static final int TetheringStatsListResult = 114;
San Mehat873f2142010-01-14 10:25:07 -0800162
163 public static final int TetherStatusResult = 210;
164 public static final int IpFwdStatusResult = 211;
San Mehated4fc8a2010-01-22 12:28:36 -0800165 public static final int InterfaceGetCfgResult = 213;
Robert Greenwalte3253922010-02-18 09:23:25 -0800166 public static final int SoftapStatusResult = 214;
San Mehat91cac642010-03-31 14:31:36 -0700167 public static final int InterfaceRxCounterResult = 216;
168 public static final int InterfaceTxCounterResult = 217;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700169 public static final int QuotaCounterResult = 220;
170 public static final int TetheringStatsResult = 221;
Selim Gurun84c00c62012-02-27 15:42:38 -0800171 public static final int DnsProxyQueryResult = 222;
Lorenzo Colitti79751842013-02-28 16:16:03 +0900172 public static final int ClatdStatusResult = 223;
Robert Greenwalte3253922010-02-18 09:23:25 -0800173
174 public static final int InterfaceChange = 600;
JP Abgrall12b933d2011-07-14 18:09:22 -0700175 public static final int BandwidthControl = 601;
Haoyu Bai6b7358d2012-07-17 16:36:50 -0700176 public static final int InterfaceClassActivity = 613;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900177 public static final int InterfaceAddressChange = 614;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900178 public static final int InterfaceDnsServerInfo = 615;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900179 public static final int RouteChange = 616;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800180 public static final int StrictCleartext = 617;
San Mehat873f2142010-01-14 10:25:07 -0800181 }
182
Rebecca Silbersteine2ec94f2016-03-24 13:29:00 -0700183 /**
184 * String indicating a softap command.
185 */
186 static final String SOFT_AP_COMMAND = "softap";
187
188 /**
189 * String passed back to netd connector indicating softap command success.
190 */
191 static final String SOFT_AP_COMMAND_SUCCESS = "Ok";
192
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700193 static final int DAEMON_MSG_MOBILE_CONN_REAL_TIME_INFO = 1;
194
Luke Huang8a462ec2018-08-24 20:33:16 +0800195 static final boolean MODIFY_OPERATION_ADD = true;
196 static final boolean MODIFY_OPERATION_REMOVE = false;
197
San Mehat873f2142010-01-14 10:25:07 -0800198 /**
199 * Binder context for this service
200 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700201 private final Context mContext;
San Mehat873f2142010-01-14 10:25:07 -0800202
203 /**
204 * connector object for communicating with netd
205 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700206 private final NativeDaemonConnector mConnector;
San Mehat873f2142010-01-14 10:25:07 -0800207
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700208 private final Handler mFgHandler;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700209 private final Handler mDaemonHandler;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700210
Lorenzo Colittia0868002017-07-11 02:29:28 +0900211 private final SystemServices mServices;
212
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900213 private INetd mNetdService;
214
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800215 private IBatteryStats mBatteryStats;
216
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700217 private final Thread mThread;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700218 private CountDownLatch mConnectedSignal = new CountDownLatch(1);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700219
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800220 private final RemoteCallbackList<INetworkManagementEventObserver> mObservers =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700221 new RemoteCallbackList<>();
San Mehat4d02d002010-01-22 16:07:46 -0800222
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700223 private final NetworkStatsFactory mStatsFactory = new NetworkStatsFactory();
224
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900225 @GuardedBy("mTetheringStatsProviders")
226 private final HashMap<ITetheringStatsProvider, String>
227 mTetheringStatsProviders = Maps.newHashMap();
228
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700229 /**
230 * If both locks need to be held, then they should be obtained in the order:
231 * first {@link #mQuotaLock} and then {@link #mRulesLock}.
232 */
Andrew Scull45f533c2017-05-19 15:37:20 +0100233 private final Object mQuotaLock = new Object();
Andrew Scull519291f2017-05-23 13:11:03 +0100234 private final Object mRulesLock = new Object();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800235
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700236 /** Set of interfaces with active quotas. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800237 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700238 private HashMap<String, Long> mActiveQuotas = Maps.newHashMap();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700239 /** Set of interfaces with active alerts. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800240 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700241 private HashMap<String, Long> mActiveAlerts = Maps.newHashMap();
Felipe Leme65be3022016-03-22 14:53:13 -0700242 /** Set of UIDs blacklisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700243 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700244 private SparseBooleanArray mUidRejectOnMetered = new SparseBooleanArray();
245 /** Set of UIDs whitelisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700246 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700247 private SparseBooleanArray mUidAllowOnMetered = new SparseBooleanArray();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800248 /** Set of UIDs with cleartext penalties. */
249 @GuardedBy("mQuotaLock")
250 private SparseIntArray mUidCleartextPolicy = new SparseIntArray();
Amith Yamasani15e472352015-04-24 19:06:07 -0700251 /** Set of UIDs that are to be blocked/allowed by firewall controller. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700252 @GuardedBy("mRulesLock")
Amith Yamasani15e472352015-04-24 19:06:07 -0700253 private SparseIntArray mUidFirewallRules = new SparseIntArray();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700254 /**
255 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
256 * to application idles.
257 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700258 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700259 private SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
260 /**
261 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
262 * to device idles.
263 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700264 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700265 private SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800266 /**
267 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
268 * to device on power-save mode.
269 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700270 @GuardedBy("mRulesLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800271 private SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700272 /** Set of states for the child firewall chains. True if the chain is active. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700273 @GuardedBy("mRulesLock")
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700274 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700275
Felipe Leme65be3022016-03-22 14:53:13 -0700276 @GuardedBy("mQuotaLock")
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700277 private volatile boolean mDataSaverMode;
Felipe Leme65be3022016-03-22 14:53:13 -0700278
Andrew Scull45f533c2017-05-19 15:37:20 +0100279 private final Object mIdleTimerLock = new Object();
Haoyu Bai04124232012-06-28 15:26:19 -0700280 /** Set of interfaces with active idle timers. */
281 private static class IdleTimerParams {
282 public final int timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800283 public final int type;
Haoyu Bai04124232012-06-28 15:26:19 -0700284 public int networkCount;
285
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800286 IdleTimerParams(int timeout, int type) {
Haoyu Bai04124232012-06-28 15:26:19 -0700287 this.timeout = timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800288 this.type = type;
Haoyu Bai04124232012-06-28 15:26:19 -0700289 this.networkCount = 1;
290 }
291 }
292 private HashMap<String, IdleTimerParams> mActiveIdleTimers = Maps.newHashMap();
293
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700294 private volatile boolean mFirewallEnabled;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800295 private volatile boolean mStrictEnabled;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700296
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700297 private boolean mMobileActivityFromRadio = false;
298 private int mLastPowerStateFromRadio = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Adam Lesinskie08af192015-03-25 16:42:59 -0700299 private int mLastPowerStateFromWifi = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700300
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800301 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700302 new RemoteCallbackList<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800303 private boolean mNetworkActive;
304
San Mehat873f2142010-01-14 10:25:07 -0800305 /**
306 * Constructs a new NetworkManagementService instance
307 *
308 * @param context Binder context for this service
309 */
Lorenzo Colittia0868002017-07-11 02:29:28 +0900310 private NetworkManagementService(
311 Context context, String socket, SystemServices services) {
San Mehat873f2142010-01-14 10:25:07 -0800312 mContext = context;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900313 mServices = services;
San Mehat4d02d002010-01-22 16:07:46 -0800314
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700315 // make sure this is on the same looper as our NativeDaemonConnector for sync purposes
316 mFgHandler = new Handler(FgThread.get().getLooper());
317
Dianne Hackborn4590e522014-03-24 13:36:46 -0700318 // Don't need this wake lock, since we now have a time stamp for when
319 // the network actually went inactive. (It might be nice to still do this,
320 // but I don't want to do it through the power manager because that pollutes the
321 // battery stats history with pointless noise.)
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700322 //PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
Dianne Hackborn4590e522014-03-24 13:36:46 -0700323 PowerManager.WakeLock wl = null; //pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NETD_TAG);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800324
San Mehat873f2142010-01-14 10:25:07 -0800325 mConnector = new NativeDaemonConnector(
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700326 new NetdCallbackReceiver(), socket, 10, NETD_TAG, 160, wl,
327 FgThread.get().getLooper());
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700328 mThread = new Thread(mConnector, NETD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700329
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700330 mDaemonHandler = new Handler(FgThread.get().getLooper());
Wink Saville67e07892014-06-18 16:43:14 -0700331
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700332 // Add ourself to the Watchdog monitors.
333 Watchdog.getInstance().addMonitor(this);
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700334
Lorenzo Colittia0868002017-07-11 02:29:28 +0900335 mServices.registerLocalService(new LocalService());
Lorenzo Colitti8228eb32017-07-19 06:17:33 +0900336
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900337 synchronized (mTetheringStatsProviders) {
338 mTetheringStatsProviders.put(new NetdTetheringStatsProvider(), "netd");
339 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700340 }
341
342 @VisibleForTesting
343 NetworkManagementService() {
344 mConnector = null;
345 mContext = null;
346 mDaemonHandler = null;
347 mFgHandler = null;
348 mThread = null;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900349 mServices = null;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700350 }
351
Lorenzo Colittia0868002017-07-11 02:29:28 +0900352 static NetworkManagementService create(Context context, String socket, SystemServices services)
Felipe Leme03e689d2016-03-02 16:17:38 -0800353 throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900354 final NetworkManagementService service =
355 new NetworkManagementService(context, socket, services);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700356 final CountDownLatch connectedSignal = service.mConnectedSignal;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700357 if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
358 service.mThread.start();
359 if (DBG) Slog.d(TAG, "Awaiting socket connection");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700360 connectedSignal.await();
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700361 if (DBG) Slog.d(TAG, "Connected");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900362 if (DBG) Slog.d(TAG, "Connecting native netd service");
bohu07cc3bb2016-05-03 15:58:01 -0700363 service.connectNativeNetdService();
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900364 if (DBG) Slog.d(TAG, "Connected");
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700365 return service;
San Mehat873f2142010-01-14 10:25:07 -0800366 }
367
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900368 public static NetworkManagementService create(Context context) throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900369 return create(context, NETD_SERVICE_NAME, new SystemServices());
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900370 }
371
Jeff Sharkey350083e2011-06-29 10:45:16 -0700372 public void systemReady() {
Felipe Leme03e689d2016-03-02 16:17:38 -0800373 if (DBG) {
374 final long start = System.currentTimeMillis();
375 prepareNativeDaemon();
376 final long delta = System.currentTimeMillis() - start;
377 Slog.d(TAG, "Prepared in " + delta + "ms");
378 return;
379 } else {
380 prepareNativeDaemon();
381 }
Jeff Sharkey350083e2011-06-29 10:45:16 -0700382 }
383
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800384 private IBatteryStats getBatteryStats() {
385 synchronized (this) {
386 if (mBatteryStats != null) {
387 return mBatteryStats;
388 }
Lorenzo Colittia0868002017-07-11 02:29:28 +0900389 mBatteryStats =
390 IBatteryStats.Stub.asInterface(mServices.getService(BatteryStats.SERVICE_NAME));
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800391 return mBatteryStats;
392 }
393 }
394
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800395 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800396 public void registerObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800397 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800398 mObservers.register(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800399 }
400
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800401 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800402 public void unregisterObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800403 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800404 mObservers.unregister(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800405 }
406
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900407 @FunctionalInterface
408 private interface NetworkManagementEventCallback {
409 public void sendCallback(INetworkManagementEventObserver o) throws RemoteException;
410 }
411
412 private void invokeForAllObservers(NetworkManagementEventCallback eventCallback) {
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800413 final int length = mObservers.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700414 try {
415 for (int i = 0; i < length; i++) {
416 try {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900417 eventCallback.sendCallback(mObservers.getBroadcastItem(i));
Felipe Leme03e689d2016-03-02 16:17:38 -0800418 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700419 }
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700420 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700421 } finally {
422 mObservers.finishBroadcast();
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700423 }
424 }
425
426 /**
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900427 * Notify our observers of an interface status change
428 */
429 private void notifyInterfaceStatusChanged(String iface, boolean up) {
430 invokeForAllObservers(o -> o.interfaceStatusChanged(iface, up));
431 }
432
433 /**
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700434 * Notify our observers of an interface link state change
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700435 * (typically, an Ethernet cable has been plugged-in or unplugged).
436 */
437 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900438 invokeForAllObservers(o -> o.interfaceLinkStateChanged(iface, up));
San Mehat4d02d002010-01-22 16:07:46 -0800439 }
440
441 /**
442 * Notify our observers of an interface addition.
443 */
444 private void notifyInterfaceAdded(String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900445 invokeForAllObservers(o -> o.interfaceAdded(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800446 }
447
448 /**
449 * Notify our observers of an interface removal.
450 */
451 private void notifyInterfaceRemoved(String iface) {
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700452 // netd already clears out quota and alerts for removed ifaces; update
453 // our sanity-checking state.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700454 mActiveAlerts.remove(iface);
455 mActiveQuotas.remove(iface);
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700456
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900457 invokeForAllObservers(o -> o.interfaceRemoved(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800458 }
459
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700460 /**
JP Abgrall12b933d2011-07-14 18:09:22 -0700461 * Notify our observers of a limit reached.
462 */
463 private void notifyLimitReached(String limitName, String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900464 invokeForAllObservers(o -> o.limitReached(limitName, iface));
JP Abgrall12b933d2011-07-14 18:09:22 -0700465 }
466
467 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700468 * Notify our observers of a change in the data activity state of the interface
469 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700470 private void notifyInterfaceClassActivity(int type, int powerState, long tsNanos,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700471 int uid, boolean fromRadio) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700472 final boolean isMobile = ConnectivityManager.isNetworkTypeMobile(type);
473 if (isMobile) {
474 if (!fromRadio) {
475 if (mMobileActivityFromRadio) {
476 // If this call is not coming from a report from the radio itself, but we
477 // have previously received reports from the radio, then we will take the
478 // power state to just be whatever the radio last reported.
479 powerState = mLastPowerStateFromRadio;
480 }
481 } else {
482 mMobileActivityFromRadio = true;
483 }
484 if (mLastPowerStateFromRadio != powerState) {
485 mLastPowerStateFromRadio = powerState;
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700486 try {
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700487 getBatteryStats().noteMobileRadioPowerState(powerState, tsNanos, uid);
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700488 } catch (RemoteException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700489 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700490 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700491 }
492
Adam Lesinskie08af192015-03-25 16:42:59 -0700493 if (ConnectivityManager.isNetworkTypeWifi(type)) {
494 if (mLastPowerStateFromWifi != powerState) {
495 mLastPowerStateFromWifi = powerState;
496 try {
Adam Lesinski5f056f62016-07-14 16:56:08 -0700497 getBatteryStats().noteWifiRadioPowerState(powerState, tsNanos, uid);
Adam Lesinskie08af192015-03-25 16:42:59 -0700498 } catch (RemoteException e) {
499 }
500 }
501 }
502
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700503 boolean isActive = powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
504 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
505
506 if (!isMobile || fromRadio || !mMobileActivityFromRadio) {
507 // Report the change in data activity. We don't do this if this is a change
508 // on the mobile network, that is not coming from the radio itself, and we
509 // have previously seen change reports from the radio. In that case only
510 // the radio is the authority for the current state.
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900511 final boolean active = isActive;
512 invokeForAllObservers(o -> o.interfaceClassDataActivityChanged(
513 Integer.toString(type), active, tsNanos));
Haoyu Baidb3c8672012-06-20 14:29:57 -0700514 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800515
516 boolean report = false;
517 synchronized (mIdleTimerLock) {
518 if (mActiveIdleTimers.isEmpty()) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700519 // If there are no idle timers, we are not monitoring activity, so we
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800520 // are always considered active.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700521 isActive = true;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800522 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700523 if (mNetworkActive != isActive) {
524 mNetworkActive = isActive;
525 report = isActive;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800526 }
527 }
528 if (report) {
529 reportNetworkActive();
530 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700531 }
532
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900533 @Override
534 public void registerTetheringStatsProvider(ITetheringStatsProvider provider, String name) {
535 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
536 Preconditions.checkNotNull(provider);
537 synchronized(mTetheringStatsProviders) {
538 mTetheringStatsProviders.put(provider, name);
539 }
540 }
541
542 @Override
543 public void unregisterTetheringStatsProvider(ITetheringStatsProvider provider) {
544 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
545 synchronized(mTetheringStatsProviders) {
546 mTetheringStatsProviders.remove(provider);
547 }
548 }
549
Lorenzo Colitti9f0baa92017-08-15 19:25:51 +0900550 @Override
551 public void tetherLimitReached(ITetheringStatsProvider provider) {
552 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
553 synchronized(mTetheringStatsProviders) {
554 if (!mTetheringStatsProviders.containsKey(provider)) {
555 return;
556 }
557 // No current code examines the interface parameter in a global alert. Just pass null.
558 notifyLimitReached(LIMIT_GLOBAL_ALERT, null);
559 }
560 }
561
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900562 // Sync the state of the given chain with the native daemon.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700563 private void syncFirewallChainLocked(int chain, String name) {
564 SparseIntArray rules;
565 synchronized (mRulesLock) {
566 final SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900567 // Make a copy of the current rules, and then clear them. This is because
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700568 // setFirewallUidRuleInternal only pushes down rules to the native daemon if they
569 // are different from the current rules stored in the mUidFirewall*Rules array for
570 // the specified chain. If we don't clear the rules, setFirewallUidRuleInternal
571 // will do nothing.
572 rules = uidFirewallRules.clone();
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900573 uidFirewallRules.clear();
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700574 }
575 if (rules.size() > 0) {
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900576 // Now push the rules. setFirewallUidRuleInternal will push each of these down to the
577 // native daemon, and also add them to the mUidFirewall*Rules array for the specified
578 // chain.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700579 if (DBG) Slog.d(TAG, "Pushing " + rules.size() + " active firewall "
580 + name + "UID rules");
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900581 for (int i = 0; i < rules.size(); i++) {
Felipe Lemea701cad2016-05-12 09:58:14 -0700582 setFirewallUidRuleLocked(chain, rules.keyAt(i), rules.valueAt(i));
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900583 }
584 }
585 }
586
bohu07cc3bb2016-05-03 15:58:01 -0700587 private void connectNativeNetdService() {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900588 mNetdService = mServices.getNetd();
bohu07cc3bb2016-05-03 15:58:01 -0700589 }
590
591 /**
592 * Prepare native daemon once connected, enabling modules and pushing any
593 * existing in-memory rules.
594 */
595 private void prepareNativeDaemon() {
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900596
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700597 // push any existing quota or UID rules
598 synchronized (mQuotaLock) {
Felipe Leme65be3022016-03-22 14:53:13 -0700599
Luke Huang56a03a02018-09-07 12:02:16 +0800600 // Netd unconditionally enable bandwidth control
601 SystemProperties.set(PROP_QTAGUID_ENABLED, "1");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900602
Luke Huang473eb872018-07-26 17:33:14 +0800603 mStrictEnabled = true;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900604
Felipe Leme65be3022016-03-22 14:53:13 -0700605 setDataSaverModeEnabled(mDataSaverMode);
606
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700607 int size = mActiveQuotas.size();
608 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800609 if (DBG) Slog.d(TAG, "Pushing " + size + " active quota rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700610 final HashMap<String, Long> activeQuotas = mActiveQuotas;
611 mActiveQuotas = Maps.newHashMap();
612 for (Map.Entry<String, Long> entry : activeQuotas.entrySet()) {
613 setInterfaceQuota(entry.getKey(), entry.getValue());
614 }
615 }
616
617 size = mActiveAlerts.size();
618 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800619 if (DBG) Slog.d(TAG, "Pushing " + size + " active alert rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700620 final HashMap<String, Long> activeAlerts = mActiveAlerts;
621 mActiveAlerts = Maps.newHashMap();
622 for (Map.Entry<String, Long> entry : activeAlerts.entrySet()) {
623 setInterfaceAlert(entry.getKey(), entry.getValue());
624 }
625 }
626
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700627 SparseBooleanArray uidRejectOnQuota = null;
628 SparseBooleanArray uidAcceptOnQuota = null;
629 synchronized (mRulesLock) {
630 size = mUidRejectOnMetered.size();
631 if (size > 0) {
632 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered blacklist rules");
633 uidRejectOnQuota = mUidRejectOnMetered;
634 mUidRejectOnMetered = new SparseBooleanArray();
635 }
636
637 size = mUidAllowOnMetered.size();
638 if (size > 0) {
639 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered whitelist rules");
640 uidAcceptOnQuota = mUidAllowOnMetered;
641 mUidAllowOnMetered = new SparseBooleanArray();
642 }
643 }
644 if (uidRejectOnQuota != null) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700645 for (int i = 0; i < uidRejectOnQuota.size(); i++) {
Felipe Leme65be3022016-03-22 14:53:13 -0700646 setUidMeteredNetworkBlacklist(uidRejectOnQuota.keyAt(i),
647 uidRejectOnQuota.valueAt(i));
648 }
649 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700650 if (uidAcceptOnQuota != null) {
Felipe Leme65be3022016-03-22 14:53:13 -0700651 for (int i = 0; i < uidAcceptOnQuota.size(); i++) {
652 setUidMeteredNetworkWhitelist(uidAcceptOnQuota.keyAt(i),
653 uidAcceptOnQuota.valueAt(i));
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700654 }
655 }
Jeff Sharkey605eb792014-11-04 13:34:06 -0800656
657 size = mUidCleartextPolicy.size();
658 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800659 if (DBG) Slog.d(TAG, "Pushing " + size + " active UID cleartext policies");
Jeff Sharkey605eb792014-11-04 13:34:06 -0800660 final SparseIntArray local = mUidCleartextPolicy;
661 mUidCleartextPolicy = new SparseIntArray();
662 for (int i = 0; i < local.size(); i++) {
663 setUidCleartextNetworkPolicy(local.keyAt(i), local.valueAt(i));
664 }
665 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700666
Robin Leec3736bc2017-03-10 16:19:54 +0000667 setFirewallEnabled(mFirewallEnabled);
Amith Yamasani15e472352015-04-24 19:06:07 -0700668
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700669 syncFirewallChainLocked(FIREWALL_CHAIN_NONE, "");
670 syncFirewallChainLocked(FIREWALL_CHAIN_STANDBY, "standby ");
671 syncFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, "dozable ");
672 syncFirewallChainLocked(FIREWALL_CHAIN_POWERSAVE, "powersave ");
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700673
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700674 final int[] chains =
675 {FIREWALL_CHAIN_STANDBY, FIREWALL_CHAIN_DOZABLE, FIREWALL_CHAIN_POWERSAVE};
676 for (int chain : chains) {
677 if (getFirewallChainState(chain)) {
678 setFirewallChainEnabled(chain, true);
679 }
Felipe Leme011b98f2016-02-10 17:28:31 -0800680 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700681 }
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900682
Luke Huang56a03a02018-09-07 12:02:16 +0800683
684 try {
685 getBatteryStats().noteNetworkStatsEnabled();
686 } catch (RemoteException e) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900687 }
688
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700689 }
San Mehat4d02d002010-01-22 16:07:46 -0800690
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900691 /**
692 * Notify our observers of a new or updated interface address.
693 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900694 private void notifyAddressUpdated(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900695 invokeForAllObservers(o -> o.addressUpdated(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900696 }
697
698 /**
699 * Notify our observers of a deleted interface address.
700 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900701 private void notifyAddressRemoved(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900702 invokeForAllObservers(o -> o.addressRemoved(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900703 }
704
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900705 /**
706 * Notify our observers of DNS server information received.
707 */
708 private void notifyInterfaceDnsServerInfo(String iface, long lifetime, String[] addresses) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900709 invokeForAllObservers(o -> o.interfaceDnsServerInfo(iface, lifetime, addresses));
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900710 }
711
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900712 /**
713 * Notify our observers of a route change.
714 */
715 private void notifyRouteChange(String action, RouteInfo route) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900716 if (action.equals("updated")) {
717 invokeForAllObservers(o -> o.routeUpdated(route));
718 } else {
719 invokeForAllObservers(o -> o.routeRemoved(route));
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900720 }
721 }
722
San Mehat873f2142010-01-14 10:25:07 -0800723 //
724 // Netd Callback handling
725 //
726
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700727 private class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
728 @Override
San Mehat873f2142010-01-14 10:25:07 -0800729 public void onDaemonConnected() {
Felipe Leme65be3022016-03-22 14:53:13 -0700730 Slog.i(TAG, "onDaemonConnected()");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700731 // event is dispatched from internal NDC thread, so we prepare the
732 // daemon back on main thread.
733 if (mConnectedSignal != null) {
bohu07cc3bb2016-05-03 15:58:01 -0700734 // The system is booting and we're connecting to netd for the first time.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700735 mConnectedSignal.countDown();
736 mConnectedSignal = null;
737 } else {
bohu07cc3bb2016-05-03 15:58:01 -0700738 // We're reconnecting to netd after the socket connection
739 // was interrupted (e.g., if it crashed).
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700740 mFgHandler.post(new Runnable() {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700741 @Override
742 public void run() {
bohu07cc3bb2016-05-03 15:58:01 -0700743 connectNativeNetdService();
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700744 prepareNativeDaemon();
745 }
746 });
747 }
San Mehat873f2142010-01-14 10:25:07 -0800748 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700749
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700750 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800751 public boolean onCheckHoldWakeLock(int code) {
752 return code == NetdResponseCode.InterfaceClassActivity;
753 }
754
755 @Override
San Mehat873f2142010-01-14 10:25:07 -0800756 public boolean onEvent(int code, String raw, String[] cooked) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900757 String errorMessage = String.format("Invalid event from daemon (%s)", raw);
JP Abgrall12b933d2011-07-14 18:09:22 -0700758 switch (code) {
759 case NetdResponseCode.InterfaceChange:
760 /*
761 * a network interface change occured
762 * Format: "NNN Iface added <name>"
763 * "NNN Iface removed <name>"
764 * "NNN Iface changed <name> <up/down>"
765 * "NNN Iface linkstatus <name> <up/down>"
766 */
767 if (cooked.length < 4 || !cooked[1].equals("Iface")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900768 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700769 }
770 if (cooked[2].equals("added")) {
771 notifyInterfaceAdded(cooked[3]);
772 return true;
773 } else if (cooked[2].equals("removed")) {
774 notifyInterfaceRemoved(cooked[3]);
775 return true;
776 } else if (cooked[2].equals("changed") && cooked.length == 5) {
777 notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
778 return true;
779 } else if (cooked[2].equals("linkstate") && cooked.length == 5) {
780 notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
781 return true;
782 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900783 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700784 // break;
785 case NetdResponseCode.BandwidthControl:
786 /*
787 * Bandwidth control needs some attention
788 * Format: "NNN limit alert <alertName> <ifaceName>"
789 */
790 if (cooked.length < 5 || !cooked[1].equals("limit")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900791 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700792 }
793 if (cooked[2].equals("alert")) {
794 notifyLimitReached(cooked[3], cooked[4]);
795 return true;
796 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900797 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700798 // break;
Haoyu Baidb3c8672012-06-20 14:29:57 -0700799 case NetdResponseCode.InterfaceClassActivity:
800 /*
801 * An network interface class state changed (active/idle)
802 * Format: "NNN IfaceClass <active/idle> <label>"
803 */
804 if (cooked.length < 4 || !cooked[1].equals("IfaceClass")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900805 throw new IllegalStateException(errorMessage);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700806 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700807 long timestampNanos = 0;
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700808 int processUid = -1;
809 if (cooked.length >= 5) {
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700810 try {
811 timestampNanos = Long.parseLong(cooked[4]);
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700812 if (cooked.length == 6) {
813 processUid = Integer.parseInt(cooked[5]);
814 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700815 } catch(NumberFormatException ne) {}
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700816 } else {
817 timestampNanos = SystemClock.elapsedRealtimeNanos();
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700818 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700819 boolean isActive = cooked[2].equals("active");
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700820 notifyInterfaceClassActivity(Integer.parseInt(cooked[3]),
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700821 isActive ? DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700822 : DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
823 timestampNanos, processUid, false);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700824 return true;
825 // break;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900826 case NetdResponseCode.InterfaceAddressChange:
827 /*
828 * A network address change occurred
829 * Format: "NNN Address updated <addr> <iface> <flags> <scope>"
830 * "NNN Address removed <addr> <iface> <flags> <scope>"
831 */
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900832 if (cooked.length < 7 || !cooked[1].equals("Address")) {
833 throw new IllegalStateException(errorMessage);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900834 }
835
Lorenzo Colitti64483942013-11-15 18:43:52 +0900836 String iface = cooked[4];
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900837 LinkAddress address;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900838 try {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900839 int flags = Integer.parseInt(cooked[5]);
840 int scope = Integer.parseInt(cooked[6]);
841 address = new LinkAddress(cooked[3], flags, scope);
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900842 } catch(NumberFormatException e) { // Non-numeric lifetime or scope.
843 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti64483942013-11-15 18:43:52 +0900844 } catch(IllegalArgumentException e) { // Malformed/invalid IP address.
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900845 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900846 }
847
848 if (cooked[2].equals("updated")) {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900849 notifyAddressUpdated(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900850 } else {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900851 notifyAddressRemoved(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900852 }
853 return true;
854 // break;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900855 case NetdResponseCode.InterfaceDnsServerInfo:
856 /*
857 * Information about available DNS servers has been received.
858 * Format: "NNN DnsInfo servers <interface> <lifetime> <servers>"
859 */
860 long lifetime; // Actually a 32-bit unsigned integer.
861
862 if (cooked.length == 6 &&
863 cooked[1].equals("DnsInfo") &&
864 cooked[2].equals("servers")) {
865 try {
866 lifetime = Long.parseLong(cooked[4]);
867 } catch (NumberFormatException e) {
868 throw new IllegalStateException(errorMessage);
869 }
870 String[] servers = cooked[5].split(",");
871 notifyInterfaceDnsServerInfo(cooked[3], lifetime, servers);
872 }
873 return true;
874 // break;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900875 case NetdResponseCode.RouteChange:
876 /*
877 * A route has been updated or removed.
878 * Format: "NNN Route <updated|removed> <dst> [via <gateway] [dev <iface>]"
879 */
880 if (!cooked[1].equals("Route") || cooked.length < 6) {
881 throw new IllegalStateException(errorMessage);
882 }
883
884 String via = null;
885 String dev = null;
886 boolean valid = true;
887 for (int i = 4; (i + 1) < cooked.length && valid; i += 2) {
888 if (cooked[i].equals("dev")) {
889 if (dev == null) {
890 dev = cooked[i+1];
891 } else {
892 valid = false; // Duplicate interface.
893 }
894 } else if (cooked[i].equals("via")) {
895 if (via == null) {
896 via = cooked[i+1];
897 } else {
898 valid = false; // Duplicate gateway.
899 }
900 } else {
901 valid = false; // Unknown syntax.
902 }
903 }
904 if (valid) {
905 try {
906 // InetAddress.parseNumericAddress(null) inexplicably returns ::1.
907 InetAddress gateway = null;
908 if (via != null) gateway = InetAddress.parseNumericAddress(via);
909 RouteInfo route = new RouteInfo(new IpPrefix(cooked[3]), gateway, dev);
910 notifyRouteChange(cooked[2], route);
911 return true;
912 } catch (IllegalArgumentException e) {}
913 }
914 throw new IllegalStateException(errorMessage);
915 // break;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800916 case NetdResponseCode.StrictCleartext:
917 final int uid = Integer.parseInt(cooked[1]);
918 final byte[] firstPacket = HexDump.hexStringToByteArray(cooked[2]);
919 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800920 ActivityManager.getService().notifyCleartextNetwork(uid, firstPacket);
Jeff Sharkey605eb792014-11-04 13:34:06 -0800921 } catch (RemoteException ignored) {
922 }
923 break;
JP Abgrall12b933d2011-07-14 18:09:22 -0700924 default: break;
Robert Greenwalte3253922010-02-18 09:23:25 -0800925 }
926 return false;
San Mehat873f2142010-01-14 10:25:07 -0800927 }
928 }
929
San Mehated4fc8a2010-01-22 12:28:36 -0800930
San Mehat873f2142010-01-14 10:25:07 -0800931 //
932 // INetworkManagementService members
933 //
Erik Kline4e37b702016-07-05 11:34:21 +0900934 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800935 public String[] listInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800936 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700937 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +0800938 return mNetdService.interfaceGetList();
Luke Huang14f75442018-08-15 19:22:54 +0800939 } catch (RemoteException | ServiceSpecificException e) {
940 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700941 }
San Mehated4fc8a2010-01-22 12:28:36 -0800942 }
943
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800944 @Override
945 public InterfaceConfiguration getInterfaceConfig(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800946 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang14f75442018-08-15 19:22:54 +0800947 final InterfaceConfigurationParcel result;
Kenny Roota80ce062010-06-01 13:23:53 -0700948 try {
Luke Huang14f75442018-08-15 19:22:54 +0800949 result = mNetdService.interfaceGetCfg(iface);
950 } catch (RemoteException | ServiceSpecificException e) {
951 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700952 }
San Mehated4fc8a2010-01-22 12:28:36 -0800953
San Mehated4fc8a2010-01-22 12:28:36 -0800954 try {
Luke Huang14f75442018-08-15 19:22:54 +0800955 final InterfaceConfiguration cfg = InterfaceConfiguration.fromParcel(result);
956 return cfg;
957 } catch (IllegalArgumentException iae) {
958 throw new IllegalStateException("Invalid InterfaceConfigurationParcel", iae);
San Mehated4fc8a2010-01-22 12:28:36 -0800959 }
San Mehated4fc8a2010-01-22 12:28:36 -0800960 }
961
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800962 @Override
963 public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800964 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800965 LinkAddress linkAddr = cfg.getLinkAddress();
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800966 if (linkAddr == null || linkAddr.getAddress() == null) {
967 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -0800968 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800969
Luke Huang14f75442018-08-15 19:22:54 +0800970 final InterfaceConfigurationParcel cfgParcel = cfg.toParcel(iface);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800971
Kenny Roota80ce062010-06-01 13:23:53 -0700972 try {
Luke Huang14f75442018-08-15 19:22:54 +0800973 mNetdService.interfaceSetCfg(cfgParcel);
974 } catch (RemoteException | ServiceSpecificException e) {
975 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700976 }
San Mehat873f2142010-01-14 10:25:07 -0800977 }
978
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800979 @Override
980 public void setInterfaceDown(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800981 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800982 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800983 ifcg.setInterfaceDown();
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800984 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -0700985 }
986
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800987 @Override
988 public void setInterfaceUp(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800989 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800990 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800991 ifcg.setInterfaceUp();
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800992 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -0700993 }
994
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800995 @Override
996 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800997 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sheriff73293612011-09-14 12:31:56 -0700998 try {
Luke Huang14f75442018-08-15 19:22:54 +0800999 mNetdService.interfaceSetIPv6PrivacyExtensions(iface, enable);
1000 } catch (RemoteException | ServiceSpecificException e) {
1001 throw new IllegalStateException(e);
Irfan Sheriff73293612011-09-14 12:31:56 -07001002 }
1003 }
1004
Irfan Sherifff5600612011-06-16 10:26:28 -07001005 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
1006 IPv6 addresses on interface down, but we need to do full clean up here */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001007 @Override
1008 public void clearInterfaceAddresses(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001009 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sherifff5600612011-06-16 10:26:28 -07001010 try {
Luke Huang14f75442018-08-15 19:22:54 +08001011 mNetdService.interfaceClearAddrs(iface);
1012 } catch (RemoteException | ServiceSpecificException e) {
1013 throw new IllegalStateException(e);
Irfan Sherifff5600612011-06-16 10:26:28 -07001014 }
1015 }
1016
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001017 @Override
1018 public void enableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001019 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001020 try {
Luke Huang14f75442018-08-15 19:22:54 +08001021 mNetdService.interfaceSetEnableIPv6(iface, true);
1022 } catch (RemoteException | ServiceSpecificException e) {
1023 throw new IllegalStateException(e);
repo sync7960d9f2011-09-29 12:40:02 -07001024 }
1025 }
1026
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001027 @Override
Joel Scherpelz2db10742017-06-07 15:38:38 +09001028 public void setIPv6AddrGenMode(String iface, int mode) throws ServiceSpecificException {
1029 try {
1030 mNetdService.setIPv6AddrGenMode(iface, mode);
1031 } catch (RemoteException e) {
1032 throw e.rethrowAsRuntimeException();
1033 }
1034 }
1035
1036 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001037 public void disableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001038 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001039 try {
Luke Huang14f75442018-08-15 19:22:54 +08001040 mNetdService.interfaceSetEnableIPv6(iface, false);
1041 } catch (RemoteException | ServiceSpecificException e) {
1042 throw new IllegalStateException(e);
repo sync7960d9f2011-09-29 12:40:02 -07001043 }
1044 }
1045
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001046 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001047 public void addRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001048 modifyRoute(MODIFY_OPERATION_ADD, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001049 }
1050
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001051 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001052 public void removeRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001053 modifyRoute(MODIFY_OPERATION_REMOVE, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001054 }
1055
Luke Huang8a462ec2018-08-24 20:33:16 +08001056 private void modifyRoute(boolean add, int netId, RouteInfo route) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001057 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001058
Luke Huang8a462ec2018-08-24 20:33:16 +08001059 final String ifName = route.getInterface();
1060 final String dst = route.getDestination().toString();
1061 final String nextHop;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001062
1063 switch (route.getType()) {
1064 case RouteInfo.RTN_UNICAST:
1065 if (route.hasGateway()) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001066 nextHop = route.getGateway().getHostAddress();
1067 } else {
1068 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001069 }
1070 break;
1071 case RouteInfo.RTN_UNREACHABLE:
Luke Huang8a462ec2018-08-24 20:33:16 +08001072 nextHop = INetd.NEXTHOP_UNREACHABLE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001073 break;
1074 case RouteInfo.RTN_THROW:
Luke Huang8a462ec2018-08-24 20:33:16 +08001075 nextHop = INetd.NEXTHOP_THROW;
1076 break;
1077 default:
1078 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001079 break;
Sreeram Ramachandran1fbcb272014-05-22 16:30:48 -07001080 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001081 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08001082 if (add) {
1083 mNetdService.networkAddRoute(netId, ifName, dst, nextHop);
1084 } else {
1085 mNetdService.networkRemoveRoute(netId, ifName, dst, nextHop);
1086 }
1087 } catch (RemoteException | ServiceSpecificException e) {
1088 throw new IllegalStateException(e);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001089 }
1090 }
1091
1092 private ArrayList<String> readRouteList(String filename) {
1093 FileInputStream fstream = null;
Christopher Wiley212b95f2016-08-02 11:38:57 -07001094 ArrayList<String> list = new ArrayList<>();
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001095
1096 try {
1097 fstream = new FileInputStream(filename);
1098 DataInputStream in = new DataInputStream(fstream);
1099 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1100 String s;
1101
1102 // throw away the title line
1103
1104 while (((s = br.readLine()) != null) && (s.length() != 0)) {
1105 list.add(s);
1106 }
1107 } catch (IOException ex) {
1108 // return current list, possibly empty
1109 } finally {
1110 if (fstream != null) {
1111 try {
1112 fstream.close();
1113 } catch (IOException ex) {}
1114 }
1115 }
1116
1117 return list;
1118 }
1119
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001120 @Override
sy.yun9d9b74a2013-09-02 05:24:09 +09001121 public void setMtu(String iface, int mtu) {
1122 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1123
sy.yun9d9b74a2013-09-02 05:24:09 +09001124 try {
Luke Huang14f75442018-08-15 19:22:54 +08001125 mNetdService.interfaceSetMtu(iface, mtu);
1126 } catch (RemoteException | ServiceSpecificException e) {
1127 throw new IllegalStateException(e);
sy.yun9d9b74a2013-09-02 05:24:09 +09001128 }
1129 }
1130
1131 @Override
San Mehat873f2142010-01-14 10:25:07 -08001132 public void shutdown() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001133 // TODO: remove from aidl if nobody calls externally
1134 mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001135
Felipe Leme03e689d2016-03-02 16:17:38 -08001136 Slog.i(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -08001137 }
1138
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001139 @Override
San Mehat873f2142010-01-14 10:25:07 -08001140 public boolean getIpForwardingEnabled() throws IllegalStateException{
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001141 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001142
Kenny Roota80ce062010-06-01 13:23:53 -07001143 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001144 final boolean isEnabled = mNetdService.ipfwdEnabled();
1145 return isEnabled;
1146 } catch (RemoteException | ServiceSpecificException e) {
1147 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001148 }
San Mehat873f2142010-01-14 10:25:07 -08001149 }
1150
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001151 @Override
1152 public void setIpForwardingEnabled(boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001153 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001154 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001155 if (enable) {
1156 mNetdService.ipfwdEnableForwarding("tethering");
1157 } else {
1158 mNetdService.ipfwdDisableForwarding("tethering");
1159 }
1160 } catch (RemoteException | ServiceSpecificException e) {
1161 throw new IllegalStateException(e);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001162 }
San Mehat873f2142010-01-14 10:25:07 -08001163 }
1164
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001165 @Override
1166 public void startTethering(String[] dhcpRange) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001167 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -07001168 // an odd number of addrs will fail
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001169
Kenny Roota80ce062010-06-01 13:23:53 -07001170 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001171 mNetdService.tetherStart(dhcpRange);
1172 } catch (RemoteException | ServiceSpecificException e) {
1173 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001174 }
San Mehat873f2142010-01-14 10:25:07 -08001175 }
1176
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001177 @Override
1178 public void stopTethering() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001179 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001180 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001181 mNetdService.tetherStop();
1182 } catch (RemoteException | ServiceSpecificException e) {
1183 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001184 }
San Mehat873f2142010-01-14 10:25:07 -08001185 }
1186
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001187 @Override
1188 public boolean isTetheringStarted() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001189 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001190
Kenny Roota80ce062010-06-01 13:23:53 -07001191 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001192 final boolean isEnabled = mNetdService.tetherIsEnabled();
1193 return isEnabled;
1194 } catch (RemoteException | ServiceSpecificException e) {
1195 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001196 }
San Mehat873f2142010-01-14 10:25:07 -08001197 }
Matthew Xiefe19f122012-07-12 16:03:32 -07001198
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001199 @Override
1200 public void tetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001201 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001202 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001203 mNetdService.tetherInterfaceAdd(iface);
1204 } catch (RemoteException | ServiceSpecificException e) {
1205 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001206 }
Christopher Wiley212b95f2016-08-02 11:38:57 -07001207 List<RouteInfo> routes = new ArrayList<>();
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07001208 // The RouteInfo constructor truncates the LinkAddress to a network prefix, thus making it
1209 // suitable to use as a route destination.
1210 routes.add(new RouteInfo(getInterfaceConfig(iface).getLinkAddress(), null, iface));
1211 addInterfaceToLocalNetwork(iface, routes);
San Mehat873f2142010-01-14 10:25:07 -08001212 }
1213
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001214 @Override
San Mehat873f2142010-01-14 10:25:07 -08001215 public void untetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001216 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001217 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001218 mNetdService.tetherInterfaceRemove(iface);
1219 } catch (RemoteException | ServiceSpecificException e) {
1220 throw new IllegalStateException(e);
Erik Kline1f4278a2016-08-16 16:46:33 +09001221 } finally {
1222 removeInterfaceFromLocalNetwork(iface);
Kenny Roota80ce062010-06-01 13:23:53 -07001223 }
San Mehat873f2142010-01-14 10:25:07 -08001224 }
1225
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001226 @Override
1227 public String[] listTetheredInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001228 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001229 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +08001230 return mNetdService.tetherInterfaceList();
Luke Huang4a32bf42018-08-21 19:09:45 +08001231 } catch (RemoteException | ServiceSpecificException e) {
1232 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001233 }
San Mehat873f2142010-01-14 10:25:07 -08001234 }
1235
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001236 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001237 public void setDnsForwarders(Network network, String[] dns) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001238 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001239
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001240 int netId = (network != null) ? network.netId : ConnectivityManager.NETID_UNSET;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001241
San Mehat873f2142010-01-14 10:25:07 -08001242 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001243 mNetdService.tetherDnsSet(netId, dns);
1244 } catch (RemoteException | ServiceSpecificException e) {
1245 throw new IllegalStateException(e);
San Mehat873f2142010-01-14 10:25:07 -08001246 }
1247 }
1248
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001249 @Override
1250 public String[] getDnsForwarders() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001251 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001252 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +08001253 return mNetdService.tetherDnsList();
Luke Huang4a32bf42018-08-21 19:09:45 +08001254 } catch (RemoteException | ServiceSpecificException e) {
1255 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001256 }
San Mehat873f2142010-01-14 10:25:07 -08001257 }
1258
jiaguo1da35f72014-01-09 16:39:59 +08001259 private List<InterfaceAddress> excludeLinkLocal(List<InterfaceAddress> addresses) {
Christopher Wiley212b95f2016-08-02 11:38:57 -07001260 ArrayList<InterfaceAddress> filtered = new ArrayList<>(addresses.size());
jiaguo1da35f72014-01-09 16:39:59 +08001261 for (InterfaceAddress ia : addresses) {
1262 if (!ia.getAddress().isLinkLocalAddress())
1263 filtered.add(ia);
1264 }
1265 return filtered;
1266 }
1267
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001268 private void modifyInterfaceForward(boolean add, String fromIface, String toIface) {
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001269 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001270 if (add) {
1271 mNetdService.ipfwdAddInterfaceForward(fromIface, toIface);
1272 } else {
1273 mNetdService.ipfwdRemoveInterfaceForward(fromIface, toIface);
1274 }
1275 } catch (RemoteException | ServiceSpecificException e) {
1276 throw new IllegalStateException(e);
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001277 }
1278 }
1279
1280 @Override
1281 public void startInterfaceForwarding(String fromIface, String toIface) {
1282 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1283 modifyInterfaceForward(true, fromIface, toIface);
1284 }
1285
1286 @Override
1287 public void stopInterfaceForwarding(String fromIface, String toIface) {
1288 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1289 modifyInterfaceForward(false, fromIface, toIface);
1290 }
1291
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001292 @Override
1293 public void enableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001294 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001295 try {
Luke Huanga31e0732018-10-22 13:23:10 +09001296 mNetdService.tetherAddForward(internalInterface, externalInterface);
1297 } catch (RemoteException | ServiceSpecificException e) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001298 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001299 }
San Mehat873f2142010-01-14 10:25:07 -08001300 }
1301
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001302 @Override
1303 public void disableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001304 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001305 try {
Luke Huanga31e0732018-10-22 13:23:10 +09001306 mNetdService.tetherRemoveForward(internalInterface, externalInterface);
1307 } catch (RemoteException | ServiceSpecificException e) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001308 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001309 }
San Mehat873f2142010-01-14 10:25:07 -08001310 }
San Mehat72759df2010-01-19 13:50:37 -08001311
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001312 @Override
1313 public String[] listTtys() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001314 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001315 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001316 return NativeDaemonEvent.filterMessageList(
1317 mConnector.executeForList("list_ttys"), TtyListResult);
Kenny Roota80ce062010-06-01 13:23:53 -07001318 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001319 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001320 }
San Mehat72759df2010-01-19 13:50:37 -08001321 }
1322
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001323 @Override
1324 public void attachPppd(
1325 String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001326 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat72759df2010-01-19 13:50:37 -08001327 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001328 mConnector.execute("pppd", "attach", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -08001329 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
1330 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
1331 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001332 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress());
Kenny Roota80ce062010-06-01 13:23:53 -07001333 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001334 throw e.rethrowAsParcelableException();
San Mehat72759df2010-01-19 13:50:37 -08001335 }
1336 }
1337
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001338 @Override
1339 public void detachPppd(String tty) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001340 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001341 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001342 mConnector.execute("pppd", "detach", tty);
Kenny Roota80ce062010-06-01 13:23:53 -07001343 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001344 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001345 }
San Mehat72759df2010-01-19 13:50:37 -08001346 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -08001347
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001348 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001349 public void addIdleTimer(String iface, int timeout, final int type) {
Haoyu Bai04124232012-06-28 15:26:19 -07001350 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1351
1352 if (DBG) Slog.d(TAG, "Adding idletimer");
1353
1354 synchronized (mIdleTimerLock) {
1355 IdleTimerParams params = mActiveIdleTimers.get(iface);
1356 if (params != null) {
1357 // the interface already has idletimer, update network count
1358 params.networkCount++;
1359 return;
1360 }
1361
1362 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001363 mNetdService.idletimerAddInterface(iface, timeout, Integer.toString(type));
1364 } catch (RemoteException | ServiceSpecificException e) {
1365 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001366 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001367 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
1368
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001369 // Networks start up.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001370 if (ConnectivityManager.isNetworkTypeMobile(type)) {
1371 mNetworkActive = false;
1372 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001373 mDaemonHandler.post(new Runnable() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001374 @Override public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001375 notifyInterfaceClassActivity(type,
1376 DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07001377 SystemClock.elapsedRealtimeNanos(), -1, false);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001378 }
1379 });
Haoyu Bai04124232012-06-28 15:26:19 -07001380 }
1381 }
1382
1383 @Override
1384 public void removeIdleTimer(String iface) {
1385 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1386
1387 if (DBG) Slog.d(TAG, "Removing idletimer");
1388
1389 synchronized (mIdleTimerLock) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001390 final IdleTimerParams params = mActiveIdleTimers.get(iface);
Haoyu Bai04124232012-06-28 15:26:19 -07001391 if (params == null || --(params.networkCount) > 0) {
1392 return;
1393 }
1394
1395 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001396 mNetdService.idletimerRemoveInterface(iface,
1397 params.timeout, Integer.toString(params.type));
1398 } catch (RemoteException | ServiceSpecificException e) {
1399 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001400 }
1401 mActiveIdleTimers.remove(iface);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001402 mDaemonHandler.post(new Runnable() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001403 @Override public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001404 notifyInterfaceClassActivity(params.type,
1405 DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07001406 SystemClock.elapsedRealtimeNanos(), -1, false);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001407 }
1408 });
Haoyu Bai04124232012-06-28 15:26:19 -07001409 }
1410 }
1411
1412 @Override
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001413 public NetworkStats getNetworkStatsSummaryDev() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001414 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001415 try {
1416 return mStatsFactory.readNetworkStatsSummaryDev();
1417 } catch (IOException e) {
1418 throw new IllegalStateException(e);
1419 }
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001420 }
1421
1422 @Override
1423 public NetworkStats getNetworkStatsSummaryXt() {
1424 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001425 try {
1426 return mStatsFactory.readNetworkStatsSummaryXt();
1427 } catch (IOException e) {
1428 throw new IllegalStateException(e);
1429 }
Jeff Sharkeyae2c1812011-10-04 13:11:40 -07001430 }
1431
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001432 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001433 public NetworkStats getNetworkStatsDetail() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001434 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001435 try {
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08001436 return mStatsFactory.readNetworkStatsDetail(UID_ALL, null, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001437 } catch (IOException e) {
1438 throw new IllegalStateException(e);
1439 }
San Mehat91cac642010-03-31 14:31:36 -07001440 }
1441
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001442 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001443 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001444 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001445
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001446 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001447 if (mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001448 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001449 }
1450
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001451 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001452 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001453 mNetdService.bandwidthSetInterfaceQuota(iface, quotaBytes);
1454
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001455 mActiveQuotas.put(iface, quotaBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001456 } catch (RemoteException | ServiceSpecificException e) {
1457 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001458 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001459
1460 synchronized (mTetheringStatsProviders) {
1461 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1462 try {
1463 provider.setInterfaceQuota(iface, quotaBytes);
1464 } catch (RemoteException e) {
1465 Log.e(TAG, "Problem setting tethering data limit on provider " +
1466 mTetheringStatsProviders.get(provider) + ": " + e);
1467 }
1468 }
1469 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001470 }
1471 }
1472
1473 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001474 public void removeInterfaceQuota(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001475 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001476
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001477 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001478 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001479 // TODO: eventually consider throwing
1480 return;
1481 }
1482
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001483 mActiveQuotas.remove(iface);
1484 mActiveAlerts.remove(iface);
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001485
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001486 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001487 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001488 mNetdService.bandwidthRemoveInterfaceQuota(iface);
1489 } catch (RemoteException | ServiceSpecificException e) {
1490 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001491 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001492
1493 synchronized (mTetheringStatsProviders) {
1494 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1495 try {
1496 provider.setInterfaceQuota(iface, ITetheringStatsProvider.QUOTA_UNLIMITED);
1497 } catch (RemoteException e) {
1498 Log.e(TAG, "Problem removing tethering data limit on provider " +
1499 mTetheringStatsProviders.get(provider) + ": " + e);
1500 }
1501 }
1502 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001503 }
1504 }
1505
1506 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001507 public void setInterfaceAlert(String iface, long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001508 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001509
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001510 // quick sanity check
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001511 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001512 throw new IllegalStateException("setting alert requires existing quota on iface");
1513 }
1514
1515 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001516 if (mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001517 throw new IllegalStateException("iface " + iface + " already has alert");
1518 }
1519
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001520 try {
1521 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001522 mNetdService.bandwidthSetInterfaceAlert(iface, alertBytes);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001523 mActiveAlerts.put(iface, alertBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001524 } catch (RemoteException | ServiceSpecificException e) {
1525 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001526 }
1527 }
1528 }
1529
1530 @Override
1531 public void removeInterfaceAlert(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001532 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001533
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001534 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001535 if (!mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001536 // TODO: eventually consider throwing
1537 return;
1538 }
1539
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001540 try {
1541 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001542 mNetdService.bandwidthRemoveInterfaceAlert(iface);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001543 mActiveAlerts.remove(iface);
Luke Huangc7bea8662018-08-07 16:04:26 +08001544 } catch (RemoteException | ServiceSpecificException e) {
1545 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001546 }
1547 }
1548 }
1549
1550 @Override
1551 public void setGlobalAlert(long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001552 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001553
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001554 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001555 mNetdService.bandwidthSetGlobalAlert(alertBytes);
1556 } catch (RemoteException | ServiceSpecificException e) {
1557 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001558 }
1559 }
1560
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001561 private void setUidOnMeteredNetworkList(int uid, boolean blacklist, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001562 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001563
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001564 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001565 boolean oldEnable;
1566 SparseBooleanArray quotaList;
1567 synchronized (mRulesLock) {
1568 quotaList = blacklist ? mUidRejectOnMetered : mUidAllowOnMetered;
1569 oldEnable = quotaList.get(uid, false);
1570 }
Felipe Leme65be3022016-03-22 14:53:13 -07001571 if (oldEnable == enable) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001572 // TODO: eventually consider throwing
1573 return;
1574 }
1575
Felipe Leme29e72ea2016-09-08 13:26:55 -07001576 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "inetd bandwidth");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001577 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001578 if (blacklist) {
1579 if (enable) {
1580 mNetdService.bandwidthAddNaughtyApp(uid);
1581 } else {
1582 mNetdService.bandwidthRemoveNaughtyApp(uid);
1583 }
1584 } else {
1585 if (enable) {
1586 mNetdService.bandwidthAddNiceApp(uid);
1587 } else {
1588 mNetdService.bandwidthRemoveNiceApp(uid);
1589 }
1590 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001591 synchronized (mRulesLock) {
1592 if (enable) {
1593 quotaList.put(uid, true);
1594 } else {
1595 quotaList.delete(uid);
1596 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001597 }
Luke Huangc7bea8662018-08-07 16:04:26 +08001598 } catch (RemoteException | ServiceSpecificException e) {
1599 throw new IllegalStateException(e);
Felipe Leme29e72ea2016-09-08 13:26:55 -07001600 } finally {
1601 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001602 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001603 }
1604 }
1605
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001606 @Override
Felipe Leme65be3022016-03-22 14:53:13 -07001607 public void setUidMeteredNetworkBlacklist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001608 setUidOnMeteredNetworkList(uid, true, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001609 }
1610
1611 @Override
1612 public void setUidMeteredNetworkWhitelist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001613 setUidOnMeteredNetworkList(uid, false, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001614 }
1615
1616 @Override
1617 public boolean setDataSaverModeEnabled(boolean enable) {
Sehee Parka9139bc2017-12-22 13:54:05 +09001618 mContext.enforceCallingOrSelfPermission(NETWORK_SETTINGS, TAG);
1619
Felipe Leme65be3022016-03-22 14:53:13 -07001620 if (DBG) Log.d(TAG, "setDataSaverMode: " + enable);
1621 synchronized (mQuotaLock) {
1622 if (mDataSaverMode == enable) {
1623 Log.w(TAG, "setDataSaverMode(): already " + mDataSaverMode);
1624 return true;
1625 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07001626 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "bandwidthEnableDataSaver");
Felipe Leme65be3022016-03-22 14:53:13 -07001627 try {
1628 final boolean changed = mNetdService.bandwidthEnableDataSaver(enable);
1629 if (changed) {
1630 mDataSaverMode = enable;
1631 } else {
1632 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command silently failed");
1633 }
1634 return changed;
1635 } catch (RemoteException e) {
1636 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command failed", e);
1637 return false;
Felipe Leme29e72ea2016-09-08 13:26:55 -07001638 } finally {
1639 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme65be3022016-03-22 14:53:13 -07001640 }
1641 }
1642 }
1643
1644 @Override
Robin Lee17e61832016-05-09 13:46:28 +01001645 public void setAllowOnlyVpnForUids(boolean add, UidRange[] uidRanges)
1646 throws ServiceSpecificException {
Rubin Xu2ea6c552018-01-11 10:59:19 +00001647 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robin Lee17e61832016-05-09 13:46:28 +01001648 try {
1649 mNetdService.networkRejectNonSecureVpn(add, uidRanges);
1650 } catch (ServiceSpecificException e) {
1651 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1652 + ": netd command failed", e);
1653 throw e;
1654 } catch (RemoteException e) {
1655 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1656 + ": netd command failed", e);
1657 throw e.rethrowAsRuntimeException();
1658 }
1659 }
1660
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001661 private void applyUidCleartextNetworkPolicy(int uid, int policy) {
Luke Huang473eb872018-07-26 17:33:14 +08001662 final int policyValue;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001663 switch (policy) {
1664 case StrictMode.NETWORK_POLICY_ACCEPT:
Luke Huang473eb872018-07-26 17:33:14 +08001665 policyValue = INetd.PENALTY_POLICY_ACCEPT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001666 break;
1667 case StrictMode.NETWORK_POLICY_LOG:
Luke Huang473eb872018-07-26 17:33:14 +08001668 policyValue = INetd.PENALTY_POLICY_LOG;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001669 break;
1670 case StrictMode.NETWORK_POLICY_REJECT:
Luke Huang473eb872018-07-26 17:33:14 +08001671 policyValue = INetd.PENALTY_POLICY_REJECT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001672 break;
1673 default:
1674 throw new IllegalArgumentException("Unknown policy " + policy);
1675 }
1676
1677 try {
Luke Huang473eb872018-07-26 17:33:14 +08001678 mNetdService.strictUidCleartextPenalty(uid, policyValue);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001679 mUidCleartextPolicy.put(uid, policy);
Luke Huang473eb872018-07-26 17:33:14 +08001680 } catch (RemoteException | ServiceSpecificException e) {
1681 throw new IllegalStateException(e);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001682 }
1683 }
1684
Robin Lee17e61832016-05-09 13:46:28 +01001685 @Override
Jeff Sharkey605eb792014-11-04 13:34:06 -08001686 public void setUidCleartextNetworkPolicy(int uid, int policy) {
1687 if (Binder.getCallingUid() != uid) {
1688 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1689 }
1690
1691 synchronized (mQuotaLock) {
1692 final int oldPolicy = mUidCleartextPolicy.get(uid, StrictMode.NETWORK_POLICY_ACCEPT);
1693 if (oldPolicy == policy) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001694 // This also ensures we won't needlessly apply an ACCEPT policy if we've just
1695 // enabled strict and the underlying iptables rules are empty.
Jeff Sharkey605eb792014-11-04 13:34:06 -08001696 return;
1697 }
1698
Luke Huang473eb872018-07-26 17:33:14 +08001699 // TODO: remove this code after removing prepareNativeDaemon()
Jeff Sharkey605eb792014-11-04 13:34:06 -08001700 if (!mStrictEnabled) {
1701 // Module isn't enabled yet; stash the requested policy away to
1702 // apply later once the daemon is connected.
1703 mUidCleartextPolicy.put(uid, policy);
1704 return;
1705 }
1706
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001707 // netd does not keep state on strict mode policies, and cannot replace a non-accept
1708 // policy without deleting it first. Rather than add state to netd, just always send
1709 // it an accept policy when switching between two non-accept policies.
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001710 // TODO: consider keeping state in netd so we can simplify this code.
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001711 if (oldPolicy != StrictMode.NETWORK_POLICY_ACCEPT &&
1712 policy != StrictMode.NETWORK_POLICY_ACCEPT) {
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001713 applyUidCleartextNetworkPolicy(uid, StrictMode.NETWORK_POLICY_ACCEPT);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001714 }
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001715
1716 applyUidCleartextNetworkPolicy(uid, policy);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001717 }
1718 }
1719
1720 @Override
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001721 public boolean isBandwidthControlEnabled() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001722 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang56a03a02018-09-07 12:02:16 +08001723 return true;
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001724 }
1725
1726 @Override
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001727 public NetworkStats getNetworkStatsUidDetail(int uid, String[] ifaces) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001728 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001729 try {
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001730 return mStatsFactory.readNetworkStatsDetail(uid, ifaces, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001731 } catch (IOException e) {
1732 throw new IllegalStateException(e);
1733 }
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001734 }
1735
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001736 private class NetdTetheringStatsProvider extends ITetheringStatsProvider.Stub {
1737 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001738 public NetworkStats getTetherStats(int how) {
1739 // We only need to return per-UID stats. Per-device stats are already counted by
1740 // interface counters.
1741 if (how != STATS_PER_UID) {
1742 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
1743 }
1744
Luke Huang13b79e82018-09-26 14:53:42 +08001745 final TetherStatsParcel[] tetherStatsVec;
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001746 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001747 tetherStatsVec = mNetdService.tetherGetStats();
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001748 } catch (RemoteException | ServiceSpecificException e) {
1749 throw new IllegalStateException("problem parsing tethering stats: ", e);
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001750 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001751
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001752 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(),
Luke Huang13b79e82018-09-26 14:53:42 +08001753 tetherStatsVec.length);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001754 final NetworkStats.Entry entry = new NetworkStats.Entry();
1755
Luke Huang13b79e82018-09-26 14:53:42 +08001756 for (TetherStatsParcel tetherStats : tetherStatsVec) {
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001757 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001758 entry.iface = tetherStats.iface;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001759 entry.uid = UID_TETHERING;
1760 entry.set = SET_DEFAULT;
1761 entry.tag = TAG_NONE;
Luke Huang13b79e82018-09-26 14:53:42 +08001762 entry.rxBytes = tetherStats.rxBytes;
1763 entry.rxPackets = tetherStats.rxPackets;
1764 entry.txBytes = tetherStats.txBytes;
1765 entry.txPackets = tetherStats.txPackets;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001766 stats.combineValues(entry);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001767 } catch (ArrayIndexOutOfBoundsException e) {
Luke Huang13b79e82018-09-26 14:53:42 +08001768 throw new IllegalStateException("invalid tethering stats " + e);
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001769 }
1770 }
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001771
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001772 return stats;
1773 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001774
1775 @Override
1776 public void setInterfaceQuota(String iface, long quotaBytes) {
1777 // Do nothing. netd is already informed of quota changes in setInterfaceQuota.
1778 }
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001779 }
1780
1781 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001782 public NetworkStats getNetworkStatsTethering(int how) {
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001783 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1784
1785 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1786 synchronized (mTetheringStatsProviders) {
1787 for (ITetheringStatsProvider provider: mTetheringStatsProviders.keySet()) {
1788 try {
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001789 stats.combineAllValues(provider.getTetherStats(how));
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001790 } catch (RemoteException e) {
1791 Log.e(TAG, "Problem reading tethering stats from " +
1792 mTetheringStatsProviders.get(provider) + ": " + e);
1793 }
1794 }
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001795 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001796 return stats;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001797 }
1798
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001799 @Override
Erik Kline1742fe12017-12-13 19:40:49 +09001800 public void setDnsConfigurationForNetwork(int netId, String[] servers, String[] domains,
Erik Klinee5dac902018-03-04 21:01:01 +09001801 int[] params, String tlsHostname, String[] tlsServers) {
Pierre Imai8e48e672016-04-21 13:30:43 +09001802 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1803
Ben Schwartz6ec28df2017-10-02 13:08:06 -04001804 final String[] tlsFingerprints = new String[0];
Pierre Imai8e48e672016-04-21 13:30:43 +09001805 try {
Erik Kline1742fe12017-12-13 19:40:49 +09001806 mNetdService.setResolverConfiguration(
Erik Klinee5dac902018-03-04 21:01:01 +09001807 netId, servers, domains, params, tlsHostname, tlsServers, tlsFingerprints);
Pierre Imai8e48e672016-04-21 13:30:43 +09001808 } catch (RemoteException e) {
1809 throw new RuntimeException(e);
1810 }
1811 }
1812
1813 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001814 public void addVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001815 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001816
1817 try {
1818 mNetdService.networkAddUidRanges(netId, ranges);
1819 } catch (RemoteException | ServiceSpecificException e) {
1820 throw new IllegalStateException(e);
Chad Brubaker3277620a2013-06-12 13:37:30 -07001821 }
1822 }
1823
1824 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001825 public void removeVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001826 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001827 try {
1828 mNetdService.networkRemoveUidRanges(netId, ranges);
1829 } catch (RemoteException | ServiceSpecificException e) {
1830 throw new IllegalStateException(e);
Chad Brubakercca54c42013-06-27 17:41:38 -07001831 }
1832 }
1833
1834 @Override
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001835 public void setFirewallEnabled(boolean enabled) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001836 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001837 try {
Luke Huanga241db92018-07-31 20:15:24 +08001838 mNetdService.firewallSetFirewallType(
1839 enabled ? INetd.FIREWALL_WHITELIST : INetd.FIREWALL_BLACKLIST);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001840 mFirewallEnabled = enabled;
Luke Huanga241db92018-07-31 20:15:24 +08001841 } catch (RemoteException | ServiceSpecificException e) {
1842 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001843 }
1844 }
1845
1846 @Override
1847 public boolean isFirewallEnabled() {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001848 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001849 return mFirewallEnabled;
1850 }
1851
1852 @Override
Jeff Sharkey2c092982012-08-24 11:44:40 -07001853 public void setFirewallInterfaceRule(String iface, boolean allow) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001854 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001855 Preconditions.checkState(mFirewallEnabled);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001856 try {
Luke Huanga241db92018-07-31 20:15:24 +08001857 mNetdService.firewallSetInterfaceRule(iface,
1858 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
1859 } catch (RemoteException | ServiceSpecificException e) {
1860 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001861 }
1862 }
1863
Lorenzo Colitti3fef7232016-04-29 18:00:03 +09001864 private void closeSocketsForFirewallChainLocked(int chain, String chainName) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001865 // UID ranges to close sockets on.
1866 UidRange[] ranges;
1867 // UID ranges whose sockets we won't touch.
1868 int[] exemptUids;
1869
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001870 int numUids = 0;
Luke Huanga241db92018-07-31 20:15:24 +08001871 if (DBG) Slog.d(TAG, "Closing sockets after enabling chain " + chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001872 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
1873 // Close all sockets on all non-system UIDs...
1874 ranges = new UidRange[] {
1875 // TODO: is there a better way of finding all existing users? If so, we could
1876 // specify their ranges here.
1877 new UidRange(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE),
1878 };
1879 // ... except for the UIDs that have allow rules.
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001880 synchronized (mRulesLock) {
1881 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1882 exemptUids = new int[rules.size()];
1883 for (int i = 0; i < exemptUids.length; i++) {
1884 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
1885 exemptUids[numUids] = rules.keyAt(i);
1886 numUids++;
1887 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001888 }
1889 }
1890 // Normally, whitelist chains only contain deny rules, so numUids == exemptUids.length.
1891 // But the code does not guarantee this in any way, and at least in one case - if we add
1892 // a UID rule to the firewall, and then disable the firewall - the chains can contain
1893 // the wrong type of rule. In this case, don't close connections that we shouldn't.
1894 //
1895 // TODO: tighten up this code by ensuring we never set the wrong type of rule, and
1896 // fix setFirewallEnabled to grab mQuotaLock and clear rules.
1897 if (numUids != exemptUids.length) {
1898 exemptUids = Arrays.copyOf(exemptUids, numUids);
1899 }
1900 } else {
1901 // Close sockets for every UID that has a deny rule...
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001902 synchronized (mRulesLock) {
1903 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1904 ranges = new UidRange[rules.size()];
1905 for (int i = 0; i < ranges.length; i++) {
1906 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_DENY) {
1907 int uid = rules.keyAt(i);
1908 ranges[numUids] = new UidRange(uid, uid);
1909 numUids++;
1910 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001911 }
1912 }
1913 // As above; usually numUids == ranges.length, but not always.
1914 if (numUids != ranges.length) {
1915 ranges = Arrays.copyOf(ranges, numUids);
1916 }
1917 // ... with no exceptions.
1918 exemptUids = new int[0];
1919 }
1920
1921 try {
1922 mNetdService.socketDestroy(ranges, exemptUids);
1923 } catch(RemoteException | ServiceSpecificException e) {
1924 Slog.e(TAG, "Error closing sockets after enabling chain " + chainName + ": " + e);
1925 }
1926 }
1927
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001928 @Override
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001929 public void setFirewallChainEnabled(int chain, boolean enable) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001930 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001931 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001932 synchronized (mRulesLock) {
1933 if (getFirewallChainState(chain) == enable) {
1934 // All is the same, nothing to do. This relies on the fact that netd has child
1935 // chains default detached.
1936 return;
1937 }
1938 setFirewallChainState(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001939 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001940
Luke Huang615e1022018-10-25 11:54:05 +09001941 final String chainName = getFirewallChainName(chain);
Luke Huanga241db92018-07-31 20:15:24 +08001942 if (chain == FIREWALL_CHAIN_NONE) {
Luke Huang615e1022018-10-25 11:54:05 +09001943 throw new IllegalArgumentException("Bad child chain: " + chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001944 }
1945
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001946 try {
Luke Huanga241db92018-07-31 20:15:24 +08001947 mNetdService.firewallEnableChildChain(chain, enable);
1948 } catch (RemoteException | ServiceSpecificException e) {
1949 throw new IllegalStateException(e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001950 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001951
1952 // Close any sockets that were opened by the affected UIDs. This has to be done after
1953 // disabling network connectivity, in case they react to the socket close by reopening
1954 // the connection and race with the iptables commands that enable the firewall. All
1955 // whitelist and blacklist chains allow RSTs through.
1956 if (enable) {
Luke Huang615e1022018-10-25 11:54:05 +09001957 closeSocketsForFirewallChainLocked(chain, chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001958 }
Amith Yamasani15e472352015-04-24 19:06:07 -07001959 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001960 }
1961
Luke Huanga241db92018-07-31 20:15:24 +08001962 private String getFirewallChainName(int chain) {
1963 switch (chain) {
1964 case FIREWALL_CHAIN_STANDBY:
1965 return FIREWALL_CHAIN_NAME_STANDBY;
1966 case FIREWALL_CHAIN_DOZABLE:
1967 return FIREWALL_CHAIN_NAME_DOZABLE;
1968 case FIREWALL_CHAIN_POWERSAVE:
1969 return FIREWALL_CHAIN_NAME_POWERSAVE;
1970 default:
1971 throw new IllegalArgumentException("Bad child chain: " + chain);
1972 }
1973 }
1974
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001975 private int getFirewallType(int chain) {
1976 switch (chain) {
1977 case FIREWALL_CHAIN_STANDBY:
1978 return FIREWALL_TYPE_BLACKLIST;
1979 case FIREWALL_CHAIN_DOZABLE:
1980 return FIREWALL_TYPE_WHITELIST;
Felipe Leme011b98f2016-02-10 17:28:31 -08001981 case FIREWALL_CHAIN_POWERSAVE:
1982 return FIREWALL_TYPE_WHITELIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001983 default:
1984 return isFirewallEnabled() ? FIREWALL_TYPE_WHITELIST : FIREWALL_TYPE_BLACKLIST;
1985 }
1986 }
1987
1988 @Override
1989 public void setFirewallUidRules(int chain, int[] uids, int[] rules) {
1990 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001991 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001992 synchronized (mRulesLock) {
1993 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
1994 SparseIntArray newRules = new SparseIntArray();
1995 // apply new set of rules
1996 for (int index = uids.length - 1; index >= 0; --index) {
1997 int uid = uids[index];
1998 int rule = rules[index];
1999 updateFirewallUidRuleLocked(chain, uid, rule);
2000 newRules.put(uid, rule);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002001 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002002 // collect the rules to remove.
2003 SparseIntArray rulesToRemove = new SparseIntArray();
2004 for (int index = uidFirewallRules.size() - 1; index >= 0; --index) {
2005 int uid = uidFirewallRules.keyAt(index);
2006 if (newRules.indexOfKey(uid) < 0) {
2007 rulesToRemove.put(uid, FIREWALL_RULE_DEFAULT);
2008 }
2009 }
2010 // remove dead rules
2011 for (int index = rulesToRemove.size() - 1; index >= 0; --index) {
2012 int uid = rulesToRemove.keyAt(index);
2013 updateFirewallUidRuleLocked(chain, uid, FIREWALL_RULE_DEFAULT);
2014 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002015 }
2016 try {
2017 switch (chain) {
2018 case FIREWALL_CHAIN_DOZABLE:
2019 mNetdService.firewallReplaceUidChain("fw_dozable", true, uids);
2020 break;
2021 case FIREWALL_CHAIN_STANDBY:
2022 mNetdService.firewallReplaceUidChain("fw_standby", false, uids);
2023 break;
2024 case FIREWALL_CHAIN_POWERSAVE:
2025 mNetdService.firewallReplaceUidChain("fw_powersave", true, uids);
2026 break;
2027 case FIREWALL_CHAIN_NONE:
2028 default:
2029 Slog.d(TAG, "setFirewallUidRules() called on invalid chain: " + chain);
2030 }
2031 } catch (RemoteException e) {
2032 Slog.w(TAG, "Error flushing firewall chain " + chain, e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002033 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002034 }
2035 }
2036
2037 @Override
2038 public void setFirewallUidRule(int chain, int uid, int rule) {
2039 enforceSystemUid();
Felipe Lemea701cad2016-05-12 09:58:14 -07002040 synchronized (mQuotaLock) {
2041 setFirewallUidRuleLocked(chain, uid, rule);
2042 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002043 }
2044
Felipe Lemea701cad2016-05-12 09:58:14 -07002045 private void setFirewallUidRuleLocked(int chain, int uid, int rule) {
2046 if (updateFirewallUidRuleLocked(chain, uid, rule)) {
Luke Huanga241db92018-07-31 20:15:24 +08002047 final int ruleType = getFirewallRuleType(chain, rule);
Amith Yamasani15e472352015-04-24 19:06:07 -07002048 try {
Luke Huanga241db92018-07-31 20:15:24 +08002049 mNetdService.firewallSetUidRule(chain, uid, ruleType);
2050 } catch (RemoteException | ServiceSpecificException e) {
2051 throw new IllegalStateException(e);
Amith Yamasani15e472352015-04-24 19:06:07 -07002052 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002053 }
2054 }
2055
Felipe Lemea701cad2016-05-12 09:58:14 -07002056 // TODO: now that netd supports batching, NMS should not keep these data structures anymore...
2057 private boolean updateFirewallUidRuleLocked(int chain, int uid, int rule) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002058 synchronized (mRulesLock) {
2059 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Felipe Lemea701cad2016-05-12 09:58:14 -07002060
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002061 final int oldUidFirewallRule = uidFirewallRules.get(uid, FIREWALL_RULE_DEFAULT);
2062 if (DBG) {
2063 Slog.d(TAG, "oldRule = " + oldUidFirewallRule
2064 + ", newRule=" + rule + " for uid=" + uid + " on chain " + chain);
2065 }
2066 if (oldUidFirewallRule == rule) {
2067 if (DBG) Slog.d(TAG, "!!!!! Skipping change");
2068 // TODO: eventually consider throwing
2069 return false;
2070 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002071
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002072 String ruleName = getFirewallRuleName(chain, rule);
2073 String oldRuleName = getFirewallRuleName(chain, oldUidFirewallRule);
Felipe Lemea701cad2016-05-12 09:58:14 -07002074
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002075 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
2076 uidFirewallRules.delete(uid);
2077 } else {
2078 uidFirewallRules.put(uid, rule);
2079 }
2080 return !ruleName.equals(oldRuleName);
Felipe Lemea701cad2016-05-12 09:58:14 -07002081 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002082 }
2083
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002084 private @NonNull String getFirewallRuleName(int chain, int rule) {
2085 String ruleName;
2086 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
2087 if (rule == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
2088 ruleName = "allow";
2089 } else {
2090 ruleName = "deny";
2091 }
2092 } else { // Blacklist mode
2093 if (rule == NetworkPolicyManager.FIREWALL_RULE_DENY) {
2094 ruleName = "deny";
2095 } else {
2096 ruleName = "allow";
2097 }
2098 }
2099 return ruleName;
2100 }
2101
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002102 private @NonNull SparseIntArray getUidFirewallRulesLR(int chain) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002103 switch (chain) {
2104 case FIREWALL_CHAIN_STANDBY:
2105 return mUidFirewallStandbyRules;
2106 case FIREWALL_CHAIN_DOZABLE:
2107 return mUidFirewallDozableRules;
Felipe Leme011b98f2016-02-10 17:28:31 -08002108 case FIREWALL_CHAIN_POWERSAVE:
2109 return mUidFirewallPowerSaveRules;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002110 case FIREWALL_CHAIN_NONE:
2111 return mUidFirewallRules;
2112 default:
2113 throw new IllegalArgumentException("Unknown chain:" + chain);
2114 }
2115 }
2116
Luke Huanga241db92018-07-31 20:15:24 +08002117 private int getFirewallRuleType(int chain, int rule) {
Luke Huang615e1022018-10-25 11:54:05 +09002118 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
2119 return getFirewallType(chain) == FIREWALL_TYPE_WHITELIST
2120 ? INetd.FIREWALL_RULE_DENY : INetd.FIREWALL_RULE_ALLOW;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002121 }
Luke Huang615e1022018-10-25 11:54:05 +09002122 return rule;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002123 }
2124
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07002125 private static void enforceSystemUid() {
2126 final int uid = Binder.getCallingUid();
2127 if (uid != Process.SYSTEM_UID) {
2128 throw new SecurityException("Only available to AID_SYSTEM");
2129 }
2130 }
2131
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002132 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002133 public void registerNetworkActivityListener(INetworkActivityListener listener) {
2134 mNetworkActivityListeners.register(listener);
2135 }
2136
2137 @Override
2138 public void unregisterNetworkActivityListener(INetworkActivityListener listener) {
2139 mNetworkActivityListeners.unregister(listener);
2140 }
2141
2142 @Override
2143 public boolean isNetworkActive() {
2144 synchronized (mNetworkActivityListeners) {
2145 return mNetworkActive || mActiveIdleTimers.isEmpty();
2146 }
2147 }
2148
2149 private void reportNetworkActive() {
2150 final int length = mNetworkActivityListeners.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002151 try {
2152 for (int i = 0; i < length; i++) {
2153 try {
2154 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
Felipe Leme03e689d2016-03-02 16:17:38 -08002155 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002156 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002157 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002158 } finally {
2159 mNetworkActivityListeners.finishBroadcast();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002160 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002161 }
2162
Mattias Falk8b47b362011-08-23 14:15:13 +02002163 /** {@inheritDoc} */
Jeff Sharkey7b4596f2013-02-25 10:55:29 -08002164 @Override
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002165 public void monitor() {
2166 if (mConnector != null) {
2167 mConnector.monitor();
2168 }
2169 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002170
2171 @Override
2172 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002173 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002174
Robert Greenwalt470fd722012-01-18 12:51:15 -08002175 pw.println("NetworkManagementService NativeDaemonConnector Log:");
2176 mConnector.dump(fd, pw, args);
2177 pw.println();
2178
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07002179 pw.print("mMobileActivityFromRadio="); pw.print(mMobileActivityFromRadio);
2180 pw.print(" mLastPowerStateFromRadio="); pw.println(mLastPowerStateFromRadio);
2181 pw.print("mNetworkActive="); pw.println(mNetworkActive);
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002182
2183 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07002184 pw.print("Active quota ifaces: "); pw.println(mActiveQuotas.toString());
2185 pw.print("Active alert ifaces: "); pw.println(mActiveAlerts.toString());
Felipe Leme65be3022016-03-22 14:53:13 -07002186 pw.print("Data saver mode: "); pw.println(mDataSaverMode);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002187 synchronized (mRulesLock) {
2188 dumpUidRuleOnQuotaLocked(pw, "blacklist", mUidRejectOnMetered);
2189 dumpUidRuleOnQuotaLocked(pw, "whitelist", mUidAllowOnMetered);
2190 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002191 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002192
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002193 synchronized (mRulesLock) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002194 dumpUidFirewallRule(pw, "", mUidFirewallRules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002195
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002196 pw.print("UID firewall standby chain enabled: "); pw.println(
2197 getFirewallChainState(FIREWALL_CHAIN_STANDBY));
Felipe Leme011b98f2016-02-10 17:28:31 -08002198 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_STANDBY, mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002199
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002200 pw.print("UID firewall dozable chain enabled: "); pw.println(
2201 getFirewallChainState(FIREWALL_CHAIN_DOZABLE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002202 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_DOZABLE, mUidFirewallDozableRules);
Felipe Leme011b98f2016-02-10 17:28:31 -08002203
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002204 pw.println("UID firewall powersave chain enabled: " +
2205 getFirewallChainState(FIREWALL_CHAIN_POWERSAVE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002206 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_POWERSAVE, mUidFirewallPowerSaveRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002207 }
2208
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002209 synchronized (mIdleTimerLock) {
2210 pw.println("Idle timers:");
2211 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
2212 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
2213 IdleTimerParams params = ent.getValue();
2214 pw.print(" timeout="); pw.print(params.timeout);
2215 pw.print(" type="); pw.print(params.type);
2216 pw.print(" networkCount="); pw.println(params.networkCount);
2217 }
2218 }
2219
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002220 pw.print("Firewall enabled: "); pw.println(mFirewallEnabled);
Felipe Leme65be3022016-03-22 14:53:13 -07002221 pw.print("Netd service status: " );
2222 if (mNetdService == null) {
2223 pw.println("disconnected");
2224 } else {
2225 try {
2226 final boolean alive = mNetdService.isAlive();
2227 pw.println(alive ? "alive": "dead");
2228 } catch (RemoteException e) {
2229 pw.println("unreachable");
2230 }
2231 }
2232 }
2233
2234 private void dumpUidRuleOnQuotaLocked(PrintWriter pw, String name, SparseBooleanArray list) {
2235 pw.print("UID bandwith control ");
2236 pw.print(name);
2237 pw.print(" rule: [");
2238 final int size = list.size();
2239 for (int i = 0; i < size; i++) {
2240 pw.print(list.keyAt(i));
2241 if (i < size - 1) pw.print(",");
2242 }
2243 pw.println("]");
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002244 }
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002245
Felipe Leme011b98f2016-02-10 17:28:31 -08002246 private void dumpUidFirewallRule(PrintWriter pw, String name, SparseIntArray rules) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002247 pw.print("UID firewall ");
Felipe Leme011b98f2016-02-10 17:28:31 -08002248 pw.print(name);
2249 pw.print(" rule: [");
2250 final int size = rules.size();
2251 for (int i = 0; i < size; i++) {
2252 pw.print(rules.keyAt(i));
2253 pw.print(":");
2254 pw.print(rules.valueAt(i));
2255 if (i < size - 1) pw.print(",");
2256 }
2257 pw.println("]");
2258 }
2259
Robert Greenwalt568891d2014-04-04 13:38:00 -07002260 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002261 public void createPhysicalNetwork(int netId, int permission) {
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002262 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2263
2264 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002265 mNetdService.networkCreatePhysical(netId, permission);
2266 } catch (RemoteException | ServiceSpecificException e) {
2267 throw new IllegalStateException(e);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002268 }
2269 }
2270
Robert Greenwalt568891d2014-04-04 13:38:00 -07002271 @Override
ckenbed368e2018-12-05 20:32:30 +09002272 public void createVirtualNetwork(int netId, boolean secure) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002273 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2274
2275 try {
ckenbed368e2018-12-05 20:32:30 +09002276 mNetdService.networkCreateVpn(netId, secure);
Luke Huang8a462ec2018-08-24 20:33:16 +08002277 } catch (RemoteException | ServiceSpecificException e) {
2278 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002279 }
2280 }
2281
2282 @Override
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002283 public void removeNetwork(int netId) {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002284 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002285
2286 try {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002287 mNetdService.networkDestroy(netId);
2288 } catch (ServiceSpecificException e) {
2289 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2290 throw e;
2291 } catch (RemoteException e) {
2292 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2293 throw e.rethrowAsRuntimeException();
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002294 }
2295 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002296
2297 @Override
Paul Jensen992f2522014-04-28 10:33:11 -04002298 public void addInterfaceToNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002299 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, netId, iface);
Paul Jensen992f2522014-04-28 10:33:11 -04002300 }
2301
2302 @Override
2303 public void removeInterfaceFromNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002304 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, netId, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002305 }
Paul Jensen992f2522014-04-28 10:33:11 -04002306
Luke Huang8a462ec2018-08-24 20:33:16 +08002307 private void modifyInterfaceInNetwork(boolean add, int netId, String iface) {
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002308 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Paul Jensen992f2522014-04-28 10:33:11 -04002309 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002310 if (add) {
2311 mNetdService.networkAddInterface(netId, iface);
2312 } else {
2313 mNetdService.networkRemoveInterface(netId, iface);
2314 }
2315 } catch (RemoteException | ServiceSpecificException e) {
2316 throw new IllegalStateException(e);
Paul Jensen992f2522014-04-28 10:33:11 -04002317 }
2318 }
2319
2320 @Override
Robert Greenwalt913c8952014-04-07 17:36:35 -07002321 public void addLegacyRouteForNetId(int netId, RouteInfo routeInfo, int uid) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002322 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2323
Sreeram Ramachandrancc91c7b2014-06-03 18:41:43 -07002324 final LinkAddress la = routeInfo.getDestinationLinkAddress();
Luke Huang8a462ec2018-08-24 20:33:16 +08002325 final String ifName = routeInfo.getInterface();
2326 final String dst = la.toString();
2327 final String nextHop;
Robert Greenwalt568891d2014-04-04 13:38:00 -07002328
Luke Huang8a462ec2018-08-24 20:33:16 +08002329 if (routeInfo.hasGateway()) {
2330 nextHop = routeInfo.getGateway().getHostAddress();
2331 } else {
2332 nextHop = "";
2333 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002334 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002335 mNetdService.networkAddLegacyRoute(netId, ifName, dst, nextHop, uid);
2336 } catch (RemoteException | ServiceSpecificException e) {
2337 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002338 }
2339 }
2340
2341 @Override
Sreeram Ramachandranf047f2a2014-04-15 16:04:26 -07002342 public void setDefaultNetId(int netId) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002343 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2344
2345 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002346 mNetdService.networkSetDefault(netId);
2347 } catch (RemoteException | ServiceSpecificException e) {
2348 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002349 }
2350 }
2351
2352 @Override
2353 public void clearDefaultNetId() {
2354 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2355
2356 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002357 mNetdService.networkClearDefault();
2358 } catch (RemoteException | ServiceSpecificException e) {
2359 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002360 }
2361 }
2362
2363 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002364 public void setNetworkPermission(int netId, int permission) {
Paul Jensen487ffe72015-07-24 15:57:11 -04002365 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2366
2367 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002368 mNetdService.networkSetPermissionForNetwork(netId, permission);
2369 } catch (RemoteException | ServiceSpecificException e) {
2370 throw new IllegalStateException(e);
Paul Jensen487ffe72015-07-24 15:57:11 -04002371 }
2372 }
2373
Luke Huang8a462ec2018-08-24 20:33:16 +08002374 private int parsePermission(String permission) {
2375 if (permission.equals("NETWORK")) {
2376 return INetd.PERMISSION_NETWORK;
2377 }
2378 if (permission.equals("SYSTEM")) {
2379 return INetd.PERMISSION_SYSTEM;
2380 }
2381 return INetd.PERMISSION_NONE;
2382 }
Paul Jensen487ffe72015-07-24 15:57:11 -04002383
2384 @Override
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002385 public void setPermission(String permission, int[] uids) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002386 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2387
Luke Huang8a462ec2018-08-24 20:33:16 +08002388 try {
2389 mNetdService.networkSetPermissionForUser(parsePermission(permission), uids);
2390 } catch (RemoteException | ServiceSpecificException e) {
2391 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002392 }
2393 }
2394
2395 @Override
2396 public void clearPermission(int[] uids) {
2397 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2398
Luke Huang8a462ec2018-08-24 20:33:16 +08002399 try {
2400 mNetdService.networkClearPermissionForUser(uids);
2401 } catch (RemoteException | ServiceSpecificException e) {
2402 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002403 }
2404 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002405
2406 @Override
2407 public void allowProtect(int uid) {
2408 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2409
2410 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002411 mNetdService.networkSetProtectAllow(uid);
2412 } catch (RemoteException | ServiceSpecificException e) {
2413 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002414 }
2415 }
2416
2417 @Override
2418 public void denyProtect(int uid) {
2419 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2420
2421 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002422 mNetdService.networkSetProtectDeny(uid);
2423 } catch (RemoteException | ServiceSpecificException e) {
2424 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002425 }
2426 }
2427
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002428 @Override
2429 public void addInterfaceToLocalNetwork(String iface, List<RouteInfo> routes) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002430 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002431
2432 for (RouteInfo route : routes) {
2433 if (!route.isDefaultRoute()) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002434 modifyRoute(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID, route);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002435 }
2436 }
2437 }
2438
2439 @Override
2440 public void removeInterfaceFromLocalNetwork(String iface) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002441 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, INetd.LOCAL_NET_ID, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002442 }
Erik Kline6599ee82016-07-17 21:28:39 +09002443
2444 @Override
2445 public int removeRoutesFromLocalNetwork(List<RouteInfo> routes) {
2446 int failures = 0;
2447
2448 for (RouteInfo route : routes) {
2449 try {
Luke Huang706d7ab2018-10-16 15:42:15 +08002450 modifyRoute(MODIFY_OPERATION_REMOVE, INetd.LOCAL_NET_ID, route);
Erik Kline6599ee82016-07-17 21:28:39 +09002451 } catch (IllegalStateException e) {
2452 failures++;
2453 }
2454 }
2455
2456 return failures;
2457 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002458
Sudheer Shankab8f23162017-08-04 13:30:10 -07002459 @Override
2460 public boolean isNetworkRestricted(int uid) {
2461 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2462 return isNetworkRestrictedInternal(uid);
2463 }
2464
2465 private boolean isNetworkRestrictedInternal(int uid) {
2466 synchronized (mRulesLock) {
2467 if (getFirewallChainState(FIREWALL_CHAIN_STANDBY)
2468 && mUidFirewallStandbyRules.get(uid) == FIREWALL_RULE_DENY) {
2469 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of app standby mode");
2470 return true;
2471 }
2472 if (getFirewallChainState(FIREWALL_CHAIN_DOZABLE)
2473 && mUidFirewallDozableRules.get(uid) != FIREWALL_RULE_ALLOW) {
2474 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of device idle mode");
2475 return true;
2476 }
2477 if (getFirewallChainState(FIREWALL_CHAIN_POWERSAVE)
2478 && mUidFirewallPowerSaveRules.get(uid) != FIREWALL_RULE_ALLOW) {
2479 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of power saver mode");
2480 return true;
2481 }
2482 if (mUidRejectOnMetered.get(uid)) {
2483 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of no metered data"
2484 + " in the background");
2485 return true;
2486 }
2487 if (mDataSaverMode && !mUidAllowOnMetered.get(uid)) {
2488 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of data saver mode");
2489 return true;
2490 }
2491 return false;
2492 }
2493 }
2494
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002495 private void setFirewallChainState(int chain, boolean state) {
2496 synchronized (mRulesLock) {
2497 mFirewallChainStates.put(chain, state);
2498 }
2499 }
2500
2501 private boolean getFirewallChainState(int chain) {
2502 synchronized (mRulesLock) {
2503 return mFirewallChainStates.get(chain);
2504 }
2505 }
2506
2507 @VisibleForTesting
2508 class LocalService extends NetworkManagementInternal {
2509 @Override
2510 public boolean isNetworkRestrictedForUid(int uid) {
Sudheer Shankab8f23162017-08-04 13:30:10 -07002511 return isNetworkRestrictedInternal(uid);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002512 }
2513 }
2514
2515 @VisibleForTesting
2516 Injector getInjector() {
2517 return new Injector();
2518 }
2519
2520 @VisibleForTesting
2521 class Injector {
2522 void setDataSaverMode(boolean dataSaverMode) {
2523 mDataSaverMode = dataSaverMode;
2524 }
2525
2526 void setFirewallChainState(int chain, boolean state) {
2527 NetworkManagementService.this.setFirewallChainState(chain, state);
2528 }
2529
2530 void setFirewallRule(int chain, int uid, int rule) {
2531 synchronized (mRulesLock) {
2532 getUidFirewallRulesLR(chain).put(uid, rule);
2533 }
2534 }
2535
2536 void setUidOnMeteredNetworkList(boolean blacklist, int uid, boolean enable) {
2537 synchronized (mRulesLock) {
2538 if (blacklist) {
2539 mUidRejectOnMetered.put(uid, enable);
2540 } else {
2541 mUidAllowOnMetered.put(uid, enable);
2542 }
2543 }
2544 }
2545
2546 void reset() {
2547 synchronized (mRulesLock) {
2548 setDataSaverMode(false);
2549 final int[] chains = {
2550 FIREWALL_CHAIN_DOZABLE,
2551 FIREWALL_CHAIN_STANDBY,
2552 FIREWALL_CHAIN_POWERSAVE
2553 };
2554 for (int chain : chains) {
2555 setFirewallChainState(chain, false);
2556 getUidFirewallRulesLR(chain).clear();
2557 }
2558 mUidAllowOnMetered.clear();
2559 mUidRejectOnMetered.clear();
2560 }
2561 }
2562 }
San Mehat873f2142010-01-14 10:25:07 -08002563}