blob: abc6ec7e5a3b3177ece0953172d6d39f4ee80a7b [file] [log] [blame]
San Mehat873f2142010-01-14 10:25:07 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey4529bb62011-12-14 10:31:54 -080019import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Sehee Parka9139bc2017-12-22 13:54:05 +090020import static android.Manifest.permission.NETWORK_SETTINGS;
Lorenzo Colitti07f13042017-07-10 19:06:57 +090021import static android.Manifest.permission.NETWORK_STACK;
Jeff Sharkeyaf75c332011-11-18 12:41:12 -080022import static android.Manifest.permission.SHUTDOWN;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070023import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
24import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080025import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070026import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_STANDBY;
27import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NONE;
Felipe Leme011b98f2016-02-10 17:28:31 -080028import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070029import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
Sudheer Shanka62f5c172017-03-17 16:25:55 -070030import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070031import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Sudheer Shanka62f5c172017-03-17 16:25:55 -070032import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070033import static android.net.NetworkPolicyManager.FIREWALL_TYPE_BLACKLIST;
34import static android.net.NetworkPolicyManager.FIREWALL_TYPE_WHITELIST;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -070035import static android.net.NetworkStats.SET_DEFAULT;
Lorenzo Colittif1912ca2017-08-17 19:23:08 +090036import static android.net.NetworkStats.STATS_PER_UID;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080037import static android.net.NetworkStats.TAG_ALL;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070038import static android.net.NetworkStats.TAG_NONE;
39import static android.net.NetworkStats.UID_ALL;
Jeff Sharkeyae2c1812011-10-04 13:11:40 -070040import static android.net.TrafficStats.UID_TETHERING;
Lorenzo Colitti9307ca22019-01-12 01:54:23 +090041
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;
Luke Huangd290dd52018-09-04 17:08:18 +080049import android.net.InetAddresses;
Lorenzo Colitti58967ba2016-02-02 17:21:21 +090050import android.net.INetd;
Luke Huangd290dd52018-09-04 17:08:18 +080051import android.net.INetdUnsolicitedEventListener;
San Mehat4d02d002010-01-22 16:07:46 -080052import android.net.INetworkManagementEventObserver;
Lorenzo Colitti07f13042017-07-10 19:06:57 +090053import android.net.ITetheringStatsProvider;
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;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +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;
San Mehat873f2142010-01-14 10:25:07 -080087
Jeff Sharkey605eb792014-11-04 13:34:06 -080088import com.android.internal.annotations.GuardedBy;
Sudheer Shanka62f5c172017-03-17 16:25:55 -070089import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070090import com.android.internal.app.IBatteryStats;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -070091import com.android.internal.net.NetworkStatsFactory;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060092import com.android.internal.util.DumpUtils;
Jeff Sharkey605eb792014-11-04 13:34:06 -080093import com.android.internal.util.HexDump;
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -070094import com.android.internal.util.Preconditions;
Lorenzo Colitti9307ca22019-01-12 01:54:23 +090095
Jeff Sharkeyb24a7852012-05-01 15:19:37 -070096import com.google.android.collect.Maps;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070097
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070098import java.io.BufferedReader;
99import java.io.DataInputStream;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700100import java.io.FileDescriptor;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700101import java.io.FileInputStream;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700102import java.io.IOException;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700103import java.io.InputStreamReader;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700104import java.io.PrintWriter;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700105import java.net.InetAddress;
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700106import java.net.InterfaceAddress;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700107import java.util.ArrayList;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400108import java.util.Arrays;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700109import java.util.HashMap;
jiaguo1da35f72014-01-09 16:39:59 +0800110import java.util.List;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700111import java.util.Map;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700112import java.util.concurrent.CountDownLatch;
San Mehat873f2142010-01-14 10:25:07 -0800113
114/**
115 * @hide
116 */
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700117public class NetworkManagementService extends INetworkManagementService.Stub
118 implements Watchdog.Monitor {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900119
120 /**
121 * Helper class that encapsulates NetworkManagementService dependencies and makes them
122 * easier to mock in unit tests.
123 */
124 static class SystemServices {
125 public IBinder getService(String name) {
126 return ServiceManager.getService(name);
127 }
128 public void registerLocalService(NetworkManagementInternal nmi) {
129 LocalServices.addService(NetworkManagementInternal.class, nmi);
130 }
131 public INetd getNetd() {
132 return NetdService.get();
133 }
134 }
135
Amith Yamasani15e472352015-04-24 19:06:07 -0700136 private static final String TAG = "NetworkManagement";
137 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Kenny Root305bcbf2010-09-03 07:56:38 -0700138 private static final String NETD_TAG = "NetdConnector";
Lorenzo Colittia0868002017-07-11 02:29:28 +0900139 static final String NETD_SERVICE_NAME = "netd";
Kenny Root305bcbf2010-09-03 07:56:38 -0700140
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400141 private static final int MAX_UID_RANGES_PER_COMMAND = 10;
142
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700143 /**
144 * Name representing {@link #setGlobalAlert(long)} limit when delivered to
145 * {@link INetworkManagementEventObserver#limitReached(String, String)}.
146 */
147 public static final String LIMIT_GLOBAL_ALERT = "globalAlert";
148
Andrew Scull45f533c2017-05-19 15:37:20 +0100149 static class NetdResponseCode {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -0700150 /* Keep in sync with system/netd/server/ResponseCode.h */
San Mehat873f2142010-01-14 10:25:07 -0800151 public static final int InterfaceListResult = 110;
152 public static final int TetherInterfaceListResult = 111;
153 public static final int TetherDnsFwdTgtListResult = 112;
San Mehat72759df2010-01-19 13:50:37 -0800154 public static final int TtyListResult = 113;
Jeff Sharkeye4984be2013-09-10 21:03:27 -0700155 public static final int TetheringStatsListResult = 114;
San Mehat873f2142010-01-14 10:25:07 -0800156
157 public static final int TetherStatusResult = 210;
158 public static final int IpFwdStatusResult = 211;
San Mehated4fc8a2010-01-22 12:28:36 -0800159 public static final int InterfaceGetCfgResult = 213;
Robert Greenwalte3253922010-02-18 09:23:25 -0800160 public static final int SoftapStatusResult = 214;
San Mehat91cac642010-03-31 14:31:36 -0700161 public static final int InterfaceRxCounterResult = 216;
162 public static final int InterfaceTxCounterResult = 217;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700163 public static final int QuotaCounterResult = 220;
164 public static final int TetheringStatsResult = 221;
Selim Gurun84c00c62012-02-27 15:42:38 -0800165 public static final int DnsProxyQueryResult = 222;
Lorenzo Colitti79751842013-02-28 16:16:03 +0900166 public static final int ClatdStatusResult = 223;
Robert Greenwalte3253922010-02-18 09:23:25 -0800167
168 public static final int InterfaceChange = 600;
JP Abgrall12b933d2011-07-14 18:09:22 -0700169 public static final int BandwidthControl = 601;
Haoyu Bai6b7358d2012-07-17 16:36:50 -0700170 public static final int InterfaceClassActivity = 613;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900171 public static final int InterfaceAddressChange = 614;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900172 public static final int InterfaceDnsServerInfo = 615;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900173 public static final int RouteChange = 616;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800174 public static final int StrictCleartext = 617;
San Mehat873f2142010-01-14 10:25:07 -0800175 }
176
Rebecca Silbersteine2ec94f2016-03-24 13:29:00 -0700177 /**
178 * String indicating a softap command.
179 */
180 static final String SOFT_AP_COMMAND = "softap";
181
182 /**
183 * String passed back to netd connector indicating softap command success.
184 */
185 static final String SOFT_AP_COMMAND_SUCCESS = "Ok";
186
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700187 static final int DAEMON_MSG_MOBILE_CONN_REAL_TIME_INFO = 1;
188
Luke Huang8a462ec2018-08-24 20:33:16 +0800189 static final boolean MODIFY_OPERATION_ADD = true;
190 static final boolean MODIFY_OPERATION_REMOVE = false;
191
San Mehat873f2142010-01-14 10:25:07 -0800192 /**
193 * Binder context for this service
194 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700195 private final Context mContext;
San Mehat873f2142010-01-14 10:25:07 -0800196
197 /**
198 * connector object for communicating with netd
199 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700200 private final NativeDaemonConnector mConnector;
San Mehat873f2142010-01-14 10:25:07 -0800201
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700202 private final Handler mFgHandler;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700203 private final Handler mDaemonHandler;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700204
Lorenzo Colittia0868002017-07-11 02:29:28 +0900205 private final SystemServices mServices;
206
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900207 private INetd mNetdService;
208
Luke Huangd290dd52018-09-04 17:08:18 +0800209 private final NetdUnsolicitedEventListener mNetdUnsolicitedEventListener;
210
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800211 private IBatteryStats mBatteryStats;
212
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700213 private final Thread mThread;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700214 private CountDownLatch mConnectedSignal = new CountDownLatch(1);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700215
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800216 private final RemoteCallbackList<INetworkManagementEventObserver> mObservers =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700217 new RemoteCallbackList<>();
San Mehat4d02d002010-01-22 16:07:46 -0800218
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700219 private final NetworkStatsFactory mStatsFactory = new NetworkStatsFactory();
220
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900221 @GuardedBy("mTetheringStatsProviders")
222 private final HashMap<ITetheringStatsProvider, String>
223 mTetheringStatsProviders = Maps.newHashMap();
224
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700225 /**
226 * If both locks need to be held, then they should be obtained in the order:
227 * first {@link #mQuotaLock} and then {@link #mRulesLock}.
228 */
Andrew Scull45f533c2017-05-19 15:37:20 +0100229 private final Object mQuotaLock = new Object();
Andrew Scull519291f2017-05-23 13:11:03 +0100230 private final Object mRulesLock = new Object();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800231
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700232 /** Set of interfaces with active quotas. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800233 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700234 private HashMap<String, Long> mActiveQuotas = Maps.newHashMap();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700235 /** Set of interfaces with active alerts. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800236 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700237 private HashMap<String, Long> mActiveAlerts = Maps.newHashMap();
Felipe Leme65be3022016-03-22 14:53:13 -0700238 /** Set of UIDs blacklisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700239 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700240 private SparseBooleanArray mUidRejectOnMetered = new SparseBooleanArray();
241 /** Set of UIDs whitelisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700242 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700243 private SparseBooleanArray mUidAllowOnMetered = new SparseBooleanArray();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800244 /** Set of UIDs with cleartext penalties. */
245 @GuardedBy("mQuotaLock")
246 private SparseIntArray mUidCleartextPolicy = new SparseIntArray();
Amith Yamasani15e472352015-04-24 19:06:07 -0700247 /** Set of UIDs that are to be blocked/allowed by firewall controller. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700248 @GuardedBy("mRulesLock")
Amith Yamasani15e472352015-04-24 19:06:07 -0700249 private SparseIntArray mUidFirewallRules = new SparseIntArray();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700250 /**
251 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
252 * to application idles.
253 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700254 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700255 private SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
256 /**
257 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
258 * to device idles.
259 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700260 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700261 private SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800262 /**
263 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
264 * to device on power-save mode.
265 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700266 @GuardedBy("mRulesLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800267 private SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700268 /** Set of states for the child firewall chains. True if the chain is active. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700269 @GuardedBy("mRulesLock")
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700270 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700271
Felipe Leme65be3022016-03-22 14:53:13 -0700272 @GuardedBy("mQuotaLock")
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700273 private volatile boolean mDataSaverMode;
Felipe Leme65be3022016-03-22 14:53:13 -0700274
Andrew Scull45f533c2017-05-19 15:37:20 +0100275 private final Object mIdleTimerLock = new Object();
Haoyu Bai04124232012-06-28 15:26:19 -0700276 /** Set of interfaces with active idle timers. */
277 private static class IdleTimerParams {
278 public final int timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800279 public final int type;
Haoyu Bai04124232012-06-28 15:26:19 -0700280 public int networkCount;
281
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800282 IdleTimerParams(int timeout, int type) {
Haoyu Bai04124232012-06-28 15:26:19 -0700283 this.timeout = timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800284 this.type = type;
Haoyu Bai04124232012-06-28 15:26:19 -0700285 this.networkCount = 1;
286 }
287 }
288 private HashMap<String, IdleTimerParams> mActiveIdleTimers = Maps.newHashMap();
289
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700290 private volatile boolean mFirewallEnabled;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800291 private volatile boolean mStrictEnabled;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700292
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700293 private boolean mMobileActivityFromRadio = false;
294 private int mLastPowerStateFromRadio = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Adam Lesinskie08af192015-03-25 16:42:59 -0700295 private int mLastPowerStateFromWifi = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700296
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800297 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700298 new RemoteCallbackList<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800299 private boolean mNetworkActive;
300
San Mehat873f2142010-01-14 10:25:07 -0800301 /**
302 * Constructs a new NetworkManagementService instance
303 *
304 * @param context Binder context for this service
305 */
Lorenzo Colittia0868002017-07-11 02:29:28 +0900306 private NetworkManagementService(
307 Context context, String socket, SystemServices services) {
San Mehat873f2142010-01-14 10:25:07 -0800308 mContext = context;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900309 mServices = services;
San Mehat4d02d002010-01-22 16:07:46 -0800310
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700311 // make sure this is on the same looper as our NativeDaemonConnector for sync purposes
312 mFgHandler = new Handler(FgThread.get().getLooper());
313
Dianne Hackborn4590e522014-03-24 13:36:46 -0700314 // Don't need this wake lock, since we now have a time stamp for when
315 // the network actually went inactive. (It might be nice to still do this,
316 // but I don't want to do it through the power manager because that pollutes the
317 // battery stats history with pointless noise.)
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700318 //PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
Dianne Hackborn4590e522014-03-24 13:36:46 -0700319 PowerManager.WakeLock wl = null; //pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NETD_TAG);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800320
San Mehat873f2142010-01-14 10:25:07 -0800321 mConnector = new NativeDaemonConnector(
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700322 new NetdCallbackReceiver(), socket, 10, NETD_TAG, 160, wl,
323 FgThread.get().getLooper());
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700324 mThread = new Thread(mConnector, NETD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700325
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700326 mDaemonHandler = new Handler(FgThread.get().getLooper());
Wink Saville67e07892014-06-18 16:43:14 -0700327
Luke Huangd290dd52018-09-04 17:08:18 +0800328 mNetdUnsolicitedEventListener = new NetdUnsolicitedEventListener();
329
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700330 // Add ourself to the Watchdog monitors.
331 Watchdog.getInstance().addMonitor(this);
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700332
Lorenzo Colittia0868002017-07-11 02:29:28 +0900333 mServices.registerLocalService(new LocalService());
Lorenzo Colitti8228eb32017-07-19 06:17:33 +0900334
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900335 synchronized (mTetheringStatsProviders) {
336 mTetheringStatsProviders.put(new NetdTetheringStatsProvider(), "netd");
337 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700338 }
339
340 @VisibleForTesting
341 NetworkManagementService() {
342 mConnector = null;
343 mContext = null;
344 mDaemonHandler = null;
345 mFgHandler = null;
346 mThread = null;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900347 mServices = null;
Luke Huangd290dd52018-09-04 17:08:18 +0800348 mNetdUnsolicitedEventListener = null;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700349 }
350
Lorenzo Colittia0868002017-07-11 02:29:28 +0900351 static NetworkManagementService create(Context context, String socket, SystemServices services)
Felipe Leme03e689d2016-03-02 16:17:38 -0800352 throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900353 final NetworkManagementService service =
354 new NetworkManagementService(context, socket, services);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700355 final CountDownLatch connectedSignal = service.mConnectedSignal;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700356 if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
357 service.mThread.start();
358 if (DBG) Slog.d(TAG, "Awaiting socket connection");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700359 connectedSignal.await();
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700360 if (DBG) Slog.d(TAG, "Connected");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900361 if (DBG) Slog.d(TAG, "Connecting native netd service");
bohu07cc3bb2016-05-03 15:58:01 -0700362 service.connectNativeNetdService();
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900363 if (DBG) Slog.d(TAG, "Connected");
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700364 return service;
San Mehat873f2142010-01-14 10:25:07 -0800365 }
366
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900367 public static NetworkManagementService create(Context context) throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900368 return create(context, NETD_SERVICE_NAME, new SystemServices());
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900369 }
370
Jeff Sharkey350083e2011-06-29 10:45:16 -0700371 public void systemReady() {
Felipe Leme03e689d2016-03-02 16:17:38 -0800372 if (DBG) {
373 final long start = System.currentTimeMillis();
374 prepareNativeDaemon();
375 final long delta = System.currentTimeMillis() - start;
376 Slog.d(TAG, "Prepared in " + delta + "ms");
377 return;
378 } else {
379 prepareNativeDaemon();
380 }
Jeff Sharkey350083e2011-06-29 10:45:16 -0700381 }
382
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800383 private IBatteryStats getBatteryStats() {
384 synchronized (this) {
385 if (mBatteryStats != null) {
386 return mBatteryStats;
387 }
Lorenzo Colittia0868002017-07-11 02:29:28 +0900388 mBatteryStats =
389 IBatteryStats.Stub.asInterface(mServices.getService(BatteryStats.SERVICE_NAME));
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800390 return mBatteryStats;
391 }
392 }
393
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800394 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800395 public void registerObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800396 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800397 mObservers.register(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800398 }
399
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800400 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800401 public void unregisterObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800402 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800403 mObservers.unregister(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800404 }
405
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900406 @FunctionalInterface
407 private interface NetworkManagementEventCallback {
408 public void sendCallback(INetworkManagementEventObserver o) throws RemoteException;
409 }
410
411 private void invokeForAllObservers(NetworkManagementEventCallback eventCallback) {
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800412 final int length = mObservers.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700413 try {
414 for (int i = 0; i < length; i++) {
415 try {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900416 eventCallback.sendCallback(mObservers.getBroadcastItem(i));
Felipe Leme03e689d2016-03-02 16:17:38 -0800417 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700418 }
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700419 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700420 } finally {
421 mObservers.finishBroadcast();
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700422 }
423 }
424
425 /**
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900426 * Notify our observers of an interface status change
427 */
428 private void notifyInterfaceStatusChanged(String iface, boolean up) {
429 invokeForAllObservers(o -> o.interfaceStatusChanged(iface, up));
430 }
431
432 /**
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700433 * Notify our observers of an interface link state change
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700434 * (typically, an Ethernet cable has been plugged-in or unplugged).
435 */
436 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900437 invokeForAllObservers(o -> o.interfaceLinkStateChanged(iface, up));
San Mehat4d02d002010-01-22 16:07:46 -0800438 }
439
440 /**
441 * Notify our observers of an interface addition.
442 */
443 private void notifyInterfaceAdded(String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900444 invokeForAllObservers(o -> o.interfaceAdded(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800445 }
446
447 /**
448 * Notify our observers of an interface removal.
449 */
450 private void notifyInterfaceRemoved(String iface) {
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700451 // netd already clears out quota and alerts for removed ifaces; update
452 // our sanity-checking state.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700453 mActiveAlerts.remove(iface);
454 mActiveQuotas.remove(iface);
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900455 invokeForAllObservers(o -> o.interfaceRemoved(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800456 }
457
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700458 /**
JP Abgrall12b933d2011-07-14 18:09:22 -0700459 * Notify our observers of a limit reached.
460 */
461 private void notifyLimitReached(String limitName, String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900462 invokeForAllObservers(o -> o.limitReached(limitName, iface));
JP Abgrall12b933d2011-07-14 18:09:22 -0700463 }
464
465 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700466 * Notify our observers of a change in the data activity state of the interface
467 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700468 private void notifyInterfaceClassActivity(int type, int powerState, long tsNanos,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700469 int uid, boolean fromRadio) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700470 final boolean isMobile = ConnectivityManager.isNetworkTypeMobile(type);
471 if (isMobile) {
472 if (!fromRadio) {
473 if (mMobileActivityFromRadio) {
474 // If this call is not coming from a report from the radio itself, but we
475 // have previously received reports from the radio, then we will take the
476 // power state to just be whatever the radio last reported.
477 powerState = mLastPowerStateFromRadio;
478 }
479 } else {
480 mMobileActivityFromRadio = true;
481 }
482 if (mLastPowerStateFromRadio != powerState) {
483 mLastPowerStateFromRadio = powerState;
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700484 try {
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700485 getBatteryStats().noteMobileRadioPowerState(powerState, tsNanos, uid);
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700486 } catch (RemoteException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700487 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700488 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700489 }
490
Adam Lesinskie08af192015-03-25 16:42:59 -0700491 if (ConnectivityManager.isNetworkTypeWifi(type)) {
492 if (mLastPowerStateFromWifi != powerState) {
493 mLastPowerStateFromWifi = powerState;
494 try {
Adam Lesinski5f056f62016-07-14 16:56:08 -0700495 getBatteryStats().noteWifiRadioPowerState(powerState, tsNanos, uid);
Adam Lesinskie08af192015-03-25 16:42:59 -0700496 } catch (RemoteException e) {
497 }
498 }
499 }
500
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700501 boolean isActive = powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
502 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
503
504 if (!isMobile || fromRadio || !mMobileActivityFromRadio) {
505 // Report the change in data activity. We don't do this if this is a change
506 // on the mobile network, that is not coming from the radio itself, and we
507 // have previously seen change reports from the radio. In that case only
508 // the radio is the authority for the current state.
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900509 final boolean active = isActive;
510 invokeForAllObservers(o -> o.interfaceClassDataActivityChanged(
511 Integer.toString(type), active, tsNanos));
Haoyu Baidb3c8672012-06-20 14:29:57 -0700512 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800513
514 boolean report = false;
515 synchronized (mIdleTimerLock) {
516 if (mActiveIdleTimers.isEmpty()) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700517 // If there are no idle timers, we are not monitoring activity, so we
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800518 // are always considered active.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700519 isActive = true;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800520 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700521 if (mNetworkActive != isActive) {
522 mNetworkActive = isActive;
523 report = isActive;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800524 }
525 }
526 if (report) {
527 reportNetworkActive();
528 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700529 }
530
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900531 @Override
532 public void registerTetheringStatsProvider(ITetheringStatsProvider provider, String name) {
533 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
534 Preconditions.checkNotNull(provider);
535 synchronized(mTetheringStatsProviders) {
536 mTetheringStatsProviders.put(provider, name);
537 }
538 }
539
540 @Override
541 public void unregisterTetheringStatsProvider(ITetheringStatsProvider provider) {
542 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
543 synchronized(mTetheringStatsProviders) {
544 mTetheringStatsProviders.remove(provider);
545 }
546 }
547
Lorenzo Colitti9f0baa92017-08-15 19:25:51 +0900548 @Override
549 public void tetherLimitReached(ITetheringStatsProvider provider) {
550 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
551 synchronized(mTetheringStatsProviders) {
552 if (!mTetheringStatsProviders.containsKey(provider)) {
553 return;
554 }
555 // No current code examines the interface parameter in a global alert. Just pass null.
Luke Huangd290dd52018-09-04 17:08:18 +0800556 mDaemonHandler.post(() -> notifyLimitReached(LIMIT_GLOBAL_ALERT, null));
Lorenzo Colitti9f0baa92017-08-15 19:25:51 +0900557 }
558 }
559
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900560 // Sync the state of the given chain with the native daemon.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700561 private void syncFirewallChainLocked(int chain, String name) {
562 SparseIntArray rules;
563 synchronized (mRulesLock) {
564 final SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900565 // Make a copy of the current rules, and then clear them. This is because
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700566 // setFirewallUidRuleInternal only pushes down rules to the native daemon if they
567 // are different from the current rules stored in the mUidFirewall*Rules array for
568 // the specified chain. If we don't clear the rules, setFirewallUidRuleInternal
569 // will do nothing.
570 rules = uidFirewallRules.clone();
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900571 uidFirewallRules.clear();
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700572 }
573 if (rules.size() > 0) {
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900574 // Now push the rules. setFirewallUidRuleInternal will push each of these down to the
575 // native daemon, and also add them to the mUidFirewall*Rules array for the specified
576 // chain.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700577 if (DBG) Slog.d(TAG, "Pushing " + rules.size() + " active firewall "
578 + name + "UID rules");
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900579 for (int i = 0; i < rules.size(); i++) {
Felipe Lemea701cad2016-05-12 09:58:14 -0700580 setFirewallUidRuleLocked(chain, rules.keyAt(i), rules.valueAt(i));
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900581 }
582 }
583 }
584
bohu07cc3bb2016-05-03 15:58:01 -0700585 private void connectNativeNetdService() {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900586 mNetdService = mServices.getNetd();
Luke Huangd290dd52018-09-04 17:08:18 +0800587 try {
588 mNetdService.registerUnsolicitedEventListener(mNetdUnsolicitedEventListener);
589 if (DBG) Slog.d(TAG, "Register unsolicited event listener");
590 } catch (RemoteException | ServiceSpecificException e) {
591 Slog.e(TAG, "Failed to set Netd unsolicited event listener " + e);
592 }
bohu07cc3bb2016-05-03 15:58:01 -0700593 }
594
595 /**
596 * Prepare native daemon once connected, enabling modules and pushing any
597 * existing in-memory rules.
598 */
599 private void prepareNativeDaemon() {
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900600
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700601 // push any existing quota or UID rules
602 synchronized (mQuotaLock) {
Felipe Leme65be3022016-03-22 14:53:13 -0700603
Luke Huang56a03a02018-09-07 12:02:16 +0800604 // Netd unconditionally enable bandwidth control
605 SystemProperties.set(PROP_QTAGUID_ENABLED, "1");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900606
Luke Huang473eb872018-07-26 17:33:14 +0800607 mStrictEnabled = true;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900608
Felipe Leme65be3022016-03-22 14:53:13 -0700609 setDataSaverModeEnabled(mDataSaverMode);
610
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700611 int size = mActiveQuotas.size();
612 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800613 if (DBG) Slog.d(TAG, "Pushing " + size + " active quota rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700614 final HashMap<String, Long> activeQuotas = mActiveQuotas;
615 mActiveQuotas = Maps.newHashMap();
616 for (Map.Entry<String, Long> entry : activeQuotas.entrySet()) {
617 setInterfaceQuota(entry.getKey(), entry.getValue());
618 }
619 }
620
621 size = mActiveAlerts.size();
622 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800623 if (DBG) Slog.d(TAG, "Pushing " + size + " active alert rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700624 final HashMap<String, Long> activeAlerts = mActiveAlerts;
625 mActiveAlerts = Maps.newHashMap();
626 for (Map.Entry<String, Long> entry : activeAlerts.entrySet()) {
627 setInterfaceAlert(entry.getKey(), entry.getValue());
628 }
629 }
630
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700631 SparseBooleanArray uidRejectOnQuota = null;
632 SparseBooleanArray uidAcceptOnQuota = null;
633 synchronized (mRulesLock) {
634 size = mUidRejectOnMetered.size();
635 if (size > 0) {
636 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered blacklist rules");
637 uidRejectOnQuota = mUidRejectOnMetered;
638 mUidRejectOnMetered = new SparseBooleanArray();
639 }
640
641 size = mUidAllowOnMetered.size();
642 if (size > 0) {
643 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered whitelist rules");
644 uidAcceptOnQuota = mUidAllowOnMetered;
645 mUidAllowOnMetered = new SparseBooleanArray();
646 }
647 }
648 if (uidRejectOnQuota != null) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700649 for (int i = 0; i < uidRejectOnQuota.size(); i++) {
Felipe Leme65be3022016-03-22 14:53:13 -0700650 setUidMeteredNetworkBlacklist(uidRejectOnQuota.keyAt(i),
651 uidRejectOnQuota.valueAt(i));
652 }
653 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700654 if (uidAcceptOnQuota != null) {
Felipe Leme65be3022016-03-22 14:53:13 -0700655 for (int i = 0; i < uidAcceptOnQuota.size(); i++) {
656 setUidMeteredNetworkWhitelist(uidAcceptOnQuota.keyAt(i),
657 uidAcceptOnQuota.valueAt(i));
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700658 }
659 }
Jeff Sharkey605eb792014-11-04 13:34:06 -0800660
661 size = mUidCleartextPolicy.size();
662 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800663 if (DBG) Slog.d(TAG, "Pushing " + size + " active UID cleartext policies");
Jeff Sharkey605eb792014-11-04 13:34:06 -0800664 final SparseIntArray local = mUidCleartextPolicy;
665 mUidCleartextPolicy = new SparseIntArray();
666 for (int i = 0; i < local.size(); i++) {
667 setUidCleartextNetworkPolicy(local.keyAt(i), local.valueAt(i));
668 }
669 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700670
Robin Leec3736bc2017-03-10 16:19:54 +0000671 setFirewallEnabled(mFirewallEnabled);
Amith Yamasani15e472352015-04-24 19:06:07 -0700672
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700673 syncFirewallChainLocked(FIREWALL_CHAIN_NONE, "");
674 syncFirewallChainLocked(FIREWALL_CHAIN_STANDBY, "standby ");
675 syncFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, "dozable ");
676 syncFirewallChainLocked(FIREWALL_CHAIN_POWERSAVE, "powersave ");
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700677
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700678 final int[] chains =
679 {FIREWALL_CHAIN_STANDBY, FIREWALL_CHAIN_DOZABLE, FIREWALL_CHAIN_POWERSAVE};
680 for (int chain : chains) {
681 if (getFirewallChainState(chain)) {
682 setFirewallChainEnabled(chain, true);
683 }
Felipe Leme011b98f2016-02-10 17:28:31 -0800684 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700685 }
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900686
Luke Huang56a03a02018-09-07 12:02:16 +0800687
688 try {
689 getBatteryStats().noteNetworkStatsEnabled();
690 } catch (RemoteException e) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900691 }
692
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700693 }
San Mehat4d02d002010-01-22 16:07:46 -0800694
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900695 /**
696 * Notify our observers of a new or updated interface address.
697 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900698 private void notifyAddressUpdated(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900699 invokeForAllObservers(o -> o.addressUpdated(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900700 }
701
702 /**
703 * Notify our observers of a deleted interface address.
704 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900705 private void notifyAddressRemoved(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900706 invokeForAllObservers(o -> o.addressRemoved(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900707 }
708
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900709 /**
710 * Notify our observers of DNS server information received.
711 */
712 private void notifyInterfaceDnsServerInfo(String iface, long lifetime, String[] addresses) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900713 invokeForAllObservers(o -> o.interfaceDnsServerInfo(iface, lifetime, addresses));
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900714 }
715
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900716 /**
717 * Notify our observers of a route change.
718 */
Luke Huangd290dd52018-09-04 17:08:18 +0800719 private void notifyRouteChange(boolean updated, RouteInfo route) {
720 if (updated) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900721 invokeForAllObservers(o -> o.routeUpdated(route));
722 } else {
723 invokeForAllObservers(o -> o.routeRemoved(route));
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900724 }
725 }
726
Luke Huangd290dd52018-09-04 17:08:18 +0800727 private class NetdUnsolicitedEventListener extends INetdUnsolicitedEventListener.Stub {
728 @Override
729 public void onInterfaceClassActivityChanged(boolean isActive,
730 int label, long timestamp, int uid) throws RemoteException {
731 final long timestampNanos;
732 if (timestamp <= 0) {
733 timestampNanos = SystemClock.elapsedRealtimeNanos();
734 } else {
735 timestampNanos = timestamp;
736 }
737 mDaemonHandler.post(() -> notifyInterfaceClassActivity(label,
738 isActive ? DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH
739 : DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
740 timestampNanos, uid, false));
741 }
742
743 @Override
744 public void onQuotaLimitReached(String alertName, String ifName)
745 throws RemoteException {
746 mDaemonHandler.post(() -> notifyLimitReached(alertName, ifName));
747 }
748
749 @Override
750 public void onInterfaceDnsServerInfo(String ifName,
751 long lifetime, String[] servers) throws RemoteException {
752 mDaemonHandler.post(() -> notifyInterfaceDnsServerInfo(ifName, lifetime, servers));
753 }
754
755 @Override
756 public void onInterfaceAddressUpdated(String addr,
757 String ifName, int flags, int scope) throws RemoteException {
758 final LinkAddress address = new LinkAddress(addr, flags, scope);
759 mDaemonHandler.post(() -> notifyAddressUpdated(ifName, address));
760 }
761
762 @Override
763 public void onInterfaceAddressRemoved(String addr,
764 String ifName, int flags, int scope) throws RemoteException {
765 final LinkAddress address = new LinkAddress(addr, flags, scope);
766 mDaemonHandler.post(() -> notifyAddressRemoved(ifName, address));
767 }
768
769 @Override
770 public void onInterfaceAdded(String ifName) throws RemoteException {
771 mDaemonHandler.post(() -> notifyInterfaceAdded(ifName));
772 }
773
774 @Override
775 public void onInterfaceRemoved(String ifName) throws RemoteException {
776 mDaemonHandler.post(() -> notifyInterfaceRemoved(ifName));
777 }
778
779 @Override
780 public void onInterfaceChanged(String ifName, boolean up)
781 throws RemoteException {
782 mDaemonHandler.post(() -> notifyInterfaceStatusChanged(ifName, up));
783 }
784
785 @Override
786 public void onInterfaceLinkStateChanged(String ifName, boolean up)
787 throws RemoteException {
788 mDaemonHandler.post(() -> notifyInterfaceLinkStateChanged(ifName, up));
789 }
790
791 @Override
792 public void onRouteChanged(boolean updated,
793 String route, String gateway, String ifName) throws RemoteException {
794 final RouteInfo processRoute = new RouteInfo(new IpPrefix(route),
795 ("".equals(gateway)) ? null : InetAddresses.parseNumericAddress(gateway),
796 ifName);
797 mDaemonHandler.post(() -> notifyRouteChange(updated, processRoute));
798 }
799
800 @Override
801 public void onStrictCleartextDetected(int uid, String hex) throws RemoteException {
802 // Don't need to post to mDaemonHandler because the only thing
803 // that notifyCleartextNetwork does is post to a handler
804 ActivityManager.getService().notifyCleartextNetwork(uid,
805 HexDump.hexStringToByteArray(hex));
806 }
807 }
808
San Mehat873f2142010-01-14 10:25:07 -0800809 //
810 // Netd Callback handling
811 //
812
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700813 private class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
814 @Override
San Mehat873f2142010-01-14 10:25:07 -0800815 public void onDaemonConnected() {
Felipe Leme65be3022016-03-22 14:53:13 -0700816 Slog.i(TAG, "onDaemonConnected()");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700817 // event is dispatched from internal NDC thread, so we prepare the
818 // daemon back on main thread.
819 if (mConnectedSignal != null) {
bohu07cc3bb2016-05-03 15:58:01 -0700820 // The system is booting and we're connecting to netd for the first time.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700821 mConnectedSignal.countDown();
822 mConnectedSignal = null;
823 } else {
bohu07cc3bb2016-05-03 15:58:01 -0700824 // We're reconnecting to netd after the socket connection
825 // was interrupted (e.g., if it crashed).
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700826 mFgHandler.post(new Runnable() {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700827 @Override
828 public void run() {
bohu07cc3bb2016-05-03 15:58:01 -0700829 connectNativeNetdService();
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700830 prepareNativeDaemon();
831 }
832 });
833 }
San Mehat873f2142010-01-14 10:25:07 -0800834 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700835
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700836 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800837 public boolean onCheckHoldWakeLock(int code) {
838 return code == NetdResponseCode.InterfaceClassActivity;
839 }
840
841 @Override
San Mehat873f2142010-01-14 10:25:07 -0800842 public boolean onEvent(int code, String raw, String[] cooked) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900843 String errorMessage = String.format("Invalid event from daemon (%s)", raw);
JP Abgrall12b933d2011-07-14 18:09:22 -0700844 switch (code) {
845 case NetdResponseCode.InterfaceChange:
846 /*
847 * a network interface change occured
848 * Format: "NNN Iface added <name>"
849 * "NNN Iface removed <name>"
850 * "NNN Iface changed <name> <up/down>"
851 * "NNN Iface linkstatus <name> <up/down>"
852 */
853 if (cooked.length < 4 || !cooked[1].equals("Iface")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900854 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700855 }
856 if (cooked[2].equals("added")) {
857 notifyInterfaceAdded(cooked[3]);
858 return true;
859 } else if (cooked[2].equals("removed")) {
860 notifyInterfaceRemoved(cooked[3]);
861 return true;
862 } else if (cooked[2].equals("changed") && cooked.length == 5) {
863 notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
864 return true;
865 } else if (cooked[2].equals("linkstate") && cooked.length == 5) {
866 notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
867 return true;
868 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900869 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700870 // break;
871 case NetdResponseCode.BandwidthControl:
872 /*
873 * Bandwidth control needs some attention
874 * Format: "NNN limit alert <alertName> <ifaceName>"
875 */
876 if (cooked.length < 5 || !cooked[1].equals("limit")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900877 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700878 }
879 if (cooked[2].equals("alert")) {
880 notifyLimitReached(cooked[3], cooked[4]);
881 return true;
882 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900883 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700884 // break;
Haoyu Baidb3c8672012-06-20 14:29:57 -0700885 case NetdResponseCode.InterfaceClassActivity:
886 /*
887 * An network interface class state changed (active/idle)
888 * Format: "NNN IfaceClass <active/idle> <label>"
889 */
890 if (cooked.length < 4 || !cooked[1].equals("IfaceClass")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900891 throw new IllegalStateException(errorMessage);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700892 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700893 long timestampNanos = 0;
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700894 int processUid = -1;
895 if (cooked.length >= 5) {
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700896 try {
897 timestampNanos = Long.parseLong(cooked[4]);
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700898 if (cooked.length == 6) {
899 processUid = Integer.parseInt(cooked[5]);
900 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700901 } catch(NumberFormatException ne) {}
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700902 } else {
903 timestampNanos = SystemClock.elapsedRealtimeNanos();
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700904 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700905 boolean isActive = cooked[2].equals("active");
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700906 notifyInterfaceClassActivity(Integer.parseInt(cooked[3]),
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700907 isActive ? DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700908 : DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
909 timestampNanos, processUid, false);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700910 return true;
911 // break;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900912 case NetdResponseCode.InterfaceAddressChange:
913 /*
914 * A network address change occurred
915 * Format: "NNN Address updated <addr> <iface> <flags> <scope>"
916 * "NNN Address removed <addr> <iface> <flags> <scope>"
917 */
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900918 if (cooked.length < 7 || !cooked[1].equals("Address")) {
919 throw new IllegalStateException(errorMessage);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900920 }
921
Lorenzo Colitti64483942013-11-15 18:43:52 +0900922 String iface = cooked[4];
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900923 LinkAddress address;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900924 try {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900925 int flags = Integer.parseInt(cooked[5]);
926 int scope = Integer.parseInt(cooked[6]);
927 address = new LinkAddress(cooked[3], flags, scope);
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900928 } catch(NumberFormatException e) { // Non-numeric lifetime or scope.
929 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti64483942013-11-15 18:43:52 +0900930 } catch(IllegalArgumentException e) { // Malformed/invalid IP address.
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900931 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900932 }
933
934 if (cooked[2].equals("updated")) {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900935 notifyAddressUpdated(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900936 } else {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900937 notifyAddressRemoved(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900938 }
939 return true;
940 // break;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900941 case NetdResponseCode.InterfaceDnsServerInfo:
942 /*
943 * Information about available DNS servers has been received.
944 * Format: "NNN DnsInfo servers <interface> <lifetime> <servers>"
945 */
946 long lifetime; // Actually a 32-bit unsigned integer.
947
948 if (cooked.length == 6 &&
949 cooked[1].equals("DnsInfo") &&
950 cooked[2].equals("servers")) {
951 try {
952 lifetime = Long.parseLong(cooked[4]);
953 } catch (NumberFormatException e) {
954 throw new IllegalStateException(errorMessage);
955 }
956 String[] servers = cooked[5].split(",");
957 notifyInterfaceDnsServerInfo(cooked[3], lifetime, servers);
958 }
959 return true;
960 // break;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900961 case NetdResponseCode.RouteChange:
962 /*
963 * A route has been updated or removed.
964 * Format: "NNN Route <updated|removed> <dst> [via <gateway] [dev <iface>]"
965 */
966 if (!cooked[1].equals("Route") || cooked.length < 6) {
967 throw new IllegalStateException(errorMessage);
968 }
969
970 String via = null;
971 String dev = null;
972 boolean valid = true;
973 for (int i = 4; (i + 1) < cooked.length && valid; i += 2) {
974 if (cooked[i].equals("dev")) {
975 if (dev == null) {
976 dev = cooked[i+1];
977 } else {
978 valid = false; // Duplicate interface.
979 }
980 } else if (cooked[i].equals("via")) {
981 if (via == null) {
982 via = cooked[i+1];
983 } else {
984 valid = false; // Duplicate gateway.
985 }
986 } else {
987 valid = false; // Unknown syntax.
988 }
989 }
990 if (valid) {
991 try {
992 // InetAddress.parseNumericAddress(null) inexplicably returns ::1.
993 InetAddress gateway = null;
994 if (via != null) gateway = InetAddress.parseNumericAddress(via);
995 RouteInfo route = new RouteInfo(new IpPrefix(cooked[3]), gateway, dev);
Luke Huangd290dd52018-09-04 17:08:18 +0800996 notifyRouteChange(cooked[2].equals("updated"), route);
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900997 return true;
998 } catch (IllegalArgumentException e) {}
999 }
1000 throw new IllegalStateException(errorMessage);
1001 // break;
Jeff Sharkey605eb792014-11-04 13:34:06 -08001002 case NetdResponseCode.StrictCleartext:
1003 final int uid = Integer.parseInt(cooked[1]);
1004 final byte[] firstPacket = HexDump.hexStringToByteArray(cooked[2]);
1005 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001006 ActivityManager.getService().notifyCleartextNetwork(uid, firstPacket);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001007 } catch (RemoteException ignored) {
1008 }
1009 break;
JP Abgrall12b933d2011-07-14 18:09:22 -07001010 default: break;
Robert Greenwalte3253922010-02-18 09:23:25 -08001011 }
1012 return false;
San Mehat873f2142010-01-14 10:25:07 -08001013 }
1014 }
1015
San Mehated4fc8a2010-01-22 12:28:36 -08001016
San Mehat873f2142010-01-14 10:25:07 -08001017 //
1018 // INetworkManagementService members
1019 //
Erik Kline4e37b702016-07-05 11:34:21 +09001020 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001021 public String[] listInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001022 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001023 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +08001024 return mNetdService.interfaceGetList();
Luke Huang14f75442018-08-15 19:22:54 +08001025 } catch (RemoteException | ServiceSpecificException e) {
1026 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001027 }
San Mehated4fc8a2010-01-22 12:28:36 -08001028 }
1029
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001030 @Override
1031 public InterfaceConfiguration getInterfaceConfig(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001032 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang14f75442018-08-15 19:22:54 +08001033 final InterfaceConfigurationParcel result;
Kenny Roota80ce062010-06-01 13:23:53 -07001034 try {
Luke Huang14f75442018-08-15 19:22:54 +08001035 result = mNetdService.interfaceGetCfg(iface);
1036 } catch (RemoteException | ServiceSpecificException e) {
1037 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001038 }
San Mehated4fc8a2010-01-22 12:28:36 -08001039
San Mehated4fc8a2010-01-22 12:28:36 -08001040 try {
Luke Huang14f75442018-08-15 19:22:54 +08001041 final InterfaceConfiguration cfg = InterfaceConfiguration.fromParcel(result);
1042 return cfg;
1043 } catch (IllegalArgumentException iae) {
1044 throw new IllegalStateException("Invalid InterfaceConfigurationParcel", iae);
San Mehated4fc8a2010-01-22 12:28:36 -08001045 }
San Mehated4fc8a2010-01-22 12:28:36 -08001046 }
1047
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001048 @Override
1049 public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001050 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001051 LinkAddress linkAddr = cfg.getLinkAddress();
Robert Greenwalt2d2afd12011-02-01 15:30:46 -08001052 if (linkAddr == null || linkAddr.getAddress() == null) {
1053 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -08001054 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001055
Luke Huang14f75442018-08-15 19:22:54 +08001056 final InterfaceConfigurationParcel cfgParcel = cfg.toParcel(iface);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001057
Kenny Roota80ce062010-06-01 13:23:53 -07001058 try {
Luke Huang14f75442018-08-15 19:22:54 +08001059 mNetdService.interfaceSetCfg(cfgParcel);
1060 } catch (RemoteException | ServiceSpecificException e) {
1061 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001062 }
San Mehat873f2142010-01-14 10:25:07 -08001063 }
1064
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001065 @Override
1066 public void setInterfaceDown(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001067 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001068 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001069 ifcg.setInterfaceDown();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001070 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001071 }
1072
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001073 @Override
1074 public void setInterfaceUp(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001075 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001076 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001077 ifcg.setInterfaceUp();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001078 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001079 }
1080
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001081 @Override
1082 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001083 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sheriff73293612011-09-14 12:31:56 -07001084 try {
Luke Huang14f75442018-08-15 19:22:54 +08001085 mNetdService.interfaceSetIPv6PrivacyExtensions(iface, enable);
1086 } catch (RemoteException | ServiceSpecificException e) {
1087 throw new IllegalStateException(e);
Irfan Sheriff73293612011-09-14 12:31:56 -07001088 }
1089 }
1090
Irfan Sherifff5600612011-06-16 10:26:28 -07001091 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
1092 IPv6 addresses on interface down, but we need to do full clean up here */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001093 @Override
1094 public void clearInterfaceAddresses(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001095 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sherifff5600612011-06-16 10:26:28 -07001096 try {
Luke Huang14f75442018-08-15 19:22:54 +08001097 mNetdService.interfaceClearAddrs(iface);
1098 } catch (RemoteException | ServiceSpecificException e) {
1099 throw new IllegalStateException(e);
Irfan Sherifff5600612011-06-16 10:26:28 -07001100 }
1101 }
1102
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001103 @Override
1104 public void enableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001105 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001106 try {
Luke Huang14f75442018-08-15 19:22:54 +08001107 mNetdService.interfaceSetEnableIPv6(iface, true);
1108 } catch (RemoteException | ServiceSpecificException e) {
1109 throw new IllegalStateException(e);
repo sync7960d9f2011-09-29 12:40:02 -07001110 }
1111 }
1112
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001113 @Override
Joel Scherpelz2db10742017-06-07 15:38:38 +09001114 public void setIPv6AddrGenMode(String iface, int mode) throws ServiceSpecificException {
1115 try {
1116 mNetdService.setIPv6AddrGenMode(iface, mode);
1117 } catch (RemoteException e) {
1118 throw e.rethrowAsRuntimeException();
1119 }
1120 }
1121
1122 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001123 public void disableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001124 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001125 try {
Luke Huang14f75442018-08-15 19:22:54 +08001126 mNetdService.interfaceSetEnableIPv6(iface, false);
1127 } catch (RemoteException | ServiceSpecificException e) {
1128 throw new IllegalStateException(e);
repo sync7960d9f2011-09-29 12:40:02 -07001129 }
1130 }
1131
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001132 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001133 public void addRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001134 modifyRoute(MODIFY_OPERATION_ADD, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001135 }
1136
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001137 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001138 public void removeRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001139 modifyRoute(MODIFY_OPERATION_REMOVE, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001140 }
1141
Luke Huang8a462ec2018-08-24 20:33:16 +08001142 private void modifyRoute(boolean add, int netId, RouteInfo route) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001143 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001144
Luke Huang8a462ec2018-08-24 20:33:16 +08001145 final String ifName = route.getInterface();
1146 final String dst = route.getDestination().toString();
1147 final String nextHop;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001148
1149 switch (route.getType()) {
1150 case RouteInfo.RTN_UNICAST:
1151 if (route.hasGateway()) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001152 nextHop = route.getGateway().getHostAddress();
1153 } else {
1154 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001155 }
1156 break;
1157 case RouteInfo.RTN_UNREACHABLE:
Luke Huang8a462ec2018-08-24 20:33:16 +08001158 nextHop = INetd.NEXTHOP_UNREACHABLE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001159 break;
1160 case RouteInfo.RTN_THROW:
Luke Huang8a462ec2018-08-24 20:33:16 +08001161 nextHop = INetd.NEXTHOP_THROW;
1162 break;
1163 default:
1164 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001165 break;
Sreeram Ramachandran1fbcb272014-05-22 16:30:48 -07001166 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001167 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08001168 if (add) {
1169 mNetdService.networkAddRoute(netId, ifName, dst, nextHop);
1170 } else {
1171 mNetdService.networkRemoveRoute(netId, ifName, dst, nextHop);
1172 }
1173 } catch (RemoteException | ServiceSpecificException e) {
1174 throw new IllegalStateException(e);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001175 }
1176 }
1177
1178 private ArrayList<String> readRouteList(String filename) {
1179 FileInputStream fstream = null;
Christopher Wiley212b95f2016-08-02 11:38:57 -07001180 ArrayList<String> list = new ArrayList<>();
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001181
1182 try {
1183 fstream = new FileInputStream(filename);
1184 DataInputStream in = new DataInputStream(fstream);
1185 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1186 String s;
1187
1188 // throw away the title line
1189
1190 while (((s = br.readLine()) != null) && (s.length() != 0)) {
1191 list.add(s);
1192 }
1193 } catch (IOException ex) {
1194 // return current list, possibly empty
1195 } finally {
1196 if (fstream != null) {
1197 try {
1198 fstream.close();
1199 } catch (IOException ex) {}
1200 }
1201 }
1202
1203 return list;
1204 }
1205
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001206 @Override
sy.yun9d9b74a2013-09-02 05:24:09 +09001207 public void setMtu(String iface, int mtu) {
1208 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1209
sy.yun9d9b74a2013-09-02 05:24:09 +09001210 try {
Luke Huang14f75442018-08-15 19:22:54 +08001211 mNetdService.interfaceSetMtu(iface, mtu);
1212 } catch (RemoteException | ServiceSpecificException e) {
1213 throw new IllegalStateException(e);
sy.yun9d9b74a2013-09-02 05:24:09 +09001214 }
1215 }
1216
1217 @Override
San Mehat873f2142010-01-14 10:25:07 -08001218 public void shutdown() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001219 // TODO: remove from aidl if nobody calls externally
1220 mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001221
Felipe Leme03e689d2016-03-02 16:17:38 -08001222 Slog.i(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -08001223 }
1224
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001225 @Override
San Mehat873f2142010-01-14 10:25:07 -08001226 public boolean getIpForwardingEnabled() throws IllegalStateException{
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001227 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001228
Kenny Roota80ce062010-06-01 13:23:53 -07001229 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001230 final boolean isEnabled = mNetdService.ipfwdEnabled();
1231 return isEnabled;
1232 } catch (RemoteException | ServiceSpecificException e) {
1233 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001234 }
San Mehat873f2142010-01-14 10:25:07 -08001235 }
1236
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001237 @Override
1238 public void setIpForwardingEnabled(boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001239 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001240 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001241 if (enable) {
1242 mNetdService.ipfwdEnableForwarding("tethering");
1243 } else {
1244 mNetdService.ipfwdDisableForwarding("tethering");
1245 }
1246 } catch (RemoteException | ServiceSpecificException e) {
1247 throw new IllegalStateException(e);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001248 }
San Mehat873f2142010-01-14 10:25:07 -08001249 }
1250
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001251 @Override
1252 public void startTethering(String[] dhcpRange) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001253 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -07001254 // an odd number of addrs will fail
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001255
Kenny Roota80ce062010-06-01 13:23:53 -07001256 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001257 mNetdService.tetherStart(dhcpRange);
1258 } catch (RemoteException | ServiceSpecificException e) {
1259 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001260 }
San Mehat873f2142010-01-14 10:25:07 -08001261 }
1262
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001263 @Override
1264 public void stopTethering() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001265 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001266 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001267 mNetdService.tetherStop();
1268 } catch (RemoteException | ServiceSpecificException e) {
1269 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001270 }
San Mehat873f2142010-01-14 10:25:07 -08001271 }
1272
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001273 @Override
1274 public boolean isTetheringStarted() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001275 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001276
Kenny Roota80ce062010-06-01 13:23:53 -07001277 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001278 final boolean isEnabled = mNetdService.tetherIsEnabled();
1279 return isEnabled;
1280 } catch (RemoteException | ServiceSpecificException e) {
1281 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001282 }
San Mehat873f2142010-01-14 10:25:07 -08001283 }
Matthew Xiefe19f122012-07-12 16:03:32 -07001284
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001285 @Override
1286 public void tetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001287 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001288 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001289 mNetdService.tetherInterfaceAdd(iface);
1290 } catch (RemoteException | ServiceSpecificException e) {
1291 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001292 }
Christopher Wiley212b95f2016-08-02 11:38:57 -07001293 List<RouteInfo> routes = new ArrayList<>();
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07001294 // The RouteInfo constructor truncates the LinkAddress to a network prefix, thus making it
1295 // suitable to use as a route destination.
1296 routes.add(new RouteInfo(getInterfaceConfig(iface).getLinkAddress(), null, iface));
1297 addInterfaceToLocalNetwork(iface, routes);
San Mehat873f2142010-01-14 10:25:07 -08001298 }
1299
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001300 @Override
San Mehat873f2142010-01-14 10:25:07 -08001301 public void untetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001302 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001303 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001304 mNetdService.tetherInterfaceRemove(iface);
1305 } catch (RemoteException | ServiceSpecificException e) {
1306 throw new IllegalStateException(e);
Erik Kline1f4278a2016-08-16 16:46:33 +09001307 } finally {
1308 removeInterfaceFromLocalNetwork(iface);
Kenny Roota80ce062010-06-01 13:23:53 -07001309 }
San Mehat873f2142010-01-14 10:25:07 -08001310 }
1311
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001312 @Override
1313 public String[] listTetheredInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001314 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001315 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +08001316 return mNetdService.tetherInterfaceList();
Luke Huang4a32bf42018-08-21 19:09:45 +08001317 } catch (RemoteException | ServiceSpecificException e) {
1318 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001319 }
San Mehat873f2142010-01-14 10:25:07 -08001320 }
1321
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001322 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001323 public void setDnsForwarders(Network network, String[] dns) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001324 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001325
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001326 int netId = (network != null) ? network.netId : ConnectivityManager.NETID_UNSET;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001327
San Mehat873f2142010-01-14 10:25:07 -08001328 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001329 mNetdService.tetherDnsSet(netId, dns);
1330 } catch (RemoteException | ServiceSpecificException e) {
1331 throw new IllegalStateException(e);
San Mehat873f2142010-01-14 10:25:07 -08001332 }
1333 }
1334
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001335 @Override
1336 public String[] getDnsForwarders() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001337 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001338 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +08001339 return mNetdService.tetherDnsList();
Luke Huang4a32bf42018-08-21 19:09:45 +08001340 } catch (RemoteException | ServiceSpecificException e) {
1341 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001342 }
San Mehat873f2142010-01-14 10:25:07 -08001343 }
1344
jiaguo1da35f72014-01-09 16:39:59 +08001345 private List<InterfaceAddress> excludeLinkLocal(List<InterfaceAddress> addresses) {
Christopher Wiley212b95f2016-08-02 11:38:57 -07001346 ArrayList<InterfaceAddress> filtered = new ArrayList<>(addresses.size());
jiaguo1da35f72014-01-09 16:39:59 +08001347 for (InterfaceAddress ia : addresses) {
1348 if (!ia.getAddress().isLinkLocalAddress())
1349 filtered.add(ia);
1350 }
1351 return filtered;
1352 }
1353
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001354 private void modifyInterfaceForward(boolean add, String fromIface, String toIface) {
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001355 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001356 if (add) {
1357 mNetdService.ipfwdAddInterfaceForward(fromIface, toIface);
1358 } else {
1359 mNetdService.ipfwdRemoveInterfaceForward(fromIface, toIface);
1360 }
1361 } catch (RemoteException | ServiceSpecificException e) {
1362 throw new IllegalStateException(e);
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001363 }
1364 }
1365
1366 @Override
1367 public void startInterfaceForwarding(String fromIface, String toIface) {
1368 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1369 modifyInterfaceForward(true, fromIface, toIface);
1370 }
1371
1372 @Override
1373 public void stopInterfaceForwarding(String fromIface, String toIface) {
1374 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1375 modifyInterfaceForward(false, fromIface, toIface);
1376 }
1377
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001378 @Override
1379 public void enableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001380 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001381 try {
Luke Huanga31e0732018-10-22 13:23:10 +09001382 mNetdService.tetherAddForward(internalInterface, externalInterface);
1383 } catch (RemoteException | ServiceSpecificException e) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001384 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001385 }
San Mehat873f2142010-01-14 10:25:07 -08001386 }
1387
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001388 @Override
1389 public void disableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001390 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001391 try {
Luke Huanga31e0732018-10-22 13:23:10 +09001392 mNetdService.tetherRemoveForward(internalInterface, externalInterface);
1393 } catch (RemoteException | ServiceSpecificException e) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001394 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001395 }
San Mehat873f2142010-01-14 10:25:07 -08001396 }
San Mehat72759df2010-01-19 13:50:37 -08001397
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001398 @Override
1399 public String[] listTtys() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001400 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001401 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001402 return NativeDaemonEvent.filterMessageList(
1403 mConnector.executeForList("list_ttys"), TtyListResult);
Kenny Roota80ce062010-06-01 13:23:53 -07001404 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001405 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001406 }
San Mehat72759df2010-01-19 13:50:37 -08001407 }
1408
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001409 @Override
1410 public void attachPppd(
1411 String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001412 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat72759df2010-01-19 13:50:37 -08001413 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001414 mConnector.execute("pppd", "attach", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -08001415 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
1416 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
1417 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001418 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress());
Kenny Roota80ce062010-06-01 13:23:53 -07001419 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001420 throw e.rethrowAsParcelableException();
San Mehat72759df2010-01-19 13:50:37 -08001421 }
1422 }
1423
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001424 @Override
1425 public void detachPppd(String tty) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001426 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001427 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001428 mConnector.execute("pppd", "detach", tty);
Kenny Roota80ce062010-06-01 13:23:53 -07001429 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001430 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001431 }
San Mehat72759df2010-01-19 13:50:37 -08001432 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -08001433
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001434 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001435 public void addIdleTimer(String iface, int timeout, final int type) {
Haoyu Bai04124232012-06-28 15:26:19 -07001436 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1437
1438 if (DBG) Slog.d(TAG, "Adding idletimer");
1439
1440 synchronized (mIdleTimerLock) {
1441 IdleTimerParams params = mActiveIdleTimers.get(iface);
1442 if (params != null) {
1443 // the interface already has idletimer, update network count
1444 params.networkCount++;
1445 return;
1446 }
1447
1448 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001449 mNetdService.idletimerAddInterface(iface, timeout, Integer.toString(type));
1450 } catch (RemoteException | ServiceSpecificException e) {
1451 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001452 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001453 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
1454
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001455 // Networks start up.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001456 if (ConnectivityManager.isNetworkTypeMobile(type)) {
1457 mNetworkActive = false;
1458 }
Luke Huangd290dd52018-09-04 17:08:18 +08001459 mDaemonHandler.post(() -> notifyInterfaceClassActivity(type,
1460 DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH,
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);
Luke Huangd290dd52018-09-04 17:08:18 +08001484 mDaemonHandler.post(() -> notifyInterfaceClassActivity(params.type,
1485 DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
1486 SystemClock.elapsedRealtimeNanos(), -1, false));
Haoyu Bai04124232012-06-28 15:26:19 -07001487 }
1488 }
1489
1490 @Override
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001491 public NetworkStats getNetworkStatsSummaryDev() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001492 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001493 try {
1494 return mStatsFactory.readNetworkStatsSummaryDev();
1495 } catch (IOException e) {
1496 throw new IllegalStateException(e);
1497 }
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001498 }
1499
1500 @Override
1501 public NetworkStats getNetworkStatsSummaryXt() {
1502 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001503 try {
1504 return mStatsFactory.readNetworkStatsSummaryXt();
1505 } catch (IOException e) {
1506 throw new IllegalStateException(e);
1507 }
Jeff Sharkeyae2c1812011-10-04 13:11:40 -07001508 }
1509
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001510 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001511 public NetworkStats getNetworkStatsDetail() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001512 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001513 try {
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08001514 return mStatsFactory.readNetworkStatsDetail(UID_ALL, null, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001515 } catch (IOException e) {
1516 throw new IllegalStateException(e);
1517 }
San Mehat91cac642010-03-31 14:31:36 -07001518 }
1519
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001520 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001521 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001522 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001523
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001524 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001525 if (mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001526 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001527 }
1528
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001529 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001530 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001531 mNetdService.bandwidthSetInterfaceQuota(iface, quotaBytes);
1532
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001533 mActiveQuotas.put(iface, quotaBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001534 } catch (RemoteException | ServiceSpecificException e) {
1535 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001536 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001537
1538 synchronized (mTetheringStatsProviders) {
1539 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1540 try {
1541 provider.setInterfaceQuota(iface, quotaBytes);
1542 } catch (RemoteException e) {
1543 Log.e(TAG, "Problem setting tethering data limit on provider " +
1544 mTetheringStatsProviders.get(provider) + ": " + e);
1545 }
1546 }
1547 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001548 }
1549 }
1550
1551 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001552 public void removeInterfaceQuota(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001553 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001554
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001555 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001556 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001557 // TODO: eventually consider throwing
1558 return;
1559 }
1560
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001561 mActiveQuotas.remove(iface);
1562 mActiveAlerts.remove(iface);
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001563
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001564 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001565 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001566 mNetdService.bandwidthRemoveInterfaceQuota(iface);
1567 } catch (RemoteException | ServiceSpecificException e) {
1568 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001569 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001570
1571 synchronized (mTetheringStatsProviders) {
1572 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1573 try {
1574 provider.setInterfaceQuota(iface, ITetheringStatsProvider.QUOTA_UNLIMITED);
1575 } catch (RemoteException e) {
1576 Log.e(TAG, "Problem removing tethering data limit on provider " +
1577 mTetheringStatsProviders.get(provider) + ": " + e);
1578 }
1579 }
1580 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001581 }
1582 }
1583
1584 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001585 public void setInterfaceAlert(String iface, long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001586 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001587
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001588 // quick sanity check
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001589 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001590 throw new IllegalStateException("setting alert requires existing quota on iface");
1591 }
1592
1593 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001594 if (mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001595 throw new IllegalStateException("iface " + iface + " already has alert");
1596 }
1597
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001598 try {
1599 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001600 mNetdService.bandwidthSetInterfaceAlert(iface, alertBytes);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001601 mActiveAlerts.put(iface, alertBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001602 } catch (RemoteException | ServiceSpecificException e) {
1603 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001604 }
1605 }
1606 }
1607
1608 @Override
1609 public void removeInterfaceAlert(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001610 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001611
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001612 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001613 if (!mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001614 // TODO: eventually consider throwing
1615 return;
1616 }
1617
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001618 try {
1619 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001620 mNetdService.bandwidthRemoveInterfaceAlert(iface);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001621 mActiveAlerts.remove(iface);
Luke Huangc7bea8662018-08-07 16:04:26 +08001622 } catch (RemoteException | ServiceSpecificException e) {
1623 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001624 }
1625 }
1626 }
1627
1628 @Override
1629 public void setGlobalAlert(long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001630 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001631
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001632 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001633 mNetdService.bandwidthSetGlobalAlert(alertBytes);
1634 } catch (RemoteException | ServiceSpecificException e) {
1635 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001636 }
1637 }
1638
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001639 private void setUidOnMeteredNetworkList(int uid, boolean blacklist, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001640 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001641
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001642 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001643 boolean oldEnable;
1644 SparseBooleanArray quotaList;
1645 synchronized (mRulesLock) {
1646 quotaList = blacklist ? mUidRejectOnMetered : mUidAllowOnMetered;
1647 oldEnable = quotaList.get(uid, false);
1648 }
Felipe Leme65be3022016-03-22 14:53:13 -07001649 if (oldEnable == enable) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001650 // TODO: eventually consider throwing
1651 return;
1652 }
1653
Felipe Leme29e72ea2016-09-08 13:26:55 -07001654 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "inetd bandwidth");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001655 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001656 if (blacklist) {
1657 if (enable) {
1658 mNetdService.bandwidthAddNaughtyApp(uid);
1659 } else {
1660 mNetdService.bandwidthRemoveNaughtyApp(uid);
1661 }
1662 } else {
1663 if (enable) {
1664 mNetdService.bandwidthAddNiceApp(uid);
1665 } else {
1666 mNetdService.bandwidthRemoveNiceApp(uid);
1667 }
1668 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001669 synchronized (mRulesLock) {
1670 if (enable) {
1671 quotaList.put(uid, true);
1672 } else {
1673 quotaList.delete(uid);
1674 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001675 }
Luke Huangc7bea8662018-08-07 16:04:26 +08001676 } catch (RemoteException | ServiceSpecificException e) {
1677 throw new IllegalStateException(e);
Felipe Leme29e72ea2016-09-08 13:26:55 -07001678 } finally {
1679 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001680 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001681 }
1682 }
1683
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001684 @Override
Felipe Leme65be3022016-03-22 14:53:13 -07001685 public void setUidMeteredNetworkBlacklist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001686 setUidOnMeteredNetworkList(uid, true, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001687 }
1688
1689 @Override
1690 public void setUidMeteredNetworkWhitelist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001691 setUidOnMeteredNetworkList(uid, false, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001692 }
1693
1694 @Override
1695 public boolean setDataSaverModeEnabled(boolean enable) {
Sehee Parka9139bc2017-12-22 13:54:05 +09001696 mContext.enforceCallingOrSelfPermission(NETWORK_SETTINGS, TAG);
1697
Felipe Leme65be3022016-03-22 14:53:13 -07001698 if (DBG) Log.d(TAG, "setDataSaverMode: " + enable);
1699 synchronized (mQuotaLock) {
1700 if (mDataSaverMode == enable) {
1701 Log.w(TAG, "setDataSaverMode(): already " + mDataSaverMode);
1702 return true;
1703 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07001704 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "bandwidthEnableDataSaver");
Felipe Leme65be3022016-03-22 14:53:13 -07001705 try {
1706 final boolean changed = mNetdService.bandwidthEnableDataSaver(enable);
1707 if (changed) {
1708 mDataSaverMode = enable;
1709 } else {
1710 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command silently failed");
1711 }
1712 return changed;
1713 } catch (RemoteException e) {
1714 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command failed", e);
1715 return false;
Felipe Leme29e72ea2016-09-08 13:26:55 -07001716 } finally {
1717 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme65be3022016-03-22 14:53:13 -07001718 }
1719 }
1720 }
1721
1722 @Override
Robin Lee17e61832016-05-09 13:46:28 +01001723 public void setAllowOnlyVpnForUids(boolean add, UidRange[] uidRanges)
1724 throws ServiceSpecificException {
Rubin Xu2ea6c552018-01-11 10:59:19 +00001725 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robin Lee17e61832016-05-09 13:46:28 +01001726 try {
1727 mNetdService.networkRejectNonSecureVpn(add, uidRanges);
1728 } catch (ServiceSpecificException e) {
1729 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1730 + ": netd command failed", e);
1731 throw e;
1732 } catch (RemoteException e) {
1733 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1734 + ": netd command failed", e);
1735 throw e.rethrowAsRuntimeException();
1736 }
1737 }
1738
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001739 private void applyUidCleartextNetworkPolicy(int uid, int policy) {
Luke Huang473eb872018-07-26 17:33:14 +08001740 final int policyValue;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001741 switch (policy) {
1742 case StrictMode.NETWORK_POLICY_ACCEPT:
Luke Huang473eb872018-07-26 17:33:14 +08001743 policyValue = INetd.PENALTY_POLICY_ACCEPT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001744 break;
1745 case StrictMode.NETWORK_POLICY_LOG:
Luke Huang473eb872018-07-26 17:33:14 +08001746 policyValue = INetd.PENALTY_POLICY_LOG;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001747 break;
1748 case StrictMode.NETWORK_POLICY_REJECT:
Luke Huang473eb872018-07-26 17:33:14 +08001749 policyValue = INetd.PENALTY_POLICY_REJECT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001750 break;
1751 default:
1752 throw new IllegalArgumentException("Unknown policy " + policy);
1753 }
1754
1755 try {
Luke Huang473eb872018-07-26 17:33:14 +08001756 mNetdService.strictUidCleartextPenalty(uid, policyValue);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001757 mUidCleartextPolicy.put(uid, policy);
Luke Huang473eb872018-07-26 17:33:14 +08001758 } catch (RemoteException | ServiceSpecificException e) {
1759 throw new IllegalStateException(e);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001760 }
1761 }
1762
Robin Lee17e61832016-05-09 13:46:28 +01001763 @Override
Jeff Sharkey605eb792014-11-04 13:34:06 -08001764 public void setUidCleartextNetworkPolicy(int uid, int policy) {
1765 if (Binder.getCallingUid() != uid) {
1766 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1767 }
1768
1769 synchronized (mQuotaLock) {
1770 final int oldPolicy = mUidCleartextPolicy.get(uid, StrictMode.NETWORK_POLICY_ACCEPT);
1771 if (oldPolicy == policy) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001772 // This also ensures we won't needlessly apply an ACCEPT policy if we've just
1773 // enabled strict and the underlying iptables rules are empty.
Jeff Sharkey605eb792014-11-04 13:34:06 -08001774 return;
1775 }
1776
Luke Huang473eb872018-07-26 17:33:14 +08001777 // TODO: remove this code after removing prepareNativeDaemon()
Jeff Sharkey605eb792014-11-04 13:34:06 -08001778 if (!mStrictEnabled) {
1779 // Module isn't enabled yet; stash the requested policy away to
1780 // apply later once the daemon is connected.
1781 mUidCleartextPolicy.put(uid, policy);
1782 return;
1783 }
1784
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001785 // netd does not keep state on strict mode policies, and cannot replace a non-accept
1786 // policy without deleting it first. Rather than add state to netd, just always send
1787 // it an accept policy when switching between two non-accept policies.
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001788 // TODO: consider keeping state in netd so we can simplify this code.
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001789 if (oldPolicy != StrictMode.NETWORK_POLICY_ACCEPT &&
1790 policy != StrictMode.NETWORK_POLICY_ACCEPT) {
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001791 applyUidCleartextNetworkPolicy(uid, StrictMode.NETWORK_POLICY_ACCEPT);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001792 }
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001793
1794 applyUidCleartextNetworkPolicy(uid, policy);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001795 }
1796 }
1797
1798 @Override
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001799 public boolean isBandwidthControlEnabled() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001800 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang56a03a02018-09-07 12:02:16 +08001801 return true;
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001802 }
1803
1804 @Override
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001805 public NetworkStats getNetworkStatsUidDetail(int uid, String[] ifaces) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001806 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001807 try {
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001808 return mStatsFactory.readNetworkStatsDetail(uid, ifaces, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001809 } catch (IOException e) {
1810 throw new IllegalStateException(e);
1811 }
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001812 }
1813
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001814 private class NetdTetheringStatsProvider extends ITetheringStatsProvider.Stub {
1815 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001816 public NetworkStats getTetherStats(int how) {
1817 // We only need to return per-UID stats. Per-device stats are already counted by
1818 // interface counters.
1819 if (how != STATS_PER_UID) {
1820 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
1821 }
1822
Luke Huang13b79e82018-09-26 14:53:42 +08001823 final TetherStatsParcel[] tetherStatsVec;
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001824 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001825 tetherStatsVec = mNetdService.tetherGetStats();
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001826 } catch (RemoteException | ServiceSpecificException e) {
1827 throw new IllegalStateException("problem parsing tethering stats: ", e);
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001828 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001829
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001830 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(),
Luke Huang13b79e82018-09-26 14:53:42 +08001831 tetherStatsVec.length);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001832 final NetworkStats.Entry entry = new NetworkStats.Entry();
1833
Luke Huang13b79e82018-09-26 14:53:42 +08001834 for (TetherStatsParcel tetherStats : tetherStatsVec) {
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001835 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001836 entry.iface = tetherStats.iface;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001837 entry.uid = UID_TETHERING;
1838 entry.set = SET_DEFAULT;
1839 entry.tag = TAG_NONE;
Luke Huang13b79e82018-09-26 14:53:42 +08001840 entry.rxBytes = tetherStats.rxBytes;
1841 entry.rxPackets = tetherStats.rxPackets;
1842 entry.txBytes = tetherStats.txBytes;
1843 entry.txPackets = tetherStats.txPackets;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001844 stats.combineValues(entry);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001845 } catch (ArrayIndexOutOfBoundsException e) {
Luke Huang13b79e82018-09-26 14:53:42 +08001846 throw new IllegalStateException("invalid tethering stats " + e);
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001847 }
1848 }
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001849
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001850 return stats;
1851 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001852
1853 @Override
1854 public void setInterfaceQuota(String iface, long quotaBytes) {
1855 // Do nothing. netd is already informed of quota changes in setInterfaceQuota.
1856 }
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001857 }
1858
1859 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001860 public NetworkStats getNetworkStatsTethering(int how) {
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001861 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1862
1863 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1864 synchronized (mTetheringStatsProviders) {
1865 for (ITetheringStatsProvider provider: mTetheringStatsProviders.keySet()) {
1866 try {
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001867 stats.combineAllValues(provider.getTetherStats(how));
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001868 } catch (RemoteException e) {
1869 Log.e(TAG, "Problem reading tethering stats from " +
1870 mTetheringStatsProviders.get(provider) + ": " + e);
1871 }
1872 }
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001873 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001874 return stats;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001875 }
1876
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001877 @Override
Erik Kline1742fe12017-12-13 19:40:49 +09001878 public void setDnsConfigurationForNetwork(int netId, String[] servers, String[] domains,
Erik Klinee5dac902018-03-04 21:01:01 +09001879 int[] params, String tlsHostname, String[] tlsServers) {
Pierre Imai8e48e672016-04-21 13:30:43 +09001880 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1881
Ben Schwartz6ec28df2017-10-02 13:08:06 -04001882 final String[] tlsFingerprints = new String[0];
Pierre Imai8e48e672016-04-21 13:30:43 +09001883 try {
Erik Kline1742fe12017-12-13 19:40:49 +09001884 mNetdService.setResolverConfiguration(
Erik Klinee5dac902018-03-04 21:01:01 +09001885 netId, servers, domains, params, tlsHostname, tlsServers, tlsFingerprints);
Pierre Imai8e48e672016-04-21 13:30:43 +09001886 } catch (RemoteException e) {
1887 throw new RuntimeException(e);
1888 }
1889 }
1890
1891 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001892 public void addVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001893 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001894
1895 try {
1896 mNetdService.networkAddUidRanges(netId, ranges);
1897 } catch (RemoteException | ServiceSpecificException e) {
1898 throw new IllegalStateException(e);
Chad Brubaker3277620a2013-06-12 13:37:30 -07001899 }
1900 }
1901
1902 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001903 public void removeVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001904 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001905 try {
1906 mNetdService.networkRemoveUidRanges(netId, ranges);
1907 } catch (RemoteException | ServiceSpecificException e) {
1908 throw new IllegalStateException(e);
Chad Brubakercca54c42013-06-27 17:41:38 -07001909 }
1910 }
1911
1912 @Override
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001913 public void setFirewallEnabled(boolean enabled) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001914 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001915 try {
Luke Huanga241db92018-07-31 20:15:24 +08001916 mNetdService.firewallSetFirewallType(
1917 enabled ? INetd.FIREWALL_WHITELIST : INetd.FIREWALL_BLACKLIST);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001918 mFirewallEnabled = enabled;
Luke Huanga241db92018-07-31 20:15:24 +08001919 } catch (RemoteException | ServiceSpecificException e) {
1920 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001921 }
1922 }
1923
1924 @Override
1925 public boolean isFirewallEnabled() {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001926 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001927 return mFirewallEnabled;
1928 }
1929
1930 @Override
Jeff Sharkey2c092982012-08-24 11:44:40 -07001931 public void setFirewallInterfaceRule(String iface, boolean allow) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001932 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001933 Preconditions.checkState(mFirewallEnabled);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001934 try {
Luke Huanga241db92018-07-31 20:15:24 +08001935 mNetdService.firewallSetInterfaceRule(iface,
1936 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
1937 } catch (RemoteException | ServiceSpecificException e) {
1938 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001939 }
1940 }
1941
Lorenzo Colitti3fef7232016-04-29 18:00:03 +09001942 private void closeSocketsForFirewallChainLocked(int chain, String chainName) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001943 // UID ranges to close sockets on.
1944 UidRange[] ranges;
1945 // UID ranges whose sockets we won't touch.
1946 int[] exemptUids;
1947
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001948 int numUids = 0;
Luke Huanga241db92018-07-31 20:15:24 +08001949 if (DBG) Slog.d(TAG, "Closing sockets after enabling chain " + chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001950 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
1951 // Close all sockets on all non-system UIDs...
1952 ranges = new UidRange[] {
1953 // TODO: is there a better way of finding all existing users? If so, we could
1954 // specify their ranges here.
1955 new UidRange(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE),
1956 };
1957 // ... except for the UIDs that have allow rules.
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001958 synchronized (mRulesLock) {
1959 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1960 exemptUids = new int[rules.size()];
1961 for (int i = 0; i < exemptUids.length; i++) {
1962 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
1963 exemptUids[numUids] = rules.keyAt(i);
1964 numUids++;
1965 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001966 }
1967 }
1968 // Normally, whitelist chains only contain deny rules, so numUids == exemptUids.length.
1969 // But the code does not guarantee this in any way, and at least in one case - if we add
1970 // a UID rule to the firewall, and then disable the firewall - the chains can contain
1971 // the wrong type of rule. In this case, don't close connections that we shouldn't.
1972 //
1973 // TODO: tighten up this code by ensuring we never set the wrong type of rule, and
1974 // fix setFirewallEnabled to grab mQuotaLock and clear rules.
1975 if (numUids != exemptUids.length) {
1976 exemptUids = Arrays.copyOf(exemptUids, numUids);
1977 }
1978 } else {
1979 // Close sockets for every UID that has a deny rule...
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001980 synchronized (mRulesLock) {
1981 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1982 ranges = new UidRange[rules.size()];
1983 for (int i = 0; i < ranges.length; i++) {
1984 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_DENY) {
1985 int uid = rules.keyAt(i);
1986 ranges[numUids] = new UidRange(uid, uid);
1987 numUids++;
1988 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001989 }
1990 }
1991 // As above; usually numUids == ranges.length, but not always.
1992 if (numUids != ranges.length) {
1993 ranges = Arrays.copyOf(ranges, numUids);
1994 }
1995 // ... with no exceptions.
1996 exemptUids = new int[0];
1997 }
1998
1999 try {
2000 mNetdService.socketDestroy(ranges, exemptUids);
2001 } catch(RemoteException | ServiceSpecificException e) {
2002 Slog.e(TAG, "Error closing sockets after enabling chain " + chainName + ": " + e);
2003 }
2004 }
2005
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002006 @Override
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002007 public void setFirewallChainEnabled(int chain, boolean enable) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07002008 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002009 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002010 synchronized (mRulesLock) {
2011 if (getFirewallChainState(chain) == enable) {
2012 // All is the same, nothing to do. This relies on the fact that netd has child
2013 // chains default detached.
2014 return;
2015 }
2016 setFirewallChainState(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002017 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002018
Luke Huang615e1022018-10-25 11:54:05 +09002019 final String chainName = getFirewallChainName(chain);
Luke Huanga241db92018-07-31 20:15:24 +08002020 if (chain == FIREWALL_CHAIN_NONE) {
Luke Huang615e1022018-10-25 11:54:05 +09002021 throw new IllegalArgumentException("Bad child chain: " + chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002022 }
2023
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002024 try {
Luke Huanga241db92018-07-31 20:15:24 +08002025 mNetdService.firewallEnableChildChain(chain, enable);
2026 } catch (RemoteException | ServiceSpecificException e) {
2027 throw new IllegalStateException(e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002028 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002029
2030 // Close any sockets that were opened by the affected UIDs. This has to be done after
2031 // disabling network connectivity, in case they react to the socket close by reopening
2032 // the connection and race with the iptables commands that enable the firewall. All
2033 // whitelist and blacklist chains allow RSTs through.
2034 if (enable) {
Luke Huang615e1022018-10-25 11:54:05 +09002035 closeSocketsForFirewallChainLocked(chain, chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002036 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002037 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002038 }
2039
Luke Huanga241db92018-07-31 20:15:24 +08002040 private String getFirewallChainName(int chain) {
2041 switch (chain) {
2042 case FIREWALL_CHAIN_STANDBY:
2043 return FIREWALL_CHAIN_NAME_STANDBY;
2044 case FIREWALL_CHAIN_DOZABLE:
2045 return FIREWALL_CHAIN_NAME_DOZABLE;
2046 case FIREWALL_CHAIN_POWERSAVE:
2047 return FIREWALL_CHAIN_NAME_POWERSAVE;
2048 default:
2049 throw new IllegalArgumentException("Bad child chain: " + chain);
2050 }
2051 }
2052
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002053 private int getFirewallType(int chain) {
2054 switch (chain) {
2055 case FIREWALL_CHAIN_STANDBY:
2056 return FIREWALL_TYPE_BLACKLIST;
2057 case FIREWALL_CHAIN_DOZABLE:
2058 return FIREWALL_TYPE_WHITELIST;
Felipe Leme011b98f2016-02-10 17:28:31 -08002059 case FIREWALL_CHAIN_POWERSAVE:
2060 return FIREWALL_TYPE_WHITELIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002061 default:
2062 return isFirewallEnabled() ? FIREWALL_TYPE_WHITELIST : FIREWALL_TYPE_BLACKLIST;
2063 }
2064 }
2065
2066 @Override
2067 public void setFirewallUidRules(int chain, int[] uids, int[] rules) {
2068 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002069 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002070 synchronized (mRulesLock) {
2071 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
2072 SparseIntArray newRules = new SparseIntArray();
2073 // apply new set of rules
2074 for (int index = uids.length - 1; index >= 0; --index) {
2075 int uid = uids[index];
2076 int rule = rules[index];
2077 updateFirewallUidRuleLocked(chain, uid, rule);
2078 newRules.put(uid, rule);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002079 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002080 // collect the rules to remove.
2081 SparseIntArray rulesToRemove = new SparseIntArray();
2082 for (int index = uidFirewallRules.size() - 1; index >= 0; --index) {
2083 int uid = uidFirewallRules.keyAt(index);
2084 if (newRules.indexOfKey(uid) < 0) {
2085 rulesToRemove.put(uid, FIREWALL_RULE_DEFAULT);
2086 }
2087 }
2088 // remove dead rules
2089 for (int index = rulesToRemove.size() - 1; index >= 0; --index) {
2090 int uid = rulesToRemove.keyAt(index);
2091 updateFirewallUidRuleLocked(chain, uid, FIREWALL_RULE_DEFAULT);
2092 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002093 }
2094 try {
2095 switch (chain) {
2096 case FIREWALL_CHAIN_DOZABLE:
2097 mNetdService.firewallReplaceUidChain("fw_dozable", true, uids);
2098 break;
2099 case FIREWALL_CHAIN_STANDBY:
2100 mNetdService.firewallReplaceUidChain("fw_standby", false, uids);
2101 break;
2102 case FIREWALL_CHAIN_POWERSAVE:
2103 mNetdService.firewallReplaceUidChain("fw_powersave", true, uids);
2104 break;
2105 case FIREWALL_CHAIN_NONE:
2106 default:
2107 Slog.d(TAG, "setFirewallUidRules() called on invalid chain: " + chain);
2108 }
2109 } catch (RemoteException e) {
2110 Slog.w(TAG, "Error flushing firewall chain " + chain, e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002111 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002112 }
2113 }
2114
2115 @Override
2116 public void setFirewallUidRule(int chain, int uid, int rule) {
2117 enforceSystemUid();
Felipe Lemea701cad2016-05-12 09:58:14 -07002118 synchronized (mQuotaLock) {
2119 setFirewallUidRuleLocked(chain, uid, rule);
2120 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002121 }
2122
Felipe Lemea701cad2016-05-12 09:58:14 -07002123 private void setFirewallUidRuleLocked(int chain, int uid, int rule) {
2124 if (updateFirewallUidRuleLocked(chain, uid, rule)) {
Luke Huanga241db92018-07-31 20:15:24 +08002125 final int ruleType = getFirewallRuleType(chain, rule);
Amith Yamasani15e472352015-04-24 19:06:07 -07002126 try {
Luke Huanga241db92018-07-31 20:15:24 +08002127 mNetdService.firewallSetUidRule(chain, uid, ruleType);
2128 } catch (RemoteException | ServiceSpecificException e) {
2129 throw new IllegalStateException(e);
Amith Yamasani15e472352015-04-24 19:06:07 -07002130 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002131 }
2132 }
2133
Felipe Lemea701cad2016-05-12 09:58:14 -07002134 // TODO: now that netd supports batching, NMS should not keep these data structures anymore...
2135 private boolean updateFirewallUidRuleLocked(int chain, int uid, int rule) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002136 synchronized (mRulesLock) {
2137 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Felipe Lemea701cad2016-05-12 09:58:14 -07002138
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002139 final int oldUidFirewallRule = uidFirewallRules.get(uid, FIREWALL_RULE_DEFAULT);
2140 if (DBG) {
2141 Slog.d(TAG, "oldRule = " + oldUidFirewallRule
2142 + ", newRule=" + rule + " for uid=" + uid + " on chain " + chain);
2143 }
2144 if (oldUidFirewallRule == rule) {
2145 if (DBG) Slog.d(TAG, "!!!!! Skipping change");
2146 // TODO: eventually consider throwing
2147 return false;
2148 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002149
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002150 String ruleName = getFirewallRuleName(chain, rule);
2151 String oldRuleName = getFirewallRuleName(chain, oldUidFirewallRule);
Felipe Lemea701cad2016-05-12 09:58:14 -07002152
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002153 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
2154 uidFirewallRules.delete(uid);
2155 } else {
2156 uidFirewallRules.put(uid, rule);
2157 }
2158 return !ruleName.equals(oldRuleName);
Felipe Lemea701cad2016-05-12 09:58:14 -07002159 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002160 }
2161
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002162 private @NonNull String getFirewallRuleName(int chain, int rule) {
2163 String ruleName;
2164 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
2165 if (rule == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
2166 ruleName = "allow";
2167 } else {
2168 ruleName = "deny";
2169 }
2170 } else { // Blacklist mode
2171 if (rule == NetworkPolicyManager.FIREWALL_RULE_DENY) {
2172 ruleName = "deny";
2173 } else {
2174 ruleName = "allow";
2175 }
2176 }
2177 return ruleName;
2178 }
2179
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) {
2197 return getFirewallType(chain) == FIREWALL_TYPE_WHITELIST
2198 ? 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}