blob: dc394d0ad48271b0a28447c52b51c33567b24032 [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;
Remi NGUYEN VANf9a8c2e2019-02-13 18:28:35 +090023import static android.net.INetd.FIREWALL_BLACKLIST;
24import static android.net.INetd.FIREWALL_CHAIN_DOZABLE;
25import static android.net.INetd.FIREWALL_CHAIN_NONE;
26import static android.net.INetd.FIREWALL_CHAIN_POWERSAVE;
27import static android.net.INetd.FIREWALL_CHAIN_STANDBY;
28import static android.net.INetd.FIREWALL_RULE_ALLOW;
29import static android.net.INetd.FIREWALL_RULE_DENY;
30import static android.net.INetd.FIREWALL_WHITELIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070031import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080032import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070033import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_STANDBY;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070034import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
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
Jeff Sharkeyba2896e2011-11-30 18:13:54 -080042import static com.android.server.NetworkManagementService.NetdResponseCode.TtyListResult;
Jeff Sharkeya63ba592011-07-19 23:47:12 -070043import static com.android.server.NetworkManagementSocketTagger.PROP_QTAGUID_ENABLED;
Erik Klineb2cfdfb2017-01-18 20:54:14 +090044
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070045import android.annotation.NonNull;
Sudheer Shankadc589ac2016-11-10 15:30:17 -080046import android.app.ActivityManager;
San Mehat873f2142010-01-14 10:25:07 -080047import android.content.Context;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080048import android.net.ConnectivityManager;
Lorenzo Colitti58967ba2016-02-02 17:21:21 +090049import android.net.INetd;
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +090050import android.net.INetdUnsolicitedEventListener;
San Mehat4d02d002010-01-22 16:07:46 -080051import android.net.INetworkManagementEventObserver;
Lorenzo Colitti07f13042017-07-10 19:06:57 +090052import android.net.ITetheringStatsProvider;
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +090053import android.net.InetAddresses;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070054import android.net.InterfaceConfiguration;
Luke Huang14f75442018-08-15 19:22:54 +080055import android.net.InterfaceConfigurationParcel;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +090056import android.net.IpPrefix;
Robert Greenwalted126402011-01-28 15:34:55 -080057import android.net.LinkAddress;
Lorenzo Colittib57edc52014-08-22 17:10:50 -070058import android.net.Network;
Amith Yamasani15e472352015-04-24 19:06:07 -070059import android.net.NetworkPolicyManager;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070060import android.net.NetworkStats;
Robert Greenwalted126402011-01-28 15:34:55 -080061import android.net.NetworkUtils;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070062import android.net.RouteInfo;
Lorenzo Colitti9307ca22019-01-12 01:54:23 +090063import android.net.TetherStatsParcel;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040064import android.net.UidRange;
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +090065import android.net.util.NetdService;
Dianne Hackborn91268cf2013-06-13 19:06:50 -070066import android.os.BatteryStats;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070067import android.os.Binder;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -070068import android.os.Handler;
Lorenzo Colittia0868002017-07-11 02:29:28 +090069import android.os.IBinder;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080070import android.os.INetworkActivityListener;
San Mehat873f2142010-01-14 10:25:07 -080071import android.os.INetworkManagementService;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080072import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070073import android.os.Process;
Jeff Sharkey3df273e2011-12-15 15:47:12 -080074import android.os.RemoteCallbackList;
75import android.os.RemoteException;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070076import android.os.ServiceManager;
Lorenzo Colitti4cb42402016-04-24 12:52:00 +090077import android.os.ServiceSpecificException;
Jeff Sharkey605eb792014-11-04 13:34:06 -080078import android.os.StrictMode;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070079import android.os.SystemClock;
Marco Nelissen62dbb222010-02-18 10:56:30 -080080import android.os.SystemProperties;
Felipe Leme29e72ea2016-09-08 13:26:55 -070081import android.os.Trace;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070082import android.telephony.DataConnectionRealTimeInfo;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080083import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080084import android.util.Slog;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070085import android.util.SparseBooleanArray;
Jeff Sharkey605eb792014-11-04 13:34:06 -080086import android.util.SparseIntArray;
Bookatz0b028b12018-05-31 16:51:17 -070087import android.util.StatsLog;
San Mehat873f2142010-01-14 10:25:07 -080088
Jeff Sharkey605eb792014-11-04 13:34:06 -080089import com.android.internal.annotations.GuardedBy;
Sudheer Shanka62f5c172017-03-17 16:25:55 -070090import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070091import com.android.internal.app.IBatteryStats;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070092import com.android.internal.net.NetworkStatsFactory;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060093import com.android.internal.util.DumpUtils;
Jeff Sharkey605eb792014-11-04 13:34:06 -080094import com.android.internal.util.HexDump;
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -070095import com.android.internal.util.Preconditions;
Lorenzo Colitti9307ca22019-01-12 01:54:23 +090096
Jeff Sharkeyb24a7852012-05-01 15:19:37 -070097import com.google.android.collect.Maps;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070098
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070099import java.io.BufferedReader;
100import java.io.DataInputStream;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700101import java.io.FileDescriptor;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700102import java.io.FileInputStream;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700103import java.io.IOException;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700104import java.io.InputStreamReader;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700105import java.io.PrintWriter;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700106import java.net.InetAddress;
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700107import java.net.InterfaceAddress;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700108import java.util.ArrayList;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400109import java.util.Arrays;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700110import java.util.HashMap;
jiaguo1da35f72014-01-09 16:39:59 +0800111import java.util.List;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700112import java.util.Map;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700113import java.util.concurrent.CountDownLatch;
San Mehat873f2142010-01-14 10:25:07 -0800114
115/**
116 * @hide
117 */
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700118public class NetworkManagementService extends INetworkManagementService.Stub
119 implements Watchdog.Monitor {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900120
121 /**
122 * Helper class that encapsulates NetworkManagementService dependencies and makes them
123 * easier to mock in unit tests.
124 */
125 static class SystemServices {
126 public IBinder getService(String name) {
127 return ServiceManager.getService(name);
128 }
129 public void registerLocalService(NetworkManagementInternal nmi) {
130 LocalServices.addService(NetworkManagementInternal.class, nmi);
131 }
132 public INetd getNetd() {
133 return NetdService.get();
134 }
135 }
136
Amith Yamasani15e472352015-04-24 19:06:07 -0700137 private static final String TAG = "NetworkManagement";
138 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Kenny Root305bcbf2010-09-03 07:56:38 -0700139 private static final String NETD_TAG = "NetdConnector";
Lorenzo Colittia0868002017-07-11 02:29:28 +0900140 static final String NETD_SERVICE_NAME = "netd";
Kenny Root305bcbf2010-09-03 07:56:38 -0700141
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400142 private static final int MAX_UID_RANGES_PER_COMMAND = 10;
143
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700144 /**
145 * Name representing {@link #setGlobalAlert(long)} limit when delivered to
146 * {@link INetworkManagementEventObserver#limitReached(String, String)}.
147 */
148 public static final String LIMIT_GLOBAL_ALERT = "globalAlert";
149
Andrew Scull45f533c2017-05-19 15:37:20 +0100150 static class NetdResponseCode {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -0700151 /* Keep in sync with system/netd/server/ResponseCode.h */
San Mehat873f2142010-01-14 10:25:07 -0800152 public static final int InterfaceListResult = 110;
153 public static final int TetherInterfaceListResult = 111;
154 public static final int TetherDnsFwdTgtListResult = 112;
San Mehat72759df2010-01-19 13:50:37 -0800155 public static final int TtyListResult = 113;
Jeff Sharkeye4984be2013-09-10 21:03:27 -0700156 public static final int TetheringStatsListResult = 114;
San Mehat873f2142010-01-14 10:25:07 -0800157
158 public static final int TetherStatusResult = 210;
159 public static final int IpFwdStatusResult = 211;
San Mehated4fc8a2010-01-22 12:28:36 -0800160 public static final int InterfaceGetCfgResult = 213;
Robert Greenwalte3253922010-02-18 09:23:25 -0800161 public static final int SoftapStatusResult = 214;
San Mehat91cac642010-03-31 14:31:36 -0700162 public static final int InterfaceRxCounterResult = 216;
163 public static final int InterfaceTxCounterResult = 217;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700164 public static final int QuotaCounterResult = 220;
165 public static final int TetheringStatsResult = 221;
Selim Gurun84c00c62012-02-27 15:42:38 -0800166 public static final int DnsProxyQueryResult = 222;
Lorenzo Colitti79751842013-02-28 16:16:03 +0900167 public static final int ClatdStatusResult = 223;
Robert Greenwalte3253922010-02-18 09:23:25 -0800168
169 public static final int InterfaceChange = 600;
JP Abgrall12b933d2011-07-14 18:09:22 -0700170 public static final int BandwidthControl = 601;
Haoyu Bai6b7358d2012-07-17 16:36:50 -0700171 public static final int InterfaceClassActivity = 613;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900172 public static final int InterfaceAddressChange = 614;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900173 public static final int InterfaceDnsServerInfo = 615;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900174 public static final int RouteChange = 616;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800175 public static final int StrictCleartext = 617;
San Mehat873f2142010-01-14 10:25:07 -0800176 }
177
Rebecca Silbersteine2ec94f2016-03-24 13:29:00 -0700178 /**
179 * String indicating a softap command.
180 */
181 static final String SOFT_AP_COMMAND = "softap";
182
183 /**
184 * String passed back to netd connector indicating softap command success.
185 */
186 static final String SOFT_AP_COMMAND_SUCCESS = "Ok";
187
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700188 static final int DAEMON_MSG_MOBILE_CONN_REAL_TIME_INFO = 1;
189
Luke Huang8a462ec2018-08-24 20:33:16 +0800190 static final boolean MODIFY_OPERATION_ADD = true;
191 static final boolean MODIFY_OPERATION_REMOVE = false;
192
San Mehat873f2142010-01-14 10:25:07 -0800193 /**
194 * Binder context for this service
195 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700196 private final Context mContext;
San Mehat873f2142010-01-14 10:25:07 -0800197
198 /**
199 * connector object for communicating with netd
200 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700201 private final NativeDaemonConnector mConnector;
San Mehat873f2142010-01-14 10:25:07 -0800202
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700203 private final Handler mFgHandler;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700204 private final Handler mDaemonHandler;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700205
Lorenzo Colittia0868002017-07-11 02:29:28 +0900206 private final SystemServices mServices;
207
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900208 private INetd mNetdService;
209
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900210 private final NetdUnsolicitedEventListener mNetdUnsolicitedEventListener;
Luke Huangd290dd52018-09-04 17:08:18 +0800211
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800212 private IBatteryStats mBatteryStats;
213
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700214 private final Thread mThread;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700215 private CountDownLatch mConnectedSignal = new CountDownLatch(1);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700216
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900217 private final RemoteCallbackList<INetworkManagementEventObserver> mObservers =
218 new RemoteCallbackList<>();
219
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700220 private final NetworkStatsFactory mStatsFactory = new NetworkStatsFactory();
221
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900222 @GuardedBy("mTetheringStatsProviders")
223 private final HashMap<ITetheringStatsProvider, String>
224 mTetheringStatsProviders = Maps.newHashMap();
225
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700226 /**
227 * If both locks need to be held, then they should be obtained in the order:
228 * first {@link #mQuotaLock} and then {@link #mRulesLock}.
229 */
Andrew Scull45f533c2017-05-19 15:37:20 +0100230 private final Object mQuotaLock = new Object();
Andrew Scull519291f2017-05-23 13:11:03 +0100231 private final Object mRulesLock = new Object();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800232
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700233 /** Set of interfaces with active quotas. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800234 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700235 private HashMap<String, Long> mActiveQuotas = Maps.newHashMap();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700236 /** Set of interfaces with active alerts. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800237 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700238 private HashMap<String, Long> mActiveAlerts = Maps.newHashMap();
Felipe Leme65be3022016-03-22 14:53:13 -0700239 /** Set of UIDs blacklisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700240 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700241 private SparseBooleanArray mUidRejectOnMetered = new SparseBooleanArray();
242 /** Set of UIDs whitelisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700243 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700244 private SparseBooleanArray mUidAllowOnMetered = new SparseBooleanArray();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800245 /** Set of UIDs with cleartext penalties. */
246 @GuardedBy("mQuotaLock")
247 private SparseIntArray mUidCleartextPolicy = new SparseIntArray();
Amith Yamasani15e472352015-04-24 19:06:07 -0700248 /** Set of UIDs that are to be blocked/allowed by firewall controller. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700249 @GuardedBy("mRulesLock")
Amith Yamasani15e472352015-04-24 19:06:07 -0700250 private SparseIntArray mUidFirewallRules = new SparseIntArray();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700251 /**
252 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
253 * to application idles.
254 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700255 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700256 private SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
257 /**
258 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
259 * to device idles.
260 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700261 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700262 private SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800263 /**
264 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
265 * to device on power-save mode.
266 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700267 @GuardedBy("mRulesLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800268 private SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700269 /** Set of states for the child firewall chains. True if the chain is active. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700270 @GuardedBy("mRulesLock")
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700271 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700272
Felipe Leme65be3022016-03-22 14:53:13 -0700273 @GuardedBy("mQuotaLock")
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700274 private volatile boolean mDataSaverMode;
Felipe Leme65be3022016-03-22 14:53:13 -0700275
Andrew Scull45f533c2017-05-19 15:37:20 +0100276 private final Object mIdleTimerLock = new Object();
Haoyu Bai04124232012-06-28 15:26:19 -0700277 /** Set of interfaces with active idle timers. */
278 private static class IdleTimerParams {
279 public final int timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800280 public final int type;
Haoyu Bai04124232012-06-28 15:26:19 -0700281 public int networkCount;
282
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800283 IdleTimerParams(int timeout, int type) {
Haoyu Bai04124232012-06-28 15:26:19 -0700284 this.timeout = timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800285 this.type = type;
Haoyu Bai04124232012-06-28 15:26:19 -0700286 this.networkCount = 1;
287 }
288 }
289 private HashMap<String, IdleTimerParams> mActiveIdleTimers = Maps.newHashMap();
290
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700291 private volatile boolean mFirewallEnabled;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800292 private volatile boolean mStrictEnabled;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700293
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700294 private boolean mMobileActivityFromRadio = false;
295 private int mLastPowerStateFromRadio = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Adam Lesinskie08af192015-03-25 16:42:59 -0700296 private int mLastPowerStateFromWifi = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700297
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800298 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700299 new RemoteCallbackList<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800300 private boolean mNetworkActive;
301
San Mehat873f2142010-01-14 10:25:07 -0800302 /**
303 * Constructs a new NetworkManagementService instance
304 *
305 * @param context Binder context for this service
306 */
Lorenzo Colittia0868002017-07-11 02:29:28 +0900307 private NetworkManagementService(
308 Context context, String socket, SystemServices services) {
San Mehat873f2142010-01-14 10:25:07 -0800309 mContext = context;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900310 mServices = services;
San Mehat4d02d002010-01-22 16:07:46 -0800311
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700312 // make sure this is on the same looper as our NativeDaemonConnector for sync purposes
313 mFgHandler = new Handler(FgThread.get().getLooper());
314
Dianne Hackborn4590e522014-03-24 13:36:46 -0700315 // Don't need this wake lock, since we now have a time stamp for when
316 // the network actually went inactive. (It might be nice to still do this,
317 // but I don't want to do it through the power manager because that pollutes the
318 // battery stats history with pointless noise.)
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700319 //PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
Dianne Hackborn4590e522014-03-24 13:36:46 -0700320 PowerManager.WakeLock wl = null; //pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NETD_TAG);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800321
San Mehat873f2142010-01-14 10:25:07 -0800322 mConnector = new NativeDaemonConnector(
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700323 new NetdCallbackReceiver(), socket, 10, NETD_TAG, 160, wl,
324 FgThread.get().getLooper());
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700325 mThread = new Thread(mConnector, NETD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700326
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700327 mDaemonHandler = new Handler(FgThread.get().getLooper());
Wink Saville67e07892014-06-18 16:43:14 -0700328
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900329 mNetdUnsolicitedEventListener = new NetdUnsolicitedEventListener();
330
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700331 // Add ourself to the Watchdog monitors.
332 Watchdog.getInstance().addMonitor(this);
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700333
Lorenzo Colittia0868002017-07-11 02:29:28 +0900334 mServices.registerLocalService(new LocalService());
Lorenzo Colitti8228eb32017-07-19 06:17:33 +0900335
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900336 synchronized (mTetheringStatsProviders) {
337 mTetheringStatsProviders.put(new NetdTetheringStatsProvider(), "netd");
338 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700339 }
340
341 @VisibleForTesting
342 NetworkManagementService() {
343 mConnector = null;
344 mContext = null;
345 mDaemonHandler = null;
346 mFgHandler = null;
347 mThread = null;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900348 mServices = null;
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900349 mNetdUnsolicitedEventListener = 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) {
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900397 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
398 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) {
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900403 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
404 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
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900412 private void invokeForAllObservers(NetworkManagementEventCallback eventCallback) {
413 final int length = mObservers.beginBroadcast();
414 try {
415 for (int i = 0; i < length; i++) {
416 try {
417 eventCallback.sendCallback(mObservers.getBroadcastItem(i));
418 } catch (RemoteException | RuntimeException e) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700419 }
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900420 }
421 } finally {
422 mObservers.finishBroadcast();
423 }
424 }
425
426 /**
427 * 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 /**
434 * Notify our observers of an interface link state change
435 * (typically, an Ethernet cable has been plugged-in or unplugged).
436 */
437 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
438 invokeForAllObservers(o -> o.interfaceLinkStateChanged(iface, up));
439 }
440
441 /**
442 * Notify our observers of an interface addition.
443 */
444 private void notifyInterfaceAdded(String iface) {
445 invokeForAllObservers(o -> o.interfaceAdded(iface));
446 }
447
448 /**
449 * Notify our observers of an interface removal.
450 */
451 private void notifyInterfaceRemoved(String iface) {
452 // netd already clears out quota and alerts for removed ifaces; update
453 // our sanity-checking state.
454 mActiveAlerts.remove(iface);
455 mActiveQuotas.remove(iface);
456 invokeForAllObservers(o -> o.interfaceRemoved(iface));
457 }
458
459 /**
460 * Notify our observers of a limit reached.
461 */
462 private void notifyLimitReached(String limitName, String iface) {
463 invokeForAllObservers(o -> o.limitReached(limitName, iface));
464 }
465
466 /**
467 * Notify our observers of a change in the data activity state of the interface
468 */
469 private void notifyInterfaceClassActivity(int type, boolean isActive, long tsNanos,
470 int uid, boolean fromRadio) {
471 final boolean isMobile = ConnectivityManager.isNetworkTypeMobile(type);
472 int powerState = isActive
473 ? DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH
474 : DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
475 if (isMobile) {
476 if (!fromRadio) {
477 if (mMobileActivityFromRadio) {
478 // If this call is not coming from a report from the radio itself, but we
479 // have previously received reports from the radio, then we will take the
480 // power state to just be whatever the radio last reported.
481 powerState = mLastPowerStateFromRadio;
482 }
483 } else {
484 mMobileActivityFromRadio = true;
485 }
486 if (mLastPowerStateFromRadio != powerState) {
487 mLastPowerStateFromRadio = powerState;
488 try {
489 getBatteryStats().noteMobileRadioPowerState(powerState, tsNanos, uid);
490 } catch (RemoteException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700491 }
Bookatz0b028b12018-05-31 16:51:17 -0700492 StatsLog.write_non_chained(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, null,
493 powerState);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700494 }
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900495 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700496
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900497 if (ConnectivityManager.isNetworkTypeWifi(type)) {
498 if (mLastPowerStateFromWifi != powerState) {
499 mLastPowerStateFromWifi = powerState;
500 try {
501 getBatteryStats().noteWifiRadioPowerState(powerState, tsNanos, uid);
502 } catch (RemoteException e) {
Adam Lesinskie08af192015-03-25 16:42:59 -0700503 }
Bookatz0b028b12018-05-31 16:51:17 -0700504 StatsLog.write_non_chained(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, null,
505 powerState);
Adam Lesinskie08af192015-03-25 16:42:59 -0700506 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800507 }
Lorenzo Colittid8bc8292019-01-24 13:28:50 +0900508
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900509 if (!isMobile || fromRadio || !mMobileActivityFromRadio) {
510 // Report the change in data activity. We don't do this if this is a change
511 // on the mobile network, that is not coming from the radio itself, and we
512 // have previously seen change reports from the radio. In that case only
513 // the radio is the authority for the current state.
514 final boolean active = isActive;
515 invokeForAllObservers(o -> o.interfaceClassDataActivityChanged(
516 Integer.toString(type), active, tsNanos));
Lorenzo Colittid8bc8292019-01-24 13:28:50 +0900517 }
518
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900519 boolean report = false;
520 synchronized (mIdleTimerLock) {
521 if (mActiveIdleTimers.isEmpty()) {
522 // If there are no idle timers, we are not monitoring activity, so we
523 // are always considered active.
524 isActive = true;
525 }
526 if (mNetworkActive != isActive) {
527 mNetworkActive = isActive;
528 report = isActive;
529 }
530 }
531 if (report) {
532 reportNetworkActive();
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800533 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700534 }
535
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900536 @Override
537 public void registerTetheringStatsProvider(ITetheringStatsProvider provider, String name) {
538 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
539 Preconditions.checkNotNull(provider);
540 synchronized(mTetheringStatsProviders) {
541 mTetheringStatsProviders.put(provider, name);
542 }
543 }
544
545 @Override
546 public void unregisterTetheringStatsProvider(ITetheringStatsProvider provider) {
547 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
548 synchronized(mTetheringStatsProviders) {
549 mTetheringStatsProviders.remove(provider);
550 }
551 }
552
Lorenzo Colitti9f0baa92017-08-15 19:25:51 +0900553 @Override
554 public void tetherLimitReached(ITetheringStatsProvider provider) {
555 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
556 synchronized(mTetheringStatsProviders) {
557 if (!mTetheringStatsProviders.containsKey(provider)) {
558 return;
559 }
560 // No current code examines the interface parameter in a global alert. Just pass null.
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900561 mDaemonHandler.post(() -> notifyLimitReached(LIMIT_GLOBAL_ALERT, null));
Lorenzo Colitti9f0baa92017-08-15 19:25:51 +0900562 }
563 }
564
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900565 // Sync the state of the given chain with the native daemon.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700566 private void syncFirewallChainLocked(int chain, String name) {
567 SparseIntArray rules;
568 synchronized (mRulesLock) {
569 final SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900570 // Make a copy of the current rules, and then clear them. This is because
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700571 // setFirewallUidRuleInternal only pushes down rules to the native daemon if they
572 // are different from the current rules stored in the mUidFirewall*Rules array for
573 // the specified chain. If we don't clear the rules, setFirewallUidRuleInternal
574 // will do nothing.
575 rules = uidFirewallRules.clone();
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900576 uidFirewallRules.clear();
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700577 }
578 if (rules.size() > 0) {
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900579 // Now push the rules. setFirewallUidRuleInternal will push each of these down to the
580 // native daemon, and also add them to the mUidFirewall*Rules array for the specified
581 // chain.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700582 if (DBG) Slog.d(TAG, "Pushing " + rules.size() + " active firewall "
583 + name + "UID rules");
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900584 for (int i = 0; i < rules.size(); i++) {
Felipe Lemea701cad2016-05-12 09:58:14 -0700585 setFirewallUidRuleLocked(chain, rules.keyAt(i), rules.valueAt(i));
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900586 }
587 }
588 }
589
bohu07cc3bb2016-05-03 15:58:01 -0700590 private void connectNativeNetdService() {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900591 mNetdService = mServices.getNetd();
Luke Huangd290dd52018-09-04 17:08:18 +0800592 try {
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900593 mNetdService.registerUnsolicitedEventListener(mNetdUnsolicitedEventListener);
594 if (DBG) Slog.d(TAG, "Register unsolicited event listener");
Luke Huangd290dd52018-09-04 17:08:18 +0800595 } catch (RemoteException | ServiceSpecificException e) {
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900596 Slog.e(TAG, "Failed to set Netd unsolicited event listener " + e);
Luke Huangd290dd52018-09-04 17:08:18 +0800597 }
bohu07cc3bb2016-05-03 15:58:01 -0700598 }
599
600 /**
601 * Prepare native daemon once connected, enabling modules and pushing any
602 * existing in-memory rules.
603 */
604 private void prepareNativeDaemon() {
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900605
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700606 // push any existing quota or UID rules
607 synchronized (mQuotaLock) {
Felipe Leme65be3022016-03-22 14:53:13 -0700608
Luke Huang56a03a02018-09-07 12:02:16 +0800609 // Netd unconditionally enable bandwidth control
610 SystemProperties.set(PROP_QTAGUID_ENABLED, "1");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900611
Luke Huang473eb872018-07-26 17:33:14 +0800612 mStrictEnabled = true;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900613
Felipe Leme65be3022016-03-22 14:53:13 -0700614 setDataSaverModeEnabled(mDataSaverMode);
615
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700616 int size = mActiveQuotas.size();
617 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800618 if (DBG) Slog.d(TAG, "Pushing " + size + " active quota rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700619 final HashMap<String, Long> activeQuotas = mActiveQuotas;
620 mActiveQuotas = Maps.newHashMap();
621 for (Map.Entry<String, Long> entry : activeQuotas.entrySet()) {
622 setInterfaceQuota(entry.getKey(), entry.getValue());
623 }
624 }
625
626 size = mActiveAlerts.size();
627 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800628 if (DBG) Slog.d(TAG, "Pushing " + size + " active alert rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700629 final HashMap<String, Long> activeAlerts = mActiveAlerts;
630 mActiveAlerts = Maps.newHashMap();
631 for (Map.Entry<String, Long> entry : activeAlerts.entrySet()) {
632 setInterfaceAlert(entry.getKey(), entry.getValue());
633 }
634 }
635
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700636 SparseBooleanArray uidRejectOnQuota = null;
637 SparseBooleanArray uidAcceptOnQuota = null;
638 synchronized (mRulesLock) {
639 size = mUidRejectOnMetered.size();
640 if (size > 0) {
641 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered blacklist rules");
642 uidRejectOnQuota = mUidRejectOnMetered;
643 mUidRejectOnMetered = new SparseBooleanArray();
644 }
645
646 size = mUidAllowOnMetered.size();
647 if (size > 0) {
648 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered whitelist rules");
649 uidAcceptOnQuota = mUidAllowOnMetered;
650 mUidAllowOnMetered = new SparseBooleanArray();
651 }
652 }
653 if (uidRejectOnQuota != null) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700654 for (int i = 0; i < uidRejectOnQuota.size(); i++) {
Felipe Leme65be3022016-03-22 14:53:13 -0700655 setUidMeteredNetworkBlacklist(uidRejectOnQuota.keyAt(i),
656 uidRejectOnQuota.valueAt(i));
657 }
658 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700659 if (uidAcceptOnQuota != null) {
Felipe Leme65be3022016-03-22 14:53:13 -0700660 for (int i = 0; i < uidAcceptOnQuota.size(); i++) {
661 setUidMeteredNetworkWhitelist(uidAcceptOnQuota.keyAt(i),
662 uidAcceptOnQuota.valueAt(i));
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700663 }
664 }
Jeff Sharkey605eb792014-11-04 13:34:06 -0800665
666 size = mUidCleartextPolicy.size();
667 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800668 if (DBG) Slog.d(TAG, "Pushing " + size + " active UID cleartext policies");
Jeff Sharkey605eb792014-11-04 13:34:06 -0800669 final SparseIntArray local = mUidCleartextPolicy;
670 mUidCleartextPolicy = new SparseIntArray();
671 for (int i = 0; i < local.size(); i++) {
672 setUidCleartextNetworkPolicy(local.keyAt(i), local.valueAt(i));
673 }
674 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700675
Robin Leec3736bc2017-03-10 16:19:54 +0000676 setFirewallEnabled(mFirewallEnabled);
Amith Yamasani15e472352015-04-24 19:06:07 -0700677
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700678 syncFirewallChainLocked(FIREWALL_CHAIN_NONE, "");
679 syncFirewallChainLocked(FIREWALL_CHAIN_STANDBY, "standby ");
680 syncFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, "dozable ");
681 syncFirewallChainLocked(FIREWALL_CHAIN_POWERSAVE, "powersave ");
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700682
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700683 final int[] chains =
684 {FIREWALL_CHAIN_STANDBY, FIREWALL_CHAIN_DOZABLE, FIREWALL_CHAIN_POWERSAVE};
685 for (int chain : chains) {
686 if (getFirewallChainState(chain)) {
687 setFirewallChainEnabled(chain, true);
688 }
Felipe Leme011b98f2016-02-10 17:28:31 -0800689 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700690 }
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900691
Luke Huang56a03a02018-09-07 12:02:16 +0800692
693 try {
694 getBatteryStats().noteNetworkStatsEnabled();
695 } catch (RemoteException e) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900696 }
697
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700698 }
San Mehat4d02d002010-01-22 16:07:46 -0800699
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900700 /**
701 * Notify our observers of a new or updated interface address.
702 */
703 private void notifyAddressUpdated(String iface, LinkAddress address) {
704 invokeForAllObservers(o -> o.addressUpdated(iface, address));
705 }
706
707 /**
708 * Notify our observers of a deleted interface address.
709 */
710 private void notifyAddressRemoved(String iface, LinkAddress address) {
711 invokeForAllObservers(o -> o.addressRemoved(iface, address));
712 }
713
714 /**
715 * Notify our observers of DNS server information received.
716 */
717 private void notifyInterfaceDnsServerInfo(String iface, long lifetime, String[] addresses) {
718 invokeForAllObservers(o -> o.interfaceDnsServerInfo(iface, lifetime, addresses));
719 }
720
721 /**
722 * Notify our observers of a route change.
723 */
724 private void notifyRouteChange(boolean updated, RouteInfo route) {
725 if (updated) {
726 invokeForAllObservers(o -> o.routeUpdated(route));
727 } else {
728 invokeForAllObservers(o -> o.routeRemoved(route));
729 }
730 }
731
732 private class NetdUnsolicitedEventListener extends INetdUnsolicitedEventListener.Stub {
733 @Override
734 public void onInterfaceClassActivityChanged(boolean isActive,
735 int label, long timestamp, int uid) throws RemoteException {
736 final long timestampNanos;
737 if (timestamp <= 0) {
738 timestampNanos = SystemClock.elapsedRealtimeNanos();
739 } else {
740 timestampNanos = timestamp;
741 }
742 mDaemonHandler.post(() ->
743 notifyInterfaceClassActivity(label, isActive, timestampNanos, uid, false));
744 }
745
746 @Override
747 public void onQuotaLimitReached(String alertName, String ifName)
748 throws RemoteException {
749 mDaemonHandler.post(() -> notifyLimitReached(alertName, ifName));
750 }
751
752 @Override
753 public void onInterfaceDnsServerInfo(String ifName,
754 long lifetime, String[] servers) throws RemoteException {
755 mDaemonHandler.post(() -> notifyInterfaceDnsServerInfo(ifName, lifetime, servers));
756 }
757
758 @Override
759 public void onInterfaceAddressUpdated(String addr,
760 String ifName, int flags, int scope) throws RemoteException {
761 final LinkAddress address = new LinkAddress(addr, flags, scope);
762 mDaemonHandler.post(() -> notifyAddressUpdated(ifName, address));
763 }
764
765 @Override
766 public void onInterfaceAddressRemoved(String addr,
767 String ifName, int flags, int scope) throws RemoteException {
768 final LinkAddress address = new LinkAddress(addr, flags, scope);
769 mDaemonHandler.post(() -> notifyAddressRemoved(ifName, address));
770 }
771
772 @Override
773 public void onInterfaceAdded(String ifName) throws RemoteException {
774 mDaemonHandler.post(() -> notifyInterfaceAdded(ifName));
775 }
776
777 @Override
778 public void onInterfaceRemoved(String ifName) throws RemoteException {
779 mDaemonHandler.post(() -> notifyInterfaceRemoved(ifName));
780 }
781
782 @Override
783 public void onInterfaceChanged(String ifName, boolean up)
784 throws RemoteException {
785 mDaemonHandler.post(() -> notifyInterfaceStatusChanged(ifName, up));
786 }
787
788 @Override
789 public void onInterfaceLinkStateChanged(String ifName, boolean up)
790 throws RemoteException {
791 mDaemonHandler.post(() -> notifyInterfaceLinkStateChanged(ifName, up));
792 }
793
794 @Override
795 public void onRouteChanged(boolean updated,
796 String route, String gateway, String ifName) throws RemoteException {
797 final RouteInfo processRoute = new RouteInfo(new IpPrefix(route),
798 ("".equals(gateway)) ? null : InetAddresses.parseNumericAddress(gateway),
799 ifName);
800 mDaemonHandler.post(() -> notifyRouteChange(updated, processRoute));
801 }
802
803 @Override
804 public void onStrictCleartextDetected(int uid, String hex) throws RemoteException {
805 // Don't need to post to mDaemonHandler because the only thing
806 // that notifyCleartextNetwork does is post to a handler
807 ActivityManager.getService().notifyCleartextNetwork(uid,
808 HexDump.hexStringToByteArray(hex));
809 }
810 }
811
San Mehat873f2142010-01-14 10:25:07 -0800812 //
813 // Netd Callback handling
814 //
815
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700816 private class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
817 @Override
San Mehat873f2142010-01-14 10:25:07 -0800818 public void onDaemonConnected() {
Felipe Leme65be3022016-03-22 14:53:13 -0700819 Slog.i(TAG, "onDaemonConnected()");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700820 // event is dispatched from internal NDC thread, so we prepare the
821 // daemon back on main thread.
822 if (mConnectedSignal != null) {
bohu07cc3bb2016-05-03 15:58:01 -0700823 // The system is booting and we're connecting to netd for the first time.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700824 mConnectedSignal.countDown();
825 mConnectedSignal = null;
826 } else {
bohu07cc3bb2016-05-03 15:58:01 -0700827 // We're reconnecting to netd after the socket connection
828 // was interrupted (e.g., if it crashed).
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700829 mFgHandler.post(new Runnable() {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700830 @Override
831 public void run() {
bohu07cc3bb2016-05-03 15:58:01 -0700832 connectNativeNetdService();
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700833 prepareNativeDaemon();
834 }
835 });
836 }
San Mehat873f2142010-01-14 10:25:07 -0800837 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700838
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700839 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800840 public boolean onCheckHoldWakeLock(int code) {
841 return code == NetdResponseCode.InterfaceClassActivity;
842 }
843
844 @Override
San Mehat873f2142010-01-14 10:25:07 -0800845 public boolean onEvent(int code, String raw, String[] cooked) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900846 String errorMessage = String.format("Invalid event from daemon (%s)", raw);
JP Abgrall12b933d2011-07-14 18:09:22 -0700847 switch (code) {
848 case NetdResponseCode.InterfaceChange:
849 /*
850 * a network interface change occured
851 * Format: "NNN Iface added <name>"
852 * "NNN Iface removed <name>"
853 * "NNN Iface changed <name> <up/down>"
854 * "NNN Iface linkstatus <name> <up/down>"
855 */
856 if (cooked.length < 4 || !cooked[1].equals("Iface")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900857 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700858 }
859 if (cooked[2].equals("added")) {
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900860 notifyInterfaceAdded(cooked[3]);
JP Abgrall12b933d2011-07-14 18:09:22 -0700861 return true;
862 } else if (cooked[2].equals("removed")) {
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900863 notifyInterfaceRemoved(cooked[3]);
JP Abgrall12b933d2011-07-14 18:09:22 -0700864 return true;
865 } else if (cooked[2].equals("changed") && cooked.length == 5) {
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900866 notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
JP Abgrall12b933d2011-07-14 18:09:22 -0700867 return true;
868 } else if (cooked[2].equals("linkstate") && cooked.length == 5) {
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900869 notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
JP Abgrall12b933d2011-07-14 18:09:22 -0700870 return true;
871 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900872 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700873 // break;
874 case NetdResponseCode.BandwidthControl:
875 /*
876 * Bandwidth control needs some attention
877 * Format: "NNN limit alert <alertName> <ifaceName>"
878 */
879 if (cooked.length < 5 || !cooked[1].equals("limit")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900880 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700881 }
882 if (cooked[2].equals("alert")) {
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900883 notifyLimitReached(cooked[3], cooked[4]);
JP Abgrall12b933d2011-07-14 18:09:22 -0700884 return true;
885 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900886 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700887 // break;
Haoyu Baidb3c8672012-06-20 14:29:57 -0700888 case NetdResponseCode.InterfaceClassActivity:
889 /*
890 * An network interface class state changed (active/idle)
891 * Format: "NNN IfaceClass <active/idle> <label>"
892 */
893 if (cooked.length < 4 || !cooked[1].equals("IfaceClass")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900894 throw new IllegalStateException(errorMessage);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700895 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700896 long timestampNanos = 0;
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700897 int processUid = -1;
898 if (cooked.length >= 5) {
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700899 try {
900 timestampNanos = Long.parseLong(cooked[4]);
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700901 if (cooked.length == 6) {
902 processUid = Integer.parseInt(cooked[5]);
903 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700904 } catch(NumberFormatException ne) {}
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700905 } else {
906 timestampNanos = SystemClock.elapsedRealtimeNanos();
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700907 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700908 boolean isActive = cooked[2].equals("active");
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900909 notifyInterfaceClassActivity(Integer.parseInt(cooked[3]),
910 isActive, timestampNanos, processUid, false);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700911 return true;
912 // break;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900913 case NetdResponseCode.InterfaceAddressChange:
914 /*
915 * A network address change occurred
916 * Format: "NNN Address updated <addr> <iface> <flags> <scope>"
917 * "NNN Address removed <addr> <iface> <flags> <scope>"
918 */
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900919 if (cooked.length < 7 || !cooked[1].equals("Address")) {
920 throw new IllegalStateException(errorMessage);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900921 }
922
Lorenzo Colitti64483942013-11-15 18:43:52 +0900923 String iface = cooked[4];
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900924 LinkAddress address;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900925 try {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900926 int flags = Integer.parseInt(cooked[5]);
927 int scope = Integer.parseInt(cooked[6]);
928 address = new LinkAddress(cooked[3], flags, scope);
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900929 } catch(NumberFormatException e) { // Non-numeric lifetime or scope.
930 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti64483942013-11-15 18:43:52 +0900931 } catch(IllegalArgumentException e) { // Malformed/invalid IP address.
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900932 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900933 }
934
935 if (cooked[2].equals("updated")) {
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900936 notifyAddressUpdated(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900937 } else {
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900938 notifyAddressRemoved(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900939 }
940 return true;
941 // break;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900942 case NetdResponseCode.InterfaceDnsServerInfo:
943 /*
944 * Information about available DNS servers has been received.
945 * Format: "NNN DnsInfo servers <interface> <lifetime> <servers>"
946 */
947 long lifetime; // Actually a 32-bit unsigned integer.
948
949 if (cooked.length == 6 &&
950 cooked[1].equals("DnsInfo") &&
951 cooked[2].equals("servers")) {
952 try {
953 lifetime = Long.parseLong(cooked[4]);
954 } catch (NumberFormatException e) {
955 throw new IllegalStateException(errorMessage);
956 }
957 String[] servers = cooked[5].split(",");
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900958 notifyInterfaceDnsServerInfo(cooked[3], lifetime, servers);
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900959 }
960 return true;
961 // break;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900962 case NetdResponseCode.RouteChange:
963 /*
964 * A route has been updated or removed.
965 * Format: "NNN Route <updated|removed> <dst> [via <gateway] [dev <iface>]"
966 */
967 if (!cooked[1].equals("Route") || cooked.length < 6) {
968 throw new IllegalStateException(errorMessage);
969 }
970
971 String via = null;
972 String dev = null;
973 boolean valid = true;
974 for (int i = 4; (i + 1) < cooked.length && valid; i += 2) {
975 if (cooked[i].equals("dev")) {
976 if (dev == null) {
977 dev = cooked[i+1];
978 } else {
979 valid = false; // Duplicate interface.
980 }
981 } else if (cooked[i].equals("via")) {
982 if (via == null) {
983 via = cooked[i+1];
984 } else {
985 valid = false; // Duplicate gateway.
986 }
987 } else {
988 valid = false; // Unknown syntax.
989 }
990 }
991 if (valid) {
992 try {
993 // InetAddress.parseNumericAddress(null) inexplicably returns ::1.
994 InetAddress gateway = null;
995 if (via != null) gateway = InetAddress.parseNumericAddress(via);
996 RouteInfo route = new RouteInfo(new IpPrefix(cooked[3]), gateway, dev);
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +0900997 notifyRouteChange(cooked[2].equals("updated"), route);
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900998 return true;
999 } catch (IllegalArgumentException e) {}
1000 }
1001 throw new IllegalStateException(errorMessage);
1002 // break;
Jeff Sharkey605eb792014-11-04 13:34:06 -08001003 case NetdResponseCode.StrictCleartext:
1004 final int uid = Integer.parseInt(cooked[1]);
1005 final byte[] firstPacket = HexDump.hexStringToByteArray(cooked[2]);
1006 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001007 ActivityManager.getService().notifyCleartextNetwork(uid, firstPacket);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001008 } catch (RemoteException ignored) {
1009 }
1010 break;
JP Abgrall12b933d2011-07-14 18:09:22 -07001011 default: break;
Robert Greenwalte3253922010-02-18 09:23:25 -08001012 }
1013 return false;
San Mehat873f2142010-01-14 10:25:07 -08001014 }
1015 }
1016
San Mehated4fc8a2010-01-22 12:28:36 -08001017
San Mehat873f2142010-01-14 10:25:07 -08001018 //
1019 // INetworkManagementService members
1020 //
Erik Kline4e37b702016-07-05 11:34:21 +09001021 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001022 public String[] listInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001023 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001024 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +08001025 return mNetdService.interfaceGetList();
Luke Huang14f75442018-08-15 19:22:54 +08001026 } catch (RemoteException | ServiceSpecificException e) {
1027 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001028 }
San Mehated4fc8a2010-01-22 12:28:36 -08001029 }
1030
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001031 @Override
1032 public InterfaceConfiguration getInterfaceConfig(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001033 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang14f75442018-08-15 19:22:54 +08001034 final InterfaceConfigurationParcel result;
Kenny Roota80ce062010-06-01 13:23:53 -07001035 try {
Luke Huang14f75442018-08-15 19:22:54 +08001036 result = mNetdService.interfaceGetCfg(iface);
1037 } catch (RemoteException | ServiceSpecificException e) {
1038 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001039 }
San Mehated4fc8a2010-01-22 12:28:36 -08001040
San Mehated4fc8a2010-01-22 12:28:36 -08001041 try {
Luke Huang14f75442018-08-15 19:22:54 +08001042 final InterfaceConfiguration cfg = InterfaceConfiguration.fromParcel(result);
1043 return cfg;
1044 } catch (IllegalArgumentException iae) {
1045 throw new IllegalStateException("Invalid InterfaceConfigurationParcel", iae);
San Mehated4fc8a2010-01-22 12:28:36 -08001046 }
San Mehated4fc8a2010-01-22 12:28:36 -08001047 }
1048
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001049 @Override
1050 public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001051 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001052 LinkAddress linkAddr = cfg.getLinkAddress();
Robert Greenwalt2d2afd12011-02-01 15:30:46 -08001053 if (linkAddr == null || linkAddr.getAddress() == null) {
1054 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -08001055 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001056
Luke Huang14f75442018-08-15 19:22:54 +08001057 final InterfaceConfigurationParcel cfgParcel = cfg.toParcel(iface);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001058
Kenny Roota80ce062010-06-01 13:23:53 -07001059 try {
Luke Huang14f75442018-08-15 19:22:54 +08001060 mNetdService.interfaceSetCfg(cfgParcel);
1061 } catch (RemoteException | ServiceSpecificException e) {
1062 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001063 }
San Mehat873f2142010-01-14 10:25:07 -08001064 }
1065
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001066 @Override
1067 public void setInterfaceDown(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001068 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001069 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001070 ifcg.setInterfaceDown();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001071 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001072 }
1073
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001074 @Override
1075 public void setInterfaceUp(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001076 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001077 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001078 ifcg.setInterfaceUp();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001079 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001080 }
1081
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001082 @Override
1083 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001084 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sheriff73293612011-09-14 12:31:56 -07001085 try {
Luke Huang14f75442018-08-15 19:22:54 +08001086 mNetdService.interfaceSetIPv6PrivacyExtensions(iface, enable);
1087 } catch (RemoteException | ServiceSpecificException e) {
1088 throw new IllegalStateException(e);
Irfan Sheriff73293612011-09-14 12:31:56 -07001089 }
1090 }
1091
Irfan Sherifff5600612011-06-16 10:26:28 -07001092 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
1093 IPv6 addresses on interface down, but we need to do full clean up here */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001094 @Override
1095 public void clearInterfaceAddresses(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001096 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sherifff5600612011-06-16 10:26:28 -07001097 try {
Luke Huang14f75442018-08-15 19:22:54 +08001098 mNetdService.interfaceClearAddrs(iface);
1099 } catch (RemoteException | ServiceSpecificException e) {
1100 throw new IllegalStateException(e);
Irfan Sherifff5600612011-06-16 10:26:28 -07001101 }
1102 }
1103
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001104 @Override
1105 public void enableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001106 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001107 try {
Luke Huang14f75442018-08-15 19:22:54 +08001108 mNetdService.interfaceSetEnableIPv6(iface, true);
1109 } catch (RemoteException | ServiceSpecificException e) {
1110 throw new IllegalStateException(e);
repo sync7960d9f2011-09-29 12:40:02 -07001111 }
1112 }
1113
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001114 @Override
Joel Scherpelz2db10742017-06-07 15:38:38 +09001115 public void setIPv6AddrGenMode(String iface, int mode) throws ServiceSpecificException {
1116 try {
1117 mNetdService.setIPv6AddrGenMode(iface, mode);
1118 } catch (RemoteException e) {
1119 throw e.rethrowAsRuntimeException();
1120 }
1121 }
1122
1123 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001124 public void disableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001125 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001126 try {
Luke Huang14f75442018-08-15 19:22:54 +08001127 mNetdService.interfaceSetEnableIPv6(iface, false);
1128 } catch (RemoteException | ServiceSpecificException e) {
1129 throw new IllegalStateException(e);
repo sync7960d9f2011-09-29 12:40:02 -07001130 }
1131 }
1132
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001133 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001134 public void addRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001135 modifyRoute(MODIFY_OPERATION_ADD, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001136 }
1137
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001138 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001139 public void removeRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001140 modifyRoute(MODIFY_OPERATION_REMOVE, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001141 }
1142
Luke Huang8a462ec2018-08-24 20:33:16 +08001143 private void modifyRoute(boolean add, int netId, RouteInfo route) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001144 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001145
Luke Huang8a462ec2018-08-24 20:33:16 +08001146 final String ifName = route.getInterface();
1147 final String dst = route.getDestination().toString();
1148 final String nextHop;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001149
1150 switch (route.getType()) {
1151 case RouteInfo.RTN_UNICAST:
1152 if (route.hasGateway()) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001153 nextHop = route.getGateway().getHostAddress();
1154 } else {
1155 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001156 }
1157 break;
1158 case RouteInfo.RTN_UNREACHABLE:
Luke Huang8a462ec2018-08-24 20:33:16 +08001159 nextHop = INetd.NEXTHOP_UNREACHABLE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001160 break;
1161 case RouteInfo.RTN_THROW:
Luke Huang8a462ec2018-08-24 20:33:16 +08001162 nextHop = INetd.NEXTHOP_THROW;
1163 break;
1164 default:
1165 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001166 break;
Sreeram Ramachandran1fbcb272014-05-22 16:30:48 -07001167 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001168 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08001169 if (add) {
1170 mNetdService.networkAddRoute(netId, ifName, dst, nextHop);
1171 } else {
1172 mNetdService.networkRemoveRoute(netId, ifName, dst, nextHop);
1173 }
1174 } catch (RemoteException | ServiceSpecificException e) {
1175 throw new IllegalStateException(e);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001176 }
1177 }
1178
1179 private ArrayList<String> readRouteList(String filename) {
1180 FileInputStream fstream = null;
Christopher Wiley212b95f2016-08-02 11:38:57 -07001181 ArrayList<String> list = new ArrayList<>();
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001182
1183 try {
1184 fstream = new FileInputStream(filename);
1185 DataInputStream in = new DataInputStream(fstream);
1186 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1187 String s;
1188
1189 // throw away the title line
1190
1191 while (((s = br.readLine()) != null) && (s.length() != 0)) {
1192 list.add(s);
1193 }
1194 } catch (IOException ex) {
1195 // return current list, possibly empty
1196 } finally {
1197 if (fstream != null) {
1198 try {
1199 fstream.close();
1200 } catch (IOException ex) {}
1201 }
1202 }
1203
1204 return list;
1205 }
1206
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001207 @Override
sy.yun9d9b74a2013-09-02 05:24:09 +09001208 public void setMtu(String iface, int mtu) {
1209 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1210
sy.yun9d9b74a2013-09-02 05:24:09 +09001211 try {
Luke Huang14f75442018-08-15 19:22:54 +08001212 mNetdService.interfaceSetMtu(iface, mtu);
1213 } catch (RemoteException | ServiceSpecificException e) {
1214 throw new IllegalStateException(e);
sy.yun9d9b74a2013-09-02 05:24:09 +09001215 }
1216 }
1217
1218 @Override
San Mehat873f2142010-01-14 10:25:07 -08001219 public void shutdown() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001220 // TODO: remove from aidl if nobody calls externally
1221 mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001222
Felipe Leme03e689d2016-03-02 16:17:38 -08001223 Slog.i(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -08001224 }
1225
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001226 @Override
San Mehat873f2142010-01-14 10:25:07 -08001227 public boolean getIpForwardingEnabled() throws IllegalStateException{
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001228 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001229
Kenny Roota80ce062010-06-01 13:23:53 -07001230 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001231 final boolean isEnabled = mNetdService.ipfwdEnabled();
1232 return isEnabled;
1233 } catch (RemoteException | ServiceSpecificException e) {
1234 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001235 }
San Mehat873f2142010-01-14 10:25:07 -08001236 }
1237
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001238 @Override
1239 public void setIpForwardingEnabled(boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001240 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001241 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001242 if (enable) {
1243 mNetdService.ipfwdEnableForwarding("tethering");
1244 } else {
1245 mNetdService.ipfwdDisableForwarding("tethering");
1246 }
1247 } catch (RemoteException | ServiceSpecificException e) {
1248 throw new IllegalStateException(e);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001249 }
San Mehat873f2142010-01-14 10:25:07 -08001250 }
1251
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001252 @Override
1253 public void startTethering(String[] dhcpRange) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001254 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -07001255 // an odd number of addrs will fail
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001256
Kenny Roota80ce062010-06-01 13:23:53 -07001257 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001258 mNetdService.tetherStart(dhcpRange);
1259 } catch (RemoteException | ServiceSpecificException e) {
1260 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001261 }
San Mehat873f2142010-01-14 10:25:07 -08001262 }
1263
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001264 @Override
1265 public void stopTethering() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001266 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001267 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001268 mNetdService.tetherStop();
1269 } catch (RemoteException | ServiceSpecificException e) {
1270 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001271 }
San Mehat873f2142010-01-14 10:25:07 -08001272 }
1273
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001274 @Override
1275 public boolean isTetheringStarted() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001276 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001277
Kenny Roota80ce062010-06-01 13:23:53 -07001278 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001279 final boolean isEnabled = mNetdService.tetherIsEnabled();
1280 return isEnabled;
1281 } catch (RemoteException | ServiceSpecificException e) {
1282 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001283 }
San Mehat873f2142010-01-14 10:25:07 -08001284 }
Matthew Xiefe19f122012-07-12 16:03:32 -07001285
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001286 @Override
1287 public void tetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001288 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001289 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001290 mNetdService.tetherInterfaceAdd(iface);
1291 } catch (RemoteException | ServiceSpecificException e) {
1292 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001293 }
Christopher Wiley212b95f2016-08-02 11:38:57 -07001294 List<RouteInfo> routes = new ArrayList<>();
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07001295 // The RouteInfo constructor truncates the LinkAddress to a network prefix, thus making it
1296 // suitable to use as a route destination.
1297 routes.add(new RouteInfo(getInterfaceConfig(iface).getLinkAddress(), null, iface));
1298 addInterfaceToLocalNetwork(iface, routes);
San Mehat873f2142010-01-14 10:25:07 -08001299 }
1300
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001301 @Override
San Mehat873f2142010-01-14 10:25:07 -08001302 public void untetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001303 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001304 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001305 mNetdService.tetherInterfaceRemove(iface);
1306 } catch (RemoteException | ServiceSpecificException e) {
1307 throw new IllegalStateException(e);
Erik Kline1f4278a2016-08-16 16:46:33 +09001308 } finally {
1309 removeInterfaceFromLocalNetwork(iface);
Kenny Roota80ce062010-06-01 13:23:53 -07001310 }
San Mehat873f2142010-01-14 10:25:07 -08001311 }
1312
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001313 @Override
1314 public String[] listTetheredInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001315 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001316 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +08001317 return mNetdService.tetherInterfaceList();
Luke Huang4a32bf42018-08-21 19:09:45 +08001318 } catch (RemoteException | ServiceSpecificException e) {
1319 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001320 }
San Mehat873f2142010-01-14 10:25:07 -08001321 }
1322
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001323 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001324 public void setDnsForwarders(Network network, String[] dns) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001325 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001326
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001327 int netId = (network != null) ? network.netId : ConnectivityManager.NETID_UNSET;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001328
San Mehat873f2142010-01-14 10:25:07 -08001329 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001330 mNetdService.tetherDnsSet(netId, dns);
1331 } catch (RemoteException | ServiceSpecificException e) {
1332 throw new IllegalStateException(e);
San Mehat873f2142010-01-14 10:25:07 -08001333 }
1334 }
1335
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001336 @Override
1337 public String[] getDnsForwarders() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001338 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001339 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +08001340 return mNetdService.tetherDnsList();
Luke Huang4a32bf42018-08-21 19:09:45 +08001341 } catch (RemoteException | ServiceSpecificException e) {
1342 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001343 }
San Mehat873f2142010-01-14 10:25:07 -08001344 }
1345
jiaguo1da35f72014-01-09 16:39:59 +08001346 private List<InterfaceAddress> excludeLinkLocal(List<InterfaceAddress> addresses) {
Christopher Wiley212b95f2016-08-02 11:38:57 -07001347 ArrayList<InterfaceAddress> filtered = new ArrayList<>(addresses.size());
jiaguo1da35f72014-01-09 16:39:59 +08001348 for (InterfaceAddress ia : addresses) {
1349 if (!ia.getAddress().isLinkLocalAddress())
1350 filtered.add(ia);
1351 }
1352 return filtered;
1353 }
1354
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001355 private void modifyInterfaceForward(boolean add, String fromIface, String toIface) {
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001356 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001357 if (add) {
1358 mNetdService.ipfwdAddInterfaceForward(fromIface, toIface);
1359 } else {
1360 mNetdService.ipfwdRemoveInterfaceForward(fromIface, toIface);
1361 }
1362 } catch (RemoteException | ServiceSpecificException e) {
1363 throw new IllegalStateException(e);
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001364 }
1365 }
1366
1367 @Override
1368 public void startInterfaceForwarding(String fromIface, String toIface) {
1369 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1370 modifyInterfaceForward(true, fromIface, toIface);
1371 }
1372
1373 @Override
1374 public void stopInterfaceForwarding(String fromIface, String toIface) {
1375 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1376 modifyInterfaceForward(false, fromIface, toIface);
1377 }
1378
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001379 @Override
1380 public void enableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001381 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001382 try {
Luke Huanga31e0732018-10-22 13:23:10 +09001383 mNetdService.tetherAddForward(internalInterface, externalInterface);
1384 } catch (RemoteException | ServiceSpecificException e) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001385 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001386 }
San Mehat873f2142010-01-14 10:25:07 -08001387 }
1388
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001389 @Override
1390 public void disableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001391 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001392 try {
Luke Huanga31e0732018-10-22 13:23:10 +09001393 mNetdService.tetherRemoveForward(internalInterface, externalInterface);
1394 } catch (RemoteException | ServiceSpecificException e) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001395 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001396 }
San Mehat873f2142010-01-14 10:25:07 -08001397 }
San Mehat72759df2010-01-19 13:50:37 -08001398
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001399 @Override
1400 public String[] listTtys() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001401 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001402 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001403 return NativeDaemonEvent.filterMessageList(
1404 mConnector.executeForList("list_ttys"), TtyListResult);
Kenny Roota80ce062010-06-01 13:23:53 -07001405 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001406 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001407 }
San Mehat72759df2010-01-19 13:50:37 -08001408 }
1409
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001410 @Override
1411 public void attachPppd(
1412 String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001413 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat72759df2010-01-19 13:50:37 -08001414 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001415 mConnector.execute("pppd", "attach", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -08001416 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
1417 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
1418 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001419 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress());
Kenny Roota80ce062010-06-01 13:23:53 -07001420 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001421 throw e.rethrowAsParcelableException();
San Mehat72759df2010-01-19 13:50:37 -08001422 }
1423 }
1424
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001425 @Override
1426 public void detachPppd(String tty) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001427 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001428 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001429 mConnector.execute("pppd", "detach", tty);
Kenny Roota80ce062010-06-01 13:23:53 -07001430 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001431 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001432 }
San Mehat72759df2010-01-19 13:50:37 -08001433 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -08001434
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001435 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001436 public void addIdleTimer(String iface, int timeout, final int type) {
Haoyu Bai04124232012-06-28 15:26:19 -07001437 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1438
1439 if (DBG) Slog.d(TAG, "Adding idletimer");
1440
1441 synchronized (mIdleTimerLock) {
1442 IdleTimerParams params = mActiveIdleTimers.get(iface);
1443 if (params != null) {
1444 // the interface already has idletimer, update network count
1445 params.networkCount++;
1446 return;
1447 }
1448
1449 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001450 mNetdService.idletimerAddInterface(iface, timeout, Integer.toString(type));
1451 } catch (RemoteException | ServiceSpecificException e) {
1452 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001453 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001454 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
1455
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001456 // Networks start up.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001457 if (ConnectivityManager.isNetworkTypeMobile(type)) {
1458 mNetworkActive = false;
1459 }
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +09001460 mDaemonHandler.post(() -> notifyInterfaceClassActivity(type, true,
1461 SystemClock.elapsedRealtimeNanos(), -1, false));
Haoyu Bai04124232012-06-28 15:26:19 -07001462 }
1463 }
1464
1465 @Override
1466 public void removeIdleTimer(String iface) {
1467 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1468
1469 if (DBG) Slog.d(TAG, "Removing idletimer");
1470
1471 synchronized (mIdleTimerLock) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001472 final IdleTimerParams params = mActiveIdleTimers.get(iface);
Haoyu Bai04124232012-06-28 15:26:19 -07001473 if (params == null || --(params.networkCount) > 0) {
1474 return;
1475 }
1476
1477 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001478 mNetdService.idletimerRemoveInterface(iface,
1479 params.timeout, Integer.toString(params.type));
1480 } catch (RemoteException | ServiceSpecificException e) {
1481 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001482 }
1483 mActiveIdleTimers.remove(iface);
Remi NGUYEN VAN9ebc3fc2019-01-29 19:12:13 +09001484 mDaemonHandler.post(() -> notifyInterfaceClassActivity(params.type, false,
1485 SystemClock.elapsedRealtimeNanos(), -1, false));
Haoyu Bai04124232012-06-28 15:26:19 -07001486 }
1487 }
1488
1489 @Override
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001490 public NetworkStats getNetworkStatsSummaryDev() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001491 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001492 try {
1493 return mStatsFactory.readNetworkStatsSummaryDev();
1494 } catch (IOException e) {
1495 throw new IllegalStateException(e);
1496 }
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001497 }
1498
1499 @Override
1500 public NetworkStats getNetworkStatsSummaryXt() {
1501 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001502 try {
1503 return mStatsFactory.readNetworkStatsSummaryXt();
1504 } catch (IOException e) {
1505 throw new IllegalStateException(e);
1506 }
Jeff Sharkeyae2c1812011-10-04 13:11:40 -07001507 }
1508
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001509 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001510 public NetworkStats getNetworkStatsDetail() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001511 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001512 try {
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08001513 return mStatsFactory.readNetworkStatsDetail(UID_ALL, null, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001514 } catch (IOException e) {
1515 throw new IllegalStateException(e);
1516 }
San Mehat91cac642010-03-31 14:31:36 -07001517 }
1518
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001519 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001520 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001521 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001522
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001523 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001524 if (mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001525 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001526 }
1527
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001528 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001529 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001530 mNetdService.bandwidthSetInterfaceQuota(iface, quotaBytes);
1531
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001532 mActiveQuotas.put(iface, quotaBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001533 } catch (RemoteException | ServiceSpecificException e) {
1534 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001535 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001536
1537 synchronized (mTetheringStatsProviders) {
1538 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1539 try {
1540 provider.setInterfaceQuota(iface, quotaBytes);
1541 } catch (RemoteException e) {
1542 Log.e(TAG, "Problem setting tethering data limit on provider " +
1543 mTetheringStatsProviders.get(provider) + ": " + e);
1544 }
1545 }
1546 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001547 }
1548 }
1549
1550 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001551 public void removeInterfaceQuota(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001552 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001553
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001554 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001555 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001556 // TODO: eventually consider throwing
1557 return;
1558 }
1559
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001560 mActiveQuotas.remove(iface);
1561 mActiveAlerts.remove(iface);
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001562
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001563 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001564 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001565 mNetdService.bandwidthRemoveInterfaceQuota(iface);
1566 } catch (RemoteException | ServiceSpecificException e) {
1567 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001568 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001569
1570 synchronized (mTetheringStatsProviders) {
1571 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1572 try {
1573 provider.setInterfaceQuota(iface, ITetheringStatsProvider.QUOTA_UNLIMITED);
1574 } catch (RemoteException e) {
1575 Log.e(TAG, "Problem removing tethering data limit on provider " +
1576 mTetheringStatsProviders.get(provider) + ": " + e);
1577 }
1578 }
1579 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001580 }
1581 }
1582
1583 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001584 public void setInterfaceAlert(String iface, long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001585 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001586
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001587 // quick sanity check
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001588 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001589 throw new IllegalStateException("setting alert requires existing quota on iface");
1590 }
1591
1592 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001593 if (mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001594 throw new IllegalStateException("iface " + iface + " already has alert");
1595 }
1596
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001597 try {
1598 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001599 mNetdService.bandwidthSetInterfaceAlert(iface, alertBytes);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001600 mActiveAlerts.put(iface, alertBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001601 } catch (RemoteException | ServiceSpecificException e) {
1602 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001603 }
1604 }
1605 }
1606
1607 @Override
1608 public void removeInterfaceAlert(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001609 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001610
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001611 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001612 if (!mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001613 // TODO: eventually consider throwing
1614 return;
1615 }
1616
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001617 try {
1618 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001619 mNetdService.bandwidthRemoveInterfaceAlert(iface);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001620 mActiveAlerts.remove(iface);
Luke Huangc7bea8662018-08-07 16:04:26 +08001621 } catch (RemoteException | ServiceSpecificException e) {
1622 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001623 }
1624 }
1625 }
1626
1627 @Override
1628 public void setGlobalAlert(long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001629 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001630
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001631 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001632 mNetdService.bandwidthSetGlobalAlert(alertBytes);
1633 } catch (RemoteException | ServiceSpecificException e) {
1634 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001635 }
1636 }
1637
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001638 private void setUidOnMeteredNetworkList(int uid, boolean blacklist, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001639 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001640
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001641 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001642 boolean oldEnable;
1643 SparseBooleanArray quotaList;
1644 synchronized (mRulesLock) {
1645 quotaList = blacklist ? mUidRejectOnMetered : mUidAllowOnMetered;
1646 oldEnable = quotaList.get(uid, false);
1647 }
Felipe Leme65be3022016-03-22 14:53:13 -07001648 if (oldEnable == enable) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001649 // TODO: eventually consider throwing
1650 return;
1651 }
1652
Felipe Leme29e72ea2016-09-08 13:26:55 -07001653 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "inetd bandwidth");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001654 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001655 if (blacklist) {
1656 if (enable) {
1657 mNetdService.bandwidthAddNaughtyApp(uid);
1658 } else {
1659 mNetdService.bandwidthRemoveNaughtyApp(uid);
1660 }
1661 } else {
1662 if (enable) {
1663 mNetdService.bandwidthAddNiceApp(uid);
1664 } else {
1665 mNetdService.bandwidthRemoveNiceApp(uid);
1666 }
1667 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001668 synchronized (mRulesLock) {
1669 if (enable) {
1670 quotaList.put(uid, true);
1671 } else {
1672 quotaList.delete(uid);
1673 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001674 }
Luke Huangc7bea8662018-08-07 16:04:26 +08001675 } catch (RemoteException | ServiceSpecificException e) {
1676 throw new IllegalStateException(e);
Felipe Leme29e72ea2016-09-08 13:26:55 -07001677 } finally {
1678 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001679 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001680 }
1681 }
1682
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001683 @Override
Felipe Leme65be3022016-03-22 14:53:13 -07001684 public void setUidMeteredNetworkBlacklist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001685 setUidOnMeteredNetworkList(uid, true, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001686 }
1687
1688 @Override
1689 public void setUidMeteredNetworkWhitelist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001690 setUidOnMeteredNetworkList(uid, false, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001691 }
1692
1693 @Override
1694 public boolean setDataSaverModeEnabled(boolean enable) {
Sehee Parka9139bc2017-12-22 13:54:05 +09001695 mContext.enforceCallingOrSelfPermission(NETWORK_SETTINGS, TAG);
1696
Felipe Leme65be3022016-03-22 14:53:13 -07001697 if (DBG) Log.d(TAG, "setDataSaverMode: " + enable);
1698 synchronized (mQuotaLock) {
1699 if (mDataSaverMode == enable) {
1700 Log.w(TAG, "setDataSaverMode(): already " + mDataSaverMode);
1701 return true;
1702 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07001703 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "bandwidthEnableDataSaver");
Felipe Leme65be3022016-03-22 14:53:13 -07001704 try {
1705 final boolean changed = mNetdService.bandwidthEnableDataSaver(enable);
1706 if (changed) {
1707 mDataSaverMode = enable;
1708 } else {
1709 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command silently failed");
1710 }
1711 return changed;
1712 } catch (RemoteException e) {
1713 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command failed", e);
1714 return false;
Felipe Leme29e72ea2016-09-08 13:26:55 -07001715 } finally {
1716 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme65be3022016-03-22 14:53:13 -07001717 }
1718 }
1719 }
1720
1721 @Override
Robin Lee17e61832016-05-09 13:46:28 +01001722 public void setAllowOnlyVpnForUids(boolean add, UidRange[] uidRanges)
1723 throws ServiceSpecificException {
Rubin Xube806662018-01-11 10:59:19 +00001724 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robin Lee17e61832016-05-09 13:46:28 +01001725 try {
1726 mNetdService.networkRejectNonSecureVpn(add, uidRanges);
1727 } catch (ServiceSpecificException e) {
1728 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1729 + ": netd command failed", e);
1730 throw e;
1731 } catch (RemoteException e) {
1732 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1733 + ": netd command failed", e);
1734 throw e.rethrowAsRuntimeException();
1735 }
1736 }
1737
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001738 private void applyUidCleartextNetworkPolicy(int uid, int policy) {
Luke Huang473eb872018-07-26 17:33:14 +08001739 final int policyValue;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001740 switch (policy) {
1741 case StrictMode.NETWORK_POLICY_ACCEPT:
Luke Huang473eb872018-07-26 17:33:14 +08001742 policyValue = INetd.PENALTY_POLICY_ACCEPT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001743 break;
1744 case StrictMode.NETWORK_POLICY_LOG:
Luke Huang473eb872018-07-26 17:33:14 +08001745 policyValue = INetd.PENALTY_POLICY_LOG;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001746 break;
1747 case StrictMode.NETWORK_POLICY_REJECT:
Luke Huang473eb872018-07-26 17:33:14 +08001748 policyValue = INetd.PENALTY_POLICY_REJECT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001749 break;
1750 default:
1751 throw new IllegalArgumentException("Unknown policy " + policy);
1752 }
1753
1754 try {
Luke Huang473eb872018-07-26 17:33:14 +08001755 mNetdService.strictUidCleartextPenalty(uid, policyValue);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001756 mUidCleartextPolicy.put(uid, policy);
Luke Huang473eb872018-07-26 17:33:14 +08001757 } catch (RemoteException | ServiceSpecificException e) {
1758 throw new IllegalStateException(e);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001759 }
1760 }
1761
Robin Lee17e61832016-05-09 13:46:28 +01001762 @Override
Jeff Sharkey605eb792014-11-04 13:34:06 -08001763 public void setUidCleartextNetworkPolicy(int uid, int policy) {
1764 if (Binder.getCallingUid() != uid) {
1765 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1766 }
1767
1768 synchronized (mQuotaLock) {
1769 final int oldPolicy = mUidCleartextPolicy.get(uid, StrictMode.NETWORK_POLICY_ACCEPT);
1770 if (oldPolicy == policy) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001771 // This also ensures we won't needlessly apply an ACCEPT policy if we've just
1772 // enabled strict and the underlying iptables rules are empty.
Jeff Sharkey605eb792014-11-04 13:34:06 -08001773 return;
1774 }
1775
Luke Huang473eb872018-07-26 17:33:14 +08001776 // TODO: remove this code after removing prepareNativeDaemon()
Jeff Sharkey605eb792014-11-04 13:34:06 -08001777 if (!mStrictEnabled) {
1778 // Module isn't enabled yet; stash the requested policy away to
1779 // apply later once the daemon is connected.
1780 mUidCleartextPolicy.put(uid, policy);
1781 return;
1782 }
1783
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001784 // netd does not keep state on strict mode policies, and cannot replace a non-accept
1785 // policy without deleting it first. Rather than add state to netd, just always send
1786 // it an accept policy when switching between two non-accept policies.
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001787 // TODO: consider keeping state in netd so we can simplify this code.
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001788 if (oldPolicy != StrictMode.NETWORK_POLICY_ACCEPT &&
1789 policy != StrictMode.NETWORK_POLICY_ACCEPT) {
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001790 applyUidCleartextNetworkPolicy(uid, StrictMode.NETWORK_POLICY_ACCEPT);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001791 }
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001792
1793 applyUidCleartextNetworkPolicy(uid, policy);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001794 }
1795 }
1796
1797 @Override
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001798 public boolean isBandwidthControlEnabled() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001799 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang56a03a02018-09-07 12:02:16 +08001800 return true;
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001801 }
1802
1803 @Override
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001804 public NetworkStats getNetworkStatsUidDetail(int uid, String[] ifaces) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001805 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001806 try {
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001807 return mStatsFactory.readNetworkStatsDetail(uid, ifaces, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001808 } catch (IOException e) {
1809 throw new IllegalStateException(e);
1810 }
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001811 }
1812
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001813 private class NetdTetheringStatsProvider extends ITetheringStatsProvider.Stub {
1814 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001815 public NetworkStats getTetherStats(int how) {
1816 // We only need to return per-UID stats. Per-device stats are already counted by
1817 // interface counters.
1818 if (how != STATS_PER_UID) {
1819 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
1820 }
1821
Luke Huang13b79e82018-09-26 14:53:42 +08001822 final TetherStatsParcel[] tetherStatsVec;
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001823 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001824 tetherStatsVec = mNetdService.tetherGetStats();
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001825 } catch (RemoteException | ServiceSpecificException e) {
1826 throw new IllegalStateException("problem parsing tethering stats: ", e);
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001827 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001828
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001829 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(),
Luke Huang13b79e82018-09-26 14:53:42 +08001830 tetherStatsVec.length);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001831 final NetworkStats.Entry entry = new NetworkStats.Entry();
1832
Luke Huang13b79e82018-09-26 14:53:42 +08001833 for (TetherStatsParcel tetherStats : tetherStatsVec) {
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001834 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001835 entry.iface = tetherStats.iface;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001836 entry.uid = UID_TETHERING;
1837 entry.set = SET_DEFAULT;
1838 entry.tag = TAG_NONE;
Luke Huang13b79e82018-09-26 14:53:42 +08001839 entry.rxBytes = tetherStats.rxBytes;
1840 entry.rxPackets = tetherStats.rxPackets;
1841 entry.txBytes = tetherStats.txBytes;
1842 entry.txPackets = tetherStats.txPackets;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001843 stats.combineValues(entry);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001844 } catch (ArrayIndexOutOfBoundsException e) {
Luke Huang13b79e82018-09-26 14:53:42 +08001845 throw new IllegalStateException("invalid tethering stats " + e);
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001846 }
1847 }
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001848
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001849 return stats;
1850 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001851
1852 @Override
1853 public void setInterfaceQuota(String iface, long quotaBytes) {
1854 // Do nothing. netd is already informed of quota changes in setInterfaceQuota.
1855 }
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001856 }
1857
1858 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001859 public NetworkStats getNetworkStatsTethering(int how) {
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001860 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1861
1862 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1863 synchronized (mTetheringStatsProviders) {
1864 for (ITetheringStatsProvider provider: mTetheringStatsProviders.keySet()) {
1865 try {
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001866 stats.combineAllValues(provider.getTetherStats(how));
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001867 } catch (RemoteException e) {
1868 Log.e(TAG, "Problem reading tethering stats from " +
1869 mTetheringStatsProviders.get(provider) + ": " + e);
1870 }
1871 }
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001872 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001873 return stats;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001874 }
1875
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001876 @Override
Erik Kline1742fe12017-12-13 19:40:49 +09001877 public void setDnsConfigurationForNetwork(int netId, String[] servers, String[] domains,
Erik Klinee5dac902018-03-04 21:01:01 +09001878 int[] params, String tlsHostname, String[] tlsServers) {
Pierre Imai8e48e672016-04-21 13:30:43 +09001879 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1880
Ben Schwartz6ec28df2017-10-02 13:08:06 -04001881 final String[] tlsFingerprints = new String[0];
Pierre Imai8e48e672016-04-21 13:30:43 +09001882 try {
Erik Kline1742fe12017-12-13 19:40:49 +09001883 mNetdService.setResolverConfiguration(
Erik Klinee5dac902018-03-04 21:01:01 +09001884 netId, servers, domains, params, tlsHostname, tlsServers, tlsFingerprints);
Pierre Imai8e48e672016-04-21 13:30:43 +09001885 } catch (RemoteException e) {
1886 throw new RuntimeException(e);
1887 }
1888 }
1889
1890 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001891 public void addVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001892 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001893
1894 try {
1895 mNetdService.networkAddUidRanges(netId, ranges);
1896 } catch (RemoteException | ServiceSpecificException e) {
1897 throw new IllegalStateException(e);
Chad Brubaker3277620a2013-06-12 13:37:30 -07001898 }
1899 }
1900
1901 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001902 public void removeVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001903 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001904 try {
1905 mNetdService.networkRemoveUidRanges(netId, ranges);
1906 } catch (RemoteException | ServiceSpecificException e) {
1907 throw new IllegalStateException(e);
Chad Brubakercca54c42013-06-27 17:41:38 -07001908 }
1909 }
1910
1911 @Override
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001912 public void setFirewallEnabled(boolean enabled) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001913 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001914 try {
Luke Huanga241db92018-07-31 20:15:24 +08001915 mNetdService.firewallSetFirewallType(
1916 enabled ? INetd.FIREWALL_WHITELIST : INetd.FIREWALL_BLACKLIST);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001917 mFirewallEnabled = enabled;
Luke Huanga241db92018-07-31 20:15:24 +08001918 } catch (RemoteException | ServiceSpecificException e) {
1919 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001920 }
1921 }
1922
1923 @Override
1924 public boolean isFirewallEnabled() {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001925 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001926 return mFirewallEnabled;
1927 }
1928
1929 @Override
Jeff Sharkey2c092982012-08-24 11:44:40 -07001930 public void setFirewallInterfaceRule(String iface, boolean allow) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001931 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001932 Preconditions.checkState(mFirewallEnabled);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001933 try {
Luke Huanga241db92018-07-31 20:15:24 +08001934 mNetdService.firewallSetInterfaceRule(iface,
1935 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
1936 } catch (RemoteException | ServiceSpecificException e) {
1937 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001938 }
1939 }
1940
Lorenzo Colitti3fef7232016-04-29 18:00:03 +09001941 private void closeSocketsForFirewallChainLocked(int chain, String chainName) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001942 // UID ranges to close sockets on.
1943 UidRange[] ranges;
1944 // UID ranges whose sockets we won't touch.
1945 int[] exemptUids;
1946
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001947 int numUids = 0;
Luke Huanga241db92018-07-31 20:15:24 +08001948 if (DBG) Slog.d(TAG, "Closing sockets after enabling chain " + chainName);
Remi NGUYEN VANf9a8c2e2019-02-13 18:28:35 +09001949 if (getFirewallType(chain) == FIREWALL_WHITELIST) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001950 // Close all sockets on all non-system UIDs...
1951 ranges = new UidRange[] {
1952 // TODO: is there a better way of finding all existing users? If so, we could
1953 // specify their ranges here.
1954 new UidRange(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE),
1955 };
1956 // ... except for the UIDs that have allow rules.
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001957 synchronized (mRulesLock) {
1958 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1959 exemptUids = new int[rules.size()];
1960 for (int i = 0; i < exemptUids.length; i++) {
Remi NGUYEN VANf9a8c2e2019-02-13 18:28:35 +09001961 if (rules.valueAt(i) == FIREWALL_RULE_ALLOW) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001962 exemptUids[numUids] = rules.keyAt(i);
1963 numUids++;
1964 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001965 }
1966 }
1967 // Normally, whitelist chains only contain deny rules, so numUids == exemptUids.length.
1968 // But the code does not guarantee this in any way, and at least in one case - if we add
1969 // a UID rule to the firewall, and then disable the firewall - the chains can contain
1970 // the wrong type of rule. In this case, don't close connections that we shouldn't.
1971 //
1972 // TODO: tighten up this code by ensuring we never set the wrong type of rule, and
1973 // fix setFirewallEnabled to grab mQuotaLock and clear rules.
1974 if (numUids != exemptUids.length) {
1975 exemptUids = Arrays.copyOf(exemptUids, numUids);
1976 }
1977 } else {
1978 // Close sockets for every UID that has a deny rule...
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001979 synchronized (mRulesLock) {
1980 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1981 ranges = new UidRange[rules.size()];
1982 for (int i = 0; i < ranges.length; i++) {
Remi NGUYEN VANf9a8c2e2019-02-13 18:28:35 +09001983 if (rules.valueAt(i) == FIREWALL_RULE_DENY) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001984 int uid = rules.keyAt(i);
1985 ranges[numUids] = new UidRange(uid, uid);
1986 numUids++;
1987 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001988 }
1989 }
1990 // As above; usually numUids == ranges.length, but not always.
1991 if (numUids != ranges.length) {
1992 ranges = Arrays.copyOf(ranges, numUids);
1993 }
1994 // ... with no exceptions.
1995 exemptUids = new int[0];
1996 }
1997
1998 try {
1999 mNetdService.socketDestroy(ranges, exemptUids);
2000 } catch(RemoteException | ServiceSpecificException e) {
2001 Slog.e(TAG, "Error closing sockets after enabling chain " + chainName + ": " + e);
2002 }
2003 }
2004
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002005 @Override
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002006 public void setFirewallChainEnabled(int chain, boolean enable) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07002007 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002008 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002009 synchronized (mRulesLock) {
2010 if (getFirewallChainState(chain) == enable) {
2011 // All is the same, nothing to do. This relies on the fact that netd has child
2012 // chains default detached.
2013 return;
2014 }
2015 setFirewallChainState(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002016 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002017
Luke Huang615e1022018-10-25 11:54:05 +09002018 final String chainName = getFirewallChainName(chain);
Luke Huanga241db92018-07-31 20:15:24 +08002019 if (chain == FIREWALL_CHAIN_NONE) {
Luke Huang615e1022018-10-25 11:54:05 +09002020 throw new IllegalArgumentException("Bad child chain: " + chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002021 }
2022
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002023 try {
Luke Huanga241db92018-07-31 20:15:24 +08002024 mNetdService.firewallEnableChildChain(chain, enable);
2025 } catch (RemoteException | ServiceSpecificException e) {
2026 throw new IllegalStateException(e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002027 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002028
2029 // Close any sockets that were opened by the affected UIDs. This has to be done after
2030 // disabling network connectivity, in case they react to the socket close by reopening
2031 // the connection and race with the iptables commands that enable the firewall. All
2032 // whitelist and blacklist chains allow RSTs through.
2033 if (enable) {
Luke Huang615e1022018-10-25 11:54:05 +09002034 closeSocketsForFirewallChainLocked(chain, chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002035 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002036 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002037 }
2038
Luke Huanga241db92018-07-31 20:15:24 +08002039 private String getFirewallChainName(int chain) {
2040 switch (chain) {
2041 case FIREWALL_CHAIN_STANDBY:
2042 return FIREWALL_CHAIN_NAME_STANDBY;
2043 case FIREWALL_CHAIN_DOZABLE:
2044 return FIREWALL_CHAIN_NAME_DOZABLE;
2045 case FIREWALL_CHAIN_POWERSAVE:
2046 return FIREWALL_CHAIN_NAME_POWERSAVE;
2047 default:
2048 throw new IllegalArgumentException("Bad child chain: " + chain);
2049 }
2050 }
2051
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002052 private int getFirewallType(int chain) {
2053 switch (chain) {
2054 case FIREWALL_CHAIN_STANDBY:
Remi NGUYEN VANf9a8c2e2019-02-13 18:28:35 +09002055 return FIREWALL_BLACKLIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002056 case FIREWALL_CHAIN_DOZABLE:
Remi NGUYEN VANf9a8c2e2019-02-13 18:28:35 +09002057 return FIREWALL_WHITELIST;
Felipe Leme011b98f2016-02-10 17:28:31 -08002058 case FIREWALL_CHAIN_POWERSAVE:
Remi NGUYEN VANf9a8c2e2019-02-13 18:28:35 +09002059 return FIREWALL_WHITELIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002060 default:
Remi NGUYEN VANf9a8c2e2019-02-13 18:28:35 +09002061 return isFirewallEnabled() ? FIREWALL_WHITELIST : FIREWALL_BLACKLIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002062 }
2063 }
2064
2065 @Override
2066 public void setFirewallUidRules(int chain, int[] uids, int[] rules) {
2067 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002068 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002069 synchronized (mRulesLock) {
2070 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
2071 SparseIntArray newRules = new SparseIntArray();
2072 // apply new set of rules
2073 for (int index = uids.length - 1; index >= 0; --index) {
2074 int uid = uids[index];
2075 int rule = rules[index];
2076 updateFirewallUidRuleLocked(chain, uid, rule);
2077 newRules.put(uid, rule);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002078 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002079 // collect the rules to remove.
2080 SparseIntArray rulesToRemove = new SparseIntArray();
2081 for (int index = uidFirewallRules.size() - 1; index >= 0; --index) {
2082 int uid = uidFirewallRules.keyAt(index);
2083 if (newRules.indexOfKey(uid) < 0) {
2084 rulesToRemove.put(uid, FIREWALL_RULE_DEFAULT);
2085 }
2086 }
2087 // remove dead rules
2088 for (int index = rulesToRemove.size() - 1; index >= 0; --index) {
2089 int uid = rulesToRemove.keyAt(index);
2090 updateFirewallUidRuleLocked(chain, uid, FIREWALL_RULE_DEFAULT);
2091 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002092 }
2093 try {
2094 switch (chain) {
2095 case FIREWALL_CHAIN_DOZABLE:
2096 mNetdService.firewallReplaceUidChain("fw_dozable", true, uids);
2097 break;
2098 case FIREWALL_CHAIN_STANDBY:
2099 mNetdService.firewallReplaceUidChain("fw_standby", false, uids);
2100 break;
2101 case FIREWALL_CHAIN_POWERSAVE:
2102 mNetdService.firewallReplaceUidChain("fw_powersave", true, uids);
2103 break;
2104 case FIREWALL_CHAIN_NONE:
2105 default:
2106 Slog.d(TAG, "setFirewallUidRules() called on invalid chain: " + chain);
2107 }
2108 } catch (RemoteException e) {
2109 Slog.w(TAG, "Error flushing firewall chain " + chain, e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002110 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002111 }
2112 }
2113
2114 @Override
2115 public void setFirewallUidRule(int chain, int uid, int rule) {
2116 enforceSystemUid();
Felipe Lemea701cad2016-05-12 09:58:14 -07002117 synchronized (mQuotaLock) {
2118 setFirewallUidRuleLocked(chain, uid, rule);
2119 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002120 }
2121
Felipe Lemea701cad2016-05-12 09:58:14 -07002122 private void setFirewallUidRuleLocked(int chain, int uid, int rule) {
2123 if (updateFirewallUidRuleLocked(chain, uid, rule)) {
Luke Huanga241db92018-07-31 20:15:24 +08002124 final int ruleType = getFirewallRuleType(chain, rule);
Amith Yamasani15e472352015-04-24 19:06:07 -07002125 try {
Luke Huanga241db92018-07-31 20:15:24 +08002126 mNetdService.firewallSetUidRule(chain, uid, ruleType);
2127 } catch (RemoteException | ServiceSpecificException e) {
2128 throw new IllegalStateException(e);
Amith Yamasani15e472352015-04-24 19:06:07 -07002129 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002130 }
2131 }
2132
Felipe Lemea701cad2016-05-12 09:58:14 -07002133 // TODO: now that netd supports batching, NMS should not keep these data structures anymore...
2134 private boolean updateFirewallUidRuleLocked(int chain, int uid, int rule) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002135 synchronized (mRulesLock) {
2136 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Felipe Lemea701cad2016-05-12 09:58:14 -07002137
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002138 final int oldUidFirewallRule = uidFirewallRules.get(uid, FIREWALL_RULE_DEFAULT);
2139 if (DBG) {
2140 Slog.d(TAG, "oldRule = " + oldUidFirewallRule
2141 + ", newRule=" + rule + " for uid=" + uid + " on chain " + chain);
2142 }
2143 if (oldUidFirewallRule == rule) {
2144 if (DBG) Slog.d(TAG, "!!!!! Skipping change");
2145 // TODO: eventually consider throwing
2146 return false;
2147 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002148
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002149 String ruleName = getFirewallRuleName(chain, rule);
2150 String oldRuleName = getFirewallRuleName(chain, oldUidFirewallRule);
Felipe Lemea701cad2016-05-12 09:58:14 -07002151
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002152 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
2153 uidFirewallRules.delete(uid);
2154 } else {
2155 uidFirewallRules.put(uid, rule);
2156 }
2157 return !ruleName.equals(oldRuleName);
Felipe Lemea701cad2016-05-12 09:58:14 -07002158 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002159 }
2160
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002161 private @NonNull String getFirewallRuleName(int chain, int rule) {
2162 String ruleName;
Remi NGUYEN VANf9a8c2e2019-02-13 18:28:35 +09002163 if (getFirewallType(chain) == FIREWALL_WHITELIST) {
2164 if (rule == FIREWALL_RULE_ALLOW) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002165 ruleName = "allow";
2166 } else {
2167 ruleName = "deny";
2168 }
2169 } else { // Blacklist mode
Remi NGUYEN VANf9a8c2e2019-02-13 18:28:35 +09002170 if (rule == FIREWALL_RULE_DENY) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002171 ruleName = "deny";
2172 } else {
2173 ruleName = "allow";
2174 }
2175 }
2176 return ruleName;
2177 }
2178
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002179 @GuardedBy("mRulesLock")
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002180 private @NonNull SparseIntArray getUidFirewallRulesLR(int chain) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002181 switch (chain) {
2182 case FIREWALL_CHAIN_STANDBY:
2183 return mUidFirewallStandbyRules;
2184 case FIREWALL_CHAIN_DOZABLE:
2185 return mUidFirewallDozableRules;
Felipe Leme011b98f2016-02-10 17:28:31 -08002186 case FIREWALL_CHAIN_POWERSAVE:
2187 return mUidFirewallPowerSaveRules;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002188 case FIREWALL_CHAIN_NONE:
2189 return mUidFirewallRules;
2190 default:
2191 throw new IllegalArgumentException("Unknown chain:" + chain);
2192 }
2193 }
2194
Luke Huanga241db92018-07-31 20:15:24 +08002195 private int getFirewallRuleType(int chain, int rule) {
Luke Huang615e1022018-10-25 11:54:05 +09002196 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
Remi NGUYEN VANf9a8c2e2019-02-13 18:28:35 +09002197 return getFirewallType(chain) == FIREWALL_WHITELIST
Luke Huang615e1022018-10-25 11:54:05 +09002198 ? INetd.FIREWALL_RULE_DENY : INetd.FIREWALL_RULE_ALLOW;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002199 }
Luke Huang615e1022018-10-25 11:54:05 +09002200 return rule;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002201 }
2202
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07002203 private static void enforceSystemUid() {
2204 final int uid = Binder.getCallingUid();
2205 if (uid != Process.SYSTEM_UID) {
2206 throw new SecurityException("Only available to AID_SYSTEM");
2207 }
2208 }
2209
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002210 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002211 public void registerNetworkActivityListener(INetworkActivityListener listener) {
2212 mNetworkActivityListeners.register(listener);
2213 }
2214
2215 @Override
2216 public void unregisterNetworkActivityListener(INetworkActivityListener listener) {
2217 mNetworkActivityListeners.unregister(listener);
2218 }
2219
2220 @Override
2221 public boolean isNetworkActive() {
2222 synchronized (mNetworkActivityListeners) {
2223 return mNetworkActive || mActiveIdleTimers.isEmpty();
2224 }
2225 }
2226
2227 private void reportNetworkActive() {
2228 final int length = mNetworkActivityListeners.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002229 try {
2230 for (int i = 0; i < length; i++) {
2231 try {
2232 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
Felipe Leme03e689d2016-03-02 16:17:38 -08002233 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002234 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002235 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002236 } finally {
2237 mNetworkActivityListeners.finishBroadcast();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002238 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002239 }
2240
Mattias Falk8b47b362011-08-23 14:15:13 +02002241 /** {@inheritDoc} */
Jeff Sharkey7b4596f2013-02-25 10:55:29 -08002242 @Override
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002243 public void monitor() {
2244 if (mConnector != null) {
2245 mConnector.monitor();
2246 }
2247 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002248
2249 @Override
2250 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002251 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002252
Robert Greenwalt470fd722012-01-18 12:51:15 -08002253 pw.println("NetworkManagementService NativeDaemonConnector Log:");
2254 mConnector.dump(fd, pw, args);
2255 pw.println();
2256
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07002257 pw.print("mMobileActivityFromRadio="); pw.print(mMobileActivityFromRadio);
2258 pw.print(" mLastPowerStateFromRadio="); pw.println(mLastPowerStateFromRadio);
2259 pw.print("mNetworkActive="); pw.println(mNetworkActive);
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002260
2261 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07002262 pw.print("Active quota ifaces: "); pw.println(mActiveQuotas.toString());
2263 pw.print("Active alert ifaces: "); pw.println(mActiveAlerts.toString());
Felipe Leme65be3022016-03-22 14:53:13 -07002264 pw.print("Data saver mode: "); pw.println(mDataSaverMode);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002265 synchronized (mRulesLock) {
2266 dumpUidRuleOnQuotaLocked(pw, "blacklist", mUidRejectOnMetered);
2267 dumpUidRuleOnQuotaLocked(pw, "whitelist", mUidAllowOnMetered);
2268 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002269 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002270
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002271 synchronized (mRulesLock) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002272 dumpUidFirewallRule(pw, "", mUidFirewallRules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002273
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002274 pw.print("UID firewall standby chain enabled: "); pw.println(
2275 getFirewallChainState(FIREWALL_CHAIN_STANDBY));
Felipe Leme011b98f2016-02-10 17:28:31 -08002276 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_STANDBY, mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002277
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002278 pw.print("UID firewall dozable chain enabled: "); pw.println(
2279 getFirewallChainState(FIREWALL_CHAIN_DOZABLE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002280 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_DOZABLE, mUidFirewallDozableRules);
Felipe Leme011b98f2016-02-10 17:28:31 -08002281
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002282 pw.println("UID firewall powersave chain enabled: " +
2283 getFirewallChainState(FIREWALL_CHAIN_POWERSAVE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002284 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_POWERSAVE, mUidFirewallPowerSaveRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002285 }
2286
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002287 synchronized (mIdleTimerLock) {
2288 pw.println("Idle timers:");
2289 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
2290 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
2291 IdleTimerParams params = ent.getValue();
2292 pw.print(" timeout="); pw.print(params.timeout);
2293 pw.print(" type="); pw.print(params.type);
2294 pw.print(" networkCount="); pw.println(params.networkCount);
2295 }
2296 }
2297
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002298 pw.print("Firewall enabled: "); pw.println(mFirewallEnabled);
Felipe Leme65be3022016-03-22 14:53:13 -07002299 pw.print("Netd service status: " );
2300 if (mNetdService == null) {
2301 pw.println("disconnected");
2302 } else {
2303 try {
2304 final boolean alive = mNetdService.isAlive();
2305 pw.println(alive ? "alive": "dead");
2306 } catch (RemoteException e) {
2307 pw.println("unreachable");
2308 }
2309 }
2310 }
2311
2312 private void dumpUidRuleOnQuotaLocked(PrintWriter pw, String name, SparseBooleanArray list) {
2313 pw.print("UID bandwith control ");
2314 pw.print(name);
2315 pw.print(" rule: [");
2316 final int size = list.size();
2317 for (int i = 0; i < size; i++) {
2318 pw.print(list.keyAt(i));
2319 if (i < size - 1) pw.print(",");
2320 }
2321 pw.println("]");
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002322 }
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002323
Felipe Leme011b98f2016-02-10 17:28:31 -08002324 private void dumpUidFirewallRule(PrintWriter pw, String name, SparseIntArray rules) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002325 pw.print("UID firewall ");
Felipe Leme011b98f2016-02-10 17:28:31 -08002326 pw.print(name);
2327 pw.print(" rule: [");
2328 final int size = rules.size();
2329 for (int i = 0; i < size; i++) {
2330 pw.print(rules.keyAt(i));
2331 pw.print(":");
2332 pw.print(rules.valueAt(i));
2333 if (i < size - 1) pw.print(",");
2334 }
2335 pw.println("]");
2336 }
2337
Robert Greenwalt568891d2014-04-04 13:38:00 -07002338 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002339 public void createPhysicalNetwork(int netId, int permission) {
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002340 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2341
2342 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002343 mNetdService.networkCreatePhysical(netId, permission);
2344 } catch (RemoteException | ServiceSpecificException e) {
2345 throw new IllegalStateException(e);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002346 }
2347 }
2348
Robert Greenwalt568891d2014-04-04 13:38:00 -07002349 @Override
ckenbed368e2018-12-05 20:32:30 +09002350 public void createVirtualNetwork(int netId, boolean secure) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002351 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2352
2353 try {
ckenbed368e2018-12-05 20:32:30 +09002354 mNetdService.networkCreateVpn(netId, secure);
Luke Huang8a462ec2018-08-24 20:33:16 +08002355 } catch (RemoteException | ServiceSpecificException e) {
2356 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002357 }
2358 }
2359
2360 @Override
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002361 public void removeNetwork(int netId) {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002362 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002363
2364 try {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002365 mNetdService.networkDestroy(netId);
2366 } catch (ServiceSpecificException e) {
2367 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2368 throw e;
2369 } catch (RemoteException e) {
2370 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2371 throw e.rethrowAsRuntimeException();
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002372 }
2373 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002374
2375 @Override
Paul Jensen992f2522014-04-28 10:33:11 -04002376 public void addInterfaceToNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002377 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, netId, iface);
Paul Jensen992f2522014-04-28 10:33:11 -04002378 }
2379
2380 @Override
2381 public void removeInterfaceFromNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002382 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, netId, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002383 }
Paul Jensen992f2522014-04-28 10:33:11 -04002384
Luke Huang8a462ec2018-08-24 20:33:16 +08002385 private void modifyInterfaceInNetwork(boolean add, int netId, String iface) {
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002386 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Paul Jensen992f2522014-04-28 10:33:11 -04002387 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002388 if (add) {
2389 mNetdService.networkAddInterface(netId, iface);
2390 } else {
2391 mNetdService.networkRemoveInterface(netId, iface);
2392 }
2393 } catch (RemoteException | ServiceSpecificException e) {
2394 throw new IllegalStateException(e);
Paul Jensen992f2522014-04-28 10:33:11 -04002395 }
2396 }
2397
2398 @Override
Robert Greenwalt913c8952014-04-07 17:36:35 -07002399 public void addLegacyRouteForNetId(int netId, RouteInfo routeInfo, int uid) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002400 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2401
Sreeram Ramachandrancc91c7b2014-06-03 18:41:43 -07002402 final LinkAddress la = routeInfo.getDestinationLinkAddress();
Luke Huang8a462ec2018-08-24 20:33:16 +08002403 final String ifName = routeInfo.getInterface();
2404 final String dst = la.toString();
2405 final String nextHop;
Robert Greenwalt568891d2014-04-04 13:38:00 -07002406
Luke Huang8a462ec2018-08-24 20:33:16 +08002407 if (routeInfo.hasGateway()) {
2408 nextHop = routeInfo.getGateway().getHostAddress();
2409 } else {
2410 nextHop = "";
2411 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002412 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002413 mNetdService.networkAddLegacyRoute(netId, ifName, dst, nextHop, uid);
2414 } catch (RemoteException | ServiceSpecificException e) {
2415 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002416 }
2417 }
2418
2419 @Override
Sreeram Ramachandranf047f2a2014-04-15 16:04:26 -07002420 public void setDefaultNetId(int netId) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002421 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2422
2423 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002424 mNetdService.networkSetDefault(netId);
2425 } catch (RemoteException | ServiceSpecificException e) {
2426 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002427 }
2428 }
2429
2430 @Override
2431 public void clearDefaultNetId() {
2432 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2433
2434 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002435 mNetdService.networkClearDefault();
2436 } catch (RemoteException | ServiceSpecificException e) {
2437 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002438 }
2439 }
2440
2441 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002442 public void setNetworkPermission(int netId, int permission) {
Paul Jensen487ffe72015-07-24 15:57:11 -04002443 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2444
2445 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002446 mNetdService.networkSetPermissionForNetwork(netId, permission);
2447 } catch (RemoteException | ServiceSpecificException e) {
2448 throw new IllegalStateException(e);
Paul Jensen487ffe72015-07-24 15:57:11 -04002449 }
2450 }
2451
Luke Huang8a462ec2018-08-24 20:33:16 +08002452 private int parsePermission(String permission) {
2453 if (permission.equals("NETWORK")) {
2454 return INetd.PERMISSION_NETWORK;
2455 }
2456 if (permission.equals("SYSTEM")) {
2457 return INetd.PERMISSION_SYSTEM;
2458 }
2459 return INetd.PERMISSION_NONE;
2460 }
Paul Jensen487ffe72015-07-24 15:57:11 -04002461
2462 @Override
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002463 public void setPermission(String permission, int[] uids) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002464 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2465
Luke Huang8a462ec2018-08-24 20:33:16 +08002466 try {
2467 mNetdService.networkSetPermissionForUser(parsePermission(permission), uids);
2468 } catch (RemoteException | ServiceSpecificException e) {
2469 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002470 }
2471 }
2472
2473 @Override
2474 public void clearPermission(int[] uids) {
2475 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2476
Luke Huang8a462ec2018-08-24 20:33:16 +08002477 try {
2478 mNetdService.networkClearPermissionForUser(uids);
2479 } catch (RemoteException | ServiceSpecificException e) {
2480 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002481 }
2482 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002483
2484 @Override
2485 public void allowProtect(int uid) {
2486 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2487
2488 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002489 mNetdService.networkSetProtectAllow(uid);
2490 } catch (RemoteException | ServiceSpecificException e) {
2491 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002492 }
2493 }
2494
2495 @Override
2496 public void denyProtect(int uid) {
2497 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2498
2499 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002500 mNetdService.networkSetProtectDeny(uid);
2501 } catch (RemoteException | ServiceSpecificException e) {
2502 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002503 }
2504 }
2505
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002506 @Override
2507 public void addInterfaceToLocalNetwork(String iface, List<RouteInfo> routes) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002508 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002509
2510 for (RouteInfo route : routes) {
2511 if (!route.isDefaultRoute()) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002512 modifyRoute(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID, route);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002513 }
2514 }
2515 }
2516
2517 @Override
2518 public void removeInterfaceFromLocalNetwork(String iface) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002519 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, INetd.LOCAL_NET_ID, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002520 }
Erik Kline6599ee82016-07-17 21:28:39 +09002521
2522 @Override
2523 public int removeRoutesFromLocalNetwork(List<RouteInfo> routes) {
2524 int failures = 0;
2525
2526 for (RouteInfo route : routes) {
2527 try {
Luke Huang706d7ab2018-10-16 15:42:15 +08002528 modifyRoute(MODIFY_OPERATION_REMOVE, INetd.LOCAL_NET_ID, route);
Erik Kline6599ee82016-07-17 21:28:39 +09002529 } catch (IllegalStateException e) {
2530 failures++;
2531 }
2532 }
2533
2534 return failures;
2535 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002536
Sudheer Shankab8f23162017-08-04 13:30:10 -07002537 @Override
2538 public boolean isNetworkRestricted(int uid) {
2539 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2540 return isNetworkRestrictedInternal(uid);
2541 }
2542
2543 private boolean isNetworkRestrictedInternal(int uid) {
2544 synchronized (mRulesLock) {
2545 if (getFirewallChainState(FIREWALL_CHAIN_STANDBY)
2546 && mUidFirewallStandbyRules.get(uid) == FIREWALL_RULE_DENY) {
2547 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of app standby mode");
2548 return true;
2549 }
2550 if (getFirewallChainState(FIREWALL_CHAIN_DOZABLE)
2551 && mUidFirewallDozableRules.get(uid) != FIREWALL_RULE_ALLOW) {
2552 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of device idle mode");
2553 return true;
2554 }
2555 if (getFirewallChainState(FIREWALL_CHAIN_POWERSAVE)
2556 && mUidFirewallPowerSaveRules.get(uid) != FIREWALL_RULE_ALLOW) {
2557 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of power saver mode");
2558 return true;
2559 }
2560 if (mUidRejectOnMetered.get(uid)) {
2561 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of no metered data"
2562 + " in the background");
2563 return true;
2564 }
2565 if (mDataSaverMode && !mUidAllowOnMetered.get(uid)) {
2566 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of data saver mode");
2567 return true;
2568 }
2569 return false;
2570 }
2571 }
2572
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002573 private void setFirewallChainState(int chain, boolean state) {
2574 synchronized (mRulesLock) {
2575 mFirewallChainStates.put(chain, state);
2576 }
2577 }
2578
2579 private boolean getFirewallChainState(int chain) {
2580 synchronized (mRulesLock) {
2581 return mFirewallChainStates.get(chain);
2582 }
2583 }
2584
2585 @VisibleForTesting
2586 class LocalService extends NetworkManagementInternal {
2587 @Override
2588 public boolean isNetworkRestrictedForUid(int uid) {
Sudheer Shankab8f23162017-08-04 13:30:10 -07002589 return isNetworkRestrictedInternal(uid);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002590 }
2591 }
2592
2593 @VisibleForTesting
2594 Injector getInjector() {
2595 return new Injector();
2596 }
2597
2598 @VisibleForTesting
2599 class Injector {
2600 void setDataSaverMode(boolean dataSaverMode) {
2601 mDataSaverMode = dataSaverMode;
2602 }
2603
2604 void setFirewallChainState(int chain, boolean state) {
2605 NetworkManagementService.this.setFirewallChainState(chain, state);
2606 }
2607
2608 void setFirewallRule(int chain, int uid, int rule) {
2609 synchronized (mRulesLock) {
2610 getUidFirewallRulesLR(chain).put(uid, rule);
2611 }
2612 }
2613
2614 void setUidOnMeteredNetworkList(boolean blacklist, int uid, boolean enable) {
2615 synchronized (mRulesLock) {
2616 if (blacklist) {
2617 mUidRejectOnMetered.put(uid, enable);
2618 } else {
2619 mUidAllowOnMetered.put(uid, enable);
2620 }
2621 }
2622 }
2623
2624 void reset() {
2625 synchronized (mRulesLock) {
2626 setDataSaverMode(false);
2627 final int[] chains = {
2628 FIREWALL_CHAIN_DOZABLE,
2629 FIREWALL_CHAIN_STANDBY,
2630 FIREWALL_CHAIN_POWERSAVE
2631 };
2632 for (int chain : chains) {
2633 setFirewallChainState(chain, false);
2634 getUidFirewallRulesLR(chain).clear();
2635 }
2636 mUidAllowOnMetered.clear();
2637 mUidRejectOnMetered.clear();
2638 }
2639 }
2640 }
San Mehat873f2142010-01-14 10:25:07 -08002641}