blob: 4fb654bfb55771ae174a32bf0f399c31d3ae834d [file] [log] [blame]
San Mehat873f2142010-01-14 10:25:07 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey4529bb62011-12-14 10:31:54 -080019import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey47eb1022011-08-25 17:48:52 -070020import static android.Manifest.permission.DUMP;
Sehee Parka9139bc2017-12-22 13:54:05 +090021import static android.Manifest.permission.NETWORK_SETTINGS;
Lorenzo Colitti07f13042017-07-10 19:06:57 +090022import static android.Manifest.permission.NETWORK_STACK;
Jeff Sharkeyaf75c332011-11-18 12:41:12 -080023import static android.Manifest.permission.SHUTDOWN;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070024import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
25import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_DOZABLE;
26import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_NONE;
Felipe Leme011b98f2016-02-10 17:28:31 -080027import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070028import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_STANDBY;
29import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NONE;
Felipe Leme011b98f2016-02-10 17:28:31 -080030import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070031import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
Sudheer Shanka62f5c172017-03-17 16:25:55 -070032import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070033import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Sudheer Shanka62f5c172017-03-17 16:25:55 -070034import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070035import static android.net.NetworkPolicyManager.FIREWALL_TYPE_BLACKLIST;
36import static android.net.NetworkPolicyManager.FIREWALL_TYPE_WHITELIST;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -070037import static android.net.NetworkStats.SET_DEFAULT;
Lorenzo Colittif1912ca2017-08-17 19:23:08 +090038import static android.net.NetworkStats.STATS_PER_UID;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080039import static android.net.NetworkStats.TAG_ALL;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070040import static android.net.NetworkStats.TAG_NONE;
41import static android.net.NetworkStats.UID_ALL;
Jeff Sharkeyae2c1812011-10-04 13:11:40 -070042import static android.net.TrafficStats.UID_TETHERING;
Lorenzo Colitti79751842013-02-28 16:16:03 +090043import static com.android.server.NetworkManagementService.NetdResponseCode.ClatdStatusResult;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -080044import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceGetCfgResult;
45import static com.android.server.NetworkManagementService.NetdResponseCode.InterfaceListResult;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -080046import static com.android.server.NetworkManagementService.NetdResponseCode.IpFwdStatusResult;
47import static com.android.server.NetworkManagementService.NetdResponseCode.TetherDnsFwdTgtListResult;
48import static com.android.server.NetworkManagementService.NetdResponseCode.TetherInterfaceListResult;
49import static com.android.server.NetworkManagementService.NetdResponseCode.TetherStatusResult;
Jeff Sharkeye4984be2013-09-10 21:03:27 -070050import static com.android.server.NetworkManagementService.NetdResponseCode.TetheringStatsListResult;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -080051import static com.android.server.NetworkManagementService.NetdResponseCode.TtyListResult;
Jeff Sharkeya63ba592011-07-19 23:47:12 -070052import static com.android.server.NetworkManagementSocketTagger.PROP_QTAGUID_ENABLED;
Erik Klineb2cfdfb2017-01-18 20:54:14 +090053
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070054import android.annotation.NonNull;
Sudheer Shankadc589ac2016-11-10 15:30:17 -080055import android.app.ActivityManager;
Pierre Imai8e48e672016-04-21 13:30:43 +090056import android.content.ContentResolver;
San Mehat873f2142010-01-14 10:25:07 -080057import android.content.Context;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080058import android.net.ConnectivityManager;
Lorenzo Colitti58967ba2016-02-02 17:21:21 +090059import android.net.INetd;
Luke Huang13b79e82018-09-26 14:53:42 +080060import android.net.TetherStatsParcel;
San Mehat4d02d002010-01-22 16:07:46 -080061import android.net.INetworkManagementEventObserver;
Lorenzo Colitti07f13042017-07-10 19:06:57 +090062import android.net.ITetheringStatsProvider;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070063import android.net.InterfaceConfiguration;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +090064import android.net.IpPrefix;
Robert Greenwalted126402011-01-28 15:34:55 -080065import android.net.LinkAddress;
Lorenzo Colittib57edc52014-08-22 17:10:50 -070066import android.net.Network;
Amith Yamasani15e472352015-04-24 19:06:07 -070067import android.net.NetworkPolicyManager;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070068import android.net.NetworkStats;
Robert Greenwalted126402011-01-28 15:34:55 -080069import android.net.NetworkUtils;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070070import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040071import android.net.UidRange;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +090072import android.net.util.NetdService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080073import android.net.wifi.WifiConfiguration;
74import android.net.wifi.WifiConfiguration.KeyMgmt;
Dianne Hackborn91268cf2013-06-13 19:06:50 -070075import android.os.BatteryStats;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070076import android.os.Binder;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -070077import android.os.Handler;
Lorenzo Colittia0868002017-07-11 02:29:28 +090078import android.os.IBinder;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080079import android.os.INetworkActivityListener;
San Mehat873f2142010-01-14 10:25:07 -080080import android.os.INetworkManagementService;
Lorenzo Colitti563dc452017-09-01 17:12:34 +090081import android.os.PersistableBundle;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080082import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070083import android.os.Process;
Jeff Sharkey3df273e2011-12-15 15:47:12 -080084import android.os.RemoteCallbackList;
85import android.os.RemoteException;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070086import android.os.ServiceManager;
Lorenzo Colitti4cb42402016-04-24 12:52:00 +090087import android.os.ServiceSpecificException;
Jeff Sharkey605eb792014-11-04 13:34:06 -080088import android.os.StrictMode;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070089import android.os.SystemClock;
Marco Nelissen62dbb222010-02-18 10:56:30 -080090import android.os.SystemProperties;
Felipe Leme29e72ea2016-09-08 13:26:55 -070091import android.os.Trace;
Pierre Imai8e48e672016-04-21 13:30:43 +090092import android.provider.Settings;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070093import android.telephony.DataConnectionRealTimeInfo;
94import android.telephony.PhoneStateListener;
Wink Savillefb40dd42014-06-12 17:02:31 -070095import android.telephony.SubscriptionManager;
Wink Saville67e07892014-06-18 16:43:14 -070096import android.telephony.TelephonyManager;
Erik Kline4d092232017-10-30 15:29:44 +090097import android.text.TextUtils;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080098import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080099import android.util.Slog;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700100import android.util.SparseBooleanArray;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800101import android.util.SparseIntArray;
San Mehat873f2142010-01-14 10:25:07 -0800102
Jeff Sharkey605eb792014-11-04 13:34:06 -0800103import com.android.internal.annotations.GuardedBy;
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700104import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700105import com.android.internal.app.IBatteryStats;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700106import com.android.internal.net.NetworkStatsFactory;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600107import com.android.internal.util.DumpUtils;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800108import com.android.internal.util.HexDump;
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700109import com.android.internal.util.Preconditions;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800110import com.android.server.NativeDaemonConnector.Command;
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700111import com.android.server.NativeDaemonConnector.SensitiveArg;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700112import com.google.android.collect.Maps;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700113
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700114import java.io.BufferedReader;
115import java.io.DataInputStream;
San Mehat873f2142010-01-14 10:25:07 -0800116import java.io.File;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700117import java.io.FileDescriptor;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700118import java.io.FileInputStream;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700119import java.io.IOException;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700120import java.io.InputStreamReader;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700121import java.io.PrintWriter;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700122import java.net.InetAddress;
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700123import java.net.InterfaceAddress;
124import java.net.NetworkInterface;
125import java.net.SocketException;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700126import java.util.ArrayList;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400127import java.util.Arrays;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700128import java.util.HashMap;
jiaguo1da35f72014-01-09 16:39:59 +0800129import java.util.List;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700130import java.util.Map;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700131import java.util.NoSuchElementException;
132import java.util.StringTokenizer;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700133import java.util.concurrent.CountDownLatch;
San Mehat873f2142010-01-14 10:25:07 -0800134
135/**
136 * @hide
137 */
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700138public class NetworkManagementService extends INetworkManagementService.Stub
139 implements Watchdog.Monitor {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900140
141 /**
142 * Helper class that encapsulates NetworkManagementService dependencies and makes them
143 * easier to mock in unit tests.
144 */
145 static class SystemServices {
146 public IBinder getService(String name) {
147 return ServiceManager.getService(name);
148 }
149 public void registerLocalService(NetworkManagementInternal nmi) {
150 LocalServices.addService(NetworkManagementInternal.class, nmi);
151 }
152 public INetd getNetd() {
153 return NetdService.get();
154 }
155 }
156
Amith Yamasani15e472352015-04-24 19:06:07 -0700157 private static final String TAG = "NetworkManagement";
158 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Kenny Root305bcbf2010-09-03 07:56:38 -0700159 private static final String NETD_TAG = "NetdConnector";
Lorenzo Colittia0868002017-07-11 02:29:28 +0900160 static final String NETD_SERVICE_NAME = "netd";
Kenny Root305bcbf2010-09-03 07:56:38 -0700161
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400162 private static final int MAX_UID_RANGES_PER_COMMAND = 10;
163
Luke Huang4a32bf42018-08-21 19:09:45 +0800164 private static final String[] EMPTY_STRING_ARRAY = new String[0];
165
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700166 /**
167 * Name representing {@link #setGlobalAlert(long)} limit when delivered to
168 * {@link INetworkManagementEventObserver#limitReached(String, String)}.
169 */
170 public static final String LIMIT_GLOBAL_ALERT = "globalAlert";
171
Andrew Scull45f533c2017-05-19 15:37:20 +0100172 static class NetdResponseCode {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -0700173 /* Keep in sync with system/netd/server/ResponseCode.h */
San Mehat873f2142010-01-14 10:25:07 -0800174 public static final int InterfaceListResult = 110;
175 public static final int TetherInterfaceListResult = 111;
176 public static final int TetherDnsFwdTgtListResult = 112;
San Mehat72759df2010-01-19 13:50:37 -0800177 public static final int TtyListResult = 113;
Jeff Sharkeye4984be2013-09-10 21:03:27 -0700178 public static final int TetheringStatsListResult = 114;
San Mehat873f2142010-01-14 10:25:07 -0800179
180 public static final int TetherStatusResult = 210;
181 public static final int IpFwdStatusResult = 211;
San Mehated4fc8a2010-01-22 12:28:36 -0800182 public static final int InterfaceGetCfgResult = 213;
Robert Greenwalte3253922010-02-18 09:23:25 -0800183 public static final int SoftapStatusResult = 214;
San Mehat91cac642010-03-31 14:31:36 -0700184 public static final int InterfaceRxCounterResult = 216;
185 public static final int InterfaceTxCounterResult = 217;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700186 public static final int QuotaCounterResult = 220;
187 public static final int TetheringStatsResult = 221;
Selim Gurun84c00c62012-02-27 15:42:38 -0800188 public static final int DnsProxyQueryResult = 222;
Lorenzo Colitti79751842013-02-28 16:16:03 +0900189 public static final int ClatdStatusResult = 223;
Robert Greenwalte3253922010-02-18 09:23:25 -0800190
191 public static final int InterfaceChange = 600;
JP Abgrall12b933d2011-07-14 18:09:22 -0700192 public static final int BandwidthControl = 601;
Haoyu Bai6b7358d2012-07-17 16:36:50 -0700193 public static final int InterfaceClassActivity = 613;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900194 public static final int InterfaceAddressChange = 614;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900195 public static final int InterfaceDnsServerInfo = 615;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900196 public static final int RouteChange = 616;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800197 public static final int StrictCleartext = 617;
San Mehat873f2142010-01-14 10:25:07 -0800198 }
199
Rebecca Silbersteine2ec94f2016-03-24 13:29:00 -0700200 /**
201 * String indicating a softap command.
202 */
203 static final String SOFT_AP_COMMAND = "softap";
204
205 /**
206 * String passed back to netd connector indicating softap command success.
207 */
208 static final String SOFT_AP_COMMAND_SUCCESS = "Ok";
209
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700210 static final int DAEMON_MSG_MOBILE_CONN_REAL_TIME_INFO = 1;
211
Luke Huang8a462ec2018-08-24 20:33:16 +0800212 static final boolean MODIFY_OPERATION_ADD = true;
213 static final boolean MODIFY_OPERATION_REMOVE = false;
214
San Mehat873f2142010-01-14 10:25:07 -0800215 /**
216 * Binder context for this service
217 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700218 private final Context mContext;
San Mehat873f2142010-01-14 10:25:07 -0800219
220 /**
221 * connector object for communicating with netd
222 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700223 private final NativeDaemonConnector mConnector;
San Mehat873f2142010-01-14 10:25:07 -0800224
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700225 private final Handler mFgHandler;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700226 private final Handler mDaemonHandler;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700227
Lorenzo Colittia0868002017-07-11 02:29:28 +0900228 private final SystemServices mServices;
229
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900230 private INetd mNetdService;
231
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800232 private IBatteryStats mBatteryStats;
233
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700234 private final Thread mThread;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700235 private CountDownLatch mConnectedSignal = new CountDownLatch(1);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700236
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800237 private final RemoteCallbackList<INetworkManagementEventObserver> mObservers =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700238 new RemoteCallbackList<>();
San Mehat4d02d002010-01-22 16:07:46 -0800239
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700240 private final NetworkStatsFactory mStatsFactory = new NetworkStatsFactory();
241
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900242 @GuardedBy("mTetheringStatsProviders")
243 private final HashMap<ITetheringStatsProvider, String>
244 mTetheringStatsProviders = Maps.newHashMap();
245
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700246 /**
247 * If both locks need to be held, then they should be obtained in the order:
248 * first {@link #mQuotaLock} and then {@link #mRulesLock}.
249 */
Andrew Scull45f533c2017-05-19 15:37:20 +0100250 private final Object mQuotaLock = new Object();
Andrew Scull519291f2017-05-23 13:11:03 +0100251 private final Object mRulesLock = new Object();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800252
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700253 /** Set of interfaces with active quotas. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800254 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700255 private HashMap<String, Long> mActiveQuotas = Maps.newHashMap();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700256 /** Set of interfaces with active alerts. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800257 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700258 private HashMap<String, Long> mActiveAlerts = Maps.newHashMap();
Felipe Leme65be3022016-03-22 14:53:13 -0700259 /** Set of UIDs blacklisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700260 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700261 private SparseBooleanArray mUidRejectOnMetered = new SparseBooleanArray();
262 /** Set of UIDs whitelisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700263 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700264 private SparseBooleanArray mUidAllowOnMetered = new SparseBooleanArray();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800265 /** Set of UIDs with cleartext penalties. */
266 @GuardedBy("mQuotaLock")
267 private SparseIntArray mUidCleartextPolicy = new SparseIntArray();
Amith Yamasani15e472352015-04-24 19:06:07 -0700268 /** Set of UIDs that are to be blocked/allowed by firewall controller. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700269 @GuardedBy("mRulesLock")
Amith Yamasani15e472352015-04-24 19:06:07 -0700270 private SparseIntArray mUidFirewallRules = new SparseIntArray();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700271 /**
272 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
273 * to application idles.
274 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700275 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700276 private SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
277 /**
278 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
279 * to device idles.
280 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700281 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700282 private SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800283 /**
284 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
285 * to device on power-save mode.
286 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700287 @GuardedBy("mRulesLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800288 private SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700289 /** Set of states for the child firewall chains. True if the chain is active. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700290 @GuardedBy("mRulesLock")
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700291 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700292
Felipe Leme65be3022016-03-22 14:53:13 -0700293 @GuardedBy("mQuotaLock")
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700294 private volatile boolean mDataSaverMode;
Felipe Leme65be3022016-03-22 14:53:13 -0700295
Andrew Scull45f533c2017-05-19 15:37:20 +0100296 private final Object mIdleTimerLock = new Object();
Haoyu Bai04124232012-06-28 15:26:19 -0700297 /** Set of interfaces with active idle timers. */
298 private static class IdleTimerParams {
299 public final int timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800300 public final int type;
Haoyu Bai04124232012-06-28 15:26:19 -0700301 public int networkCount;
302
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800303 IdleTimerParams(int timeout, int type) {
Haoyu Bai04124232012-06-28 15:26:19 -0700304 this.timeout = timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800305 this.type = type;
Haoyu Bai04124232012-06-28 15:26:19 -0700306 this.networkCount = 1;
307 }
308 }
309 private HashMap<String, IdleTimerParams> mActiveIdleTimers = Maps.newHashMap();
310
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700311 private volatile boolean mFirewallEnabled;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800312 private volatile boolean mStrictEnabled;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700313
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700314 private boolean mMobileActivityFromRadio = false;
315 private int mLastPowerStateFromRadio = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Adam Lesinskie08af192015-03-25 16:42:59 -0700316 private int mLastPowerStateFromWifi = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700317
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800318 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700319 new RemoteCallbackList<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800320 private boolean mNetworkActive;
321
San Mehat873f2142010-01-14 10:25:07 -0800322 /**
323 * Constructs a new NetworkManagementService instance
324 *
325 * @param context Binder context for this service
326 */
Lorenzo Colittia0868002017-07-11 02:29:28 +0900327 private NetworkManagementService(
328 Context context, String socket, SystemServices services) {
San Mehat873f2142010-01-14 10:25:07 -0800329 mContext = context;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900330 mServices = services;
San Mehat4d02d002010-01-22 16:07:46 -0800331
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700332 // make sure this is on the same looper as our NativeDaemonConnector for sync purposes
333 mFgHandler = new Handler(FgThread.get().getLooper());
334
Dianne Hackborn4590e522014-03-24 13:36:46 -0700335 // Don't need this wake lock, since we now have a time stamp for when
336 // the network actually went inactive. (It might be nice to still do this,
337 // but I don't want to do it through the power manager because that pollutes the
338 // battery stats history with pointless noise.)
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700339 //PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
Dianne Hackborn4590e522014-03-24 13:36:46 -0700340 PowerManager.WakeLock wl = null; //pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NETD_TAG);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800341
San Mehat873f2142010-01-14 10:25:07 -0800342 mConnector = new NativeDaemonConnector(
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700343 new NetdCallbackReceiver(), socket, 10, NETD_TAG, 160, wl,
344 FgThread.get().getLooper());
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700345 mThread = new Thread(mConnector, NETD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700346
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700347 mDaemonHandler = new Handler(FgThread.get().getLooper());
Wink Saville67e07892014-06-18 16:43:14 -0700348
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700349 // Add ourself to the Watchdog monitors.
350 Watchdog.getInstance().addMonitor(this);
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700351
Lorenzo Colittia0868002017-07-11 02:29:28 +0900352 mServices.registerLocalService(new LocalService());
Lorenzo Colitti8228eb32017-07-19 06:17:33 +0900353
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900354 synchronized (mTetheringStatsProviders) {
355 mTetheringStatsProviders.put(new NetdTetheringStatsProvider(), "netd");
356 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700357 }
358
359 @VisibleForTesting
360 NetworkManagementService() {
361 mConnector = null;
362 mContext = null;
363 mDaemonHandler = null;
364 mFgHandler = null;
365 mThread = null;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900366 mServices = null;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700367 }
368
Lorenzo Colittia0868002017-07-11 02:29:28 +0900369 static NetworkManagementService create(Context context, String socket, SystemServices services)
Felipe Leme03e689d2016-03-02 16:17:38 -0800370 throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900371 final NetworkManagementService service =
372 new NetworkManagementService(context, socket, services);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700373 final CountDownLatch connectedSignal = service.mConnectedSignal;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700374 if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
375 service.mThread.start();
376 if (DBG) Slog.d(TAG, "Awaiting socket connection");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700377 connectedSignal.await();
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700378 if (DBG) Slog.d(TAG, "Connected");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900379 if (DBG) Slog.d(TAG, "Connecting native netd service");
bohu07cc3bb2016-05-03 15:58:01 -0700380 service.connectNativeNetdService();
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900381 if (DBG) Slog.d(TAG, "Connected");
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700382 return service;
San Mehat873f2142010-01-14 10:25:07 -0800383 }
384
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900385 public static NetworkManagementService create(Context context) throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900386 return create(context, NETD_SERVICE_NAME, new SystemServices());
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900387 }
388
Jeff Sharkey350083e2011-06-29 10:45:16 -0700389 public void systemReady() {
Felipe Leme03e689d2016-03-02 16:17:38 -0800390 if (DBG) {
391 final long start = System.currentTimeMillis();
392 prepareNativeDaemon();
393 final long delta = System.currentTimeMillis() - start;
394 Slog.d(TAG, "Prepared in " + delta + "ms");
395 return;
396 } else {
397 prepareNativeDaemon();
398 }
Jeff Sharkey350083e2011-06-29 10:45:16 -0700399 }
400
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800401 private IBatteryStats getBatteryStats() {
402 synchronized (this) {
403 if (mBatteryStats != null) {
404 return mBatteryStats;
405 }
Lorenzo Colittia0868002017-07-11 02:29:28 +0900406 mBatteryStats =
407 IBatteryStats.Stub.asInterface(mServices.getService(BatteryStats.SERVICE_NAME));
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800408 return mBatteryStats;
409 }
410 }
411
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800412 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800413 public void registerObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800414 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800415 mObservers.register(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800416 }
417
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800418 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800419 public void unregisterObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800420 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800421 mObservers.unregister(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800422 }
423
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900424 @FunctionalInterface
425 private interface NetworkManagementEventCallback {
426 public void sendCallback(INetworkManagementEventObserver o) throws RemoteException;
427 }
428
429 private void invokeForAllObservers(NetworkManagementEventCallback eventCallback) {
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800430 final int length = mObservers.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700431 try {
432 for (int i = 0; i < length; i++) {
433 try {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900434 eventCallback.sendCallback(mObservers.getBroadcastItem(i));
Felipe Leme03e689d2016-03-02 16:17:38 -0800435 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700436 }
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700437 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700438 } finally {
439 mObservers.finishBroadcast();
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700440 }
441 }
442
443 /**
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900444 * Notify our observers of an interface status change
445 */
446 private void notifyInterfaceStatusChanged(String iface, boolean up) {
447 invokeForAllObservers(o -> o.interfaceStatusChanged(iface, up));
448 }
449
450 /**
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700451 * Notify our observers of an interface link state change
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700452 * (typically, an Ethernet cable has been plugged-in or unplugged).
453 */
454 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900455 invokeForAllObservers(o -> o.interfaceLinkStateChanged(iface, up));
San Mehat4d02d002010-01-22 16:07:46 -0800456 }
457
458 /**
459 * Notify our observers of an interface addition.
460 */
461 private void notifyInterfaceAdded(String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900462 invokeForAllObservers(o -> o.interfaceAdded(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800463 }
464
465 /**
466 * Notify our observers of an interface removal.
467 */
468 private void notifyInterfaceRemoved(String iface) {
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700469 // netd already clears out quota and alerts for removed ifaces; update
470 // our sanity-checking state.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700471 mActiveAlerts.remove(iface);
472 mActiveQuotas.remove(iface);
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700473
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900474 invokeForAllObservers(o -> o.interfaceRemoved(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800475 }
476
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700477 /**
JP Abgrall12b933d2011-07-14 18:09:22 -0700478 * Notify our observers of a limit reached.
479 */
480 private void notifyLimitReached(String limitName, String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900481 invokeForAllObservers(o -> o.limitReached(limitName, iface));
JP Abgrall12b933d2011-07-14 18:09:22 -0700482 }
483
484 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700485 * Notify our observers of a change in the data activity state of the interface
486 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700487 private void notifyInterfaceClassActivity(int type, int powerState, long tsNanos,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700488 int uid, boolean fromRadio) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700489 final boolean isMobile = ConnectivityManager.isNetworkTypeMobile(type);
490 if (isMobile) {
491 if (!fromRadio) {
492 if (mMobileActivityFromRadio) {
493 // If this call is not coming from a report from the radio itself, but we
494 // have previously received reports from the radio, then we will take the
495 // power state to just be whatever the radio last reported.
496 powerState = mLastPowerStateFromRadio;
497 }
498 } else {
499 mMobileActivityFromRadio = true;
500 }
501 if (mLastPowerStateFromRadio != powerState) {
502 mLastPowerStateFromRadio = powerState;
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700503 try {
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700504 getBatteryStats().noteMobileRadioPowerState(powerState, tsNanos, uid);
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700505 } catch (RemoteException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700506 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700507 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700508 }
509
Adam Lesinskie08af192015-03-25 16:42:59 -0700510 if (ConnectivityManager.isNetworkTypeWifi(type)) {
511 if (mLastPowerStateFromWifi != powerState) {
512 mLastPowerStateFromWifi = powerState;
513 try {
Adam Lesinski5f056f62016-07-14 16:56:08 -0700514 getBatteryStats().noteWifiRadioPowerState(powerState, tsNanos, uid);
Adam Lesinskie08af192015-03-25 16:42:59 -0700515 } catch (RemoteException e) {
516 }
517 }
518 }
519
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700520 boolean isActive = powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
521 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
522
523 if (!isMobile || fromRadio || !mMobileActivityFromRadio) {
524 // Report the change in data activity. We don't do this if this is a change
525 // on the mobile network, that is not coming from the radio itself, and we
526 // have previously seen change reports from the radio. In that case only
527 // the radio is the authority for the current state.
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900528 final boolean active = isActive;
529 invokeForAllObservers(o -> o.interfaceClassDataActivityChanged(
530 Integer.toString(type), active, tsNanos));
Haoyu Baidb3c8672012-06-20 14:29:57 -0700531 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800532
533 boolean report = false;
534 synchronized (mIdleTimerLock) {
535 if (mActiveIdleTimers.isEmpty()) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700536 // If there are no idle timers, we are not monitoring activity, so we
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800537 // are always considered active.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700538 isActive = true;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800539 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700540 if (mNetworkActive != isActive) {
541 mNetworkActive = isActive;
542 report = isActive;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800543 }
544 }
545 if (report) {
546 reportNetworkActive();
547 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700548 }
549
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900550 @Override
551 public void registerTetheringStatsProvider(ITetheringStatsProvider provider, String name) {
552 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
553 Preconditions.checkNotNull(provider);
554 synchronized(mTetheringStatsProviders) {
555 mTetheringStatsProviders.put(provider, name);
556 }
557 }
558
559 @Override
560 public void unregisterTetheringStatsProvider(ITetheringStatsProvider provider) {
561 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
562 synchronized(mTetheringStatsProviders) {
563 mTetheringStatsProviders.remove(provider);
564 }
565 }
566
Lorenzo Colitti9f0baa92017-08-15 19:25:51 +0900567 @Override
568 public void tetherLimitReached(ITetheringStatsProvider provider) {
569 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
570 synchronized(mTetheringStatsProviders) {
571 if (!mTetheringStatsProviders.containsKey(provider)) {
572 return;
573 }
574 // No current code examines the interface parameter in a global alert. Just pass null.
575 notifyLimitReached(LIMIT_GLOBAL_ALERT, null);
576 }
577 }
578
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900579 // Sync the state of the given chain with the native daemon.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700580 private void syncFirewallChainLocked(int chain, String name) {
581 SparseIntArray rules;
582 synchronized (mRulesLock) {
583 final SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900584 // Make a copy of the current rules, and then clear them. This is because
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700585 // setFirewallUidRuleInternal only pushes down rules to the native daemon if they
586 // are different from the current rules stored in the mUidFirewall*Rules array for
587 // the specified chain. If we don't clear the rules, setFirewallUidRuleInternal
588 // will do nothing.
589 rules = uidFirewallRules.clone();
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900590 uidFirewallRules.clear();
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700591 }
592 if (rules.size() > 0) {
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900593 // Now push the rules. setFirewallUidRuleInternal will push each of these down to the
594 // native daemon, and also add them to the mUidFirewall*Rules array for the specified
595 // chain.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700596 if (DBG) Slog.d(TAG, "Pushing " + rules.size() + " active firewall "
597 + name + "UID rules");
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900598 for (int i = 0; i < rules.size(); i++) {
Felipe Lemea701cad2016-05-12 09:58:14 -0700599 setFirewallUidRuleLocked(chain, rules.keyAt(i), rules.valueAt(i));
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900600 }
601 }
602 }
603
bohu07cc3bb2016-05-03 15:58:01 -0700604 private void connectNativeNetdService() {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900605 mNetdService = mServices.getNetd();
bohu07cc3bb2016-05-03 15:58:01 -0700606 }
607
608 /**
609 * Prepare native daemon once connected, enabling modules and pushing any
610 * existing in-memory rules.
611 */
612 private void prepareNativeDaemon() {
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900613
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700614 // push any existing quota or UID rules
615 synchronized (mQuotaLock) {
Felipe Leme65be3022016-03-22 14:53:13 -0700616
Luke Huang56a03a02018-09-07 12:02:16 +0800617 // Netd unconditionally enable bandwidth control
618 SystemProperties.set(PROP_QTAGUID_ENABLED, "1");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900619
Luke Huang473eb872018-07-26 17:33:14 +0800620 mStrictEnabled = true;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900621
Felipe Leme65be3022016-03-22 14:53:13 -0700622 setDataSaverModeEnabled(mDataSaverMode);
623
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700624 int size = mActiveQuotas.size();
625 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800626 if (DBG) Slog.d(TAG, "Pushing " + size + " active quota rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700627 final HashMap<String, Long> activeQuotas = mActiveQuotas;
628 mActiveQuotas = Maps.newHashMap();
629 for (Map.Entry<String, Long> entry : activeQuotas.entrySet()) {
630 setInterfaceQuota(entry.getKey(), entry.getValue());
631 }
632 }
633
634 size = mActiveAlerts.size();
635 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800636 if (DBG) Slog.d(TAG, "Pushing " + size + " active alert rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700637 final HashMap<String, Long> activeAlerts = mActiveAlerts;
638 mActiveAlerts = Maps.newHashMap();
639 for (Map.Entry<String, Long> entry : activeAlerts.entrySet()) {
640 setInterfaceAlert(entry.getKey(), entry.getValue());
641 }
642 }
643
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700644 SparseBooleanArray uidRejectOnQuota = null;
645 SparseBooleanArray uidAcceptOnQuota = null;
646 synchronized (mRulesLock) {
647 size = mUidRejectOnMetered.size();
648 if (size > 0) {
649 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered blacklist rules");
650 uidRejectOnQuota = mUidRejectOnMetered;
651 mUidRejectOnMetered = new SparseBooleanArray();
652 }
653
654 size = mUidAllowOnMetered.size();
655 if (size > 0) {
656 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered whitelist rules");
657 uidAcceptOnQuota = mUidAllowOnMetered;
658 mUidAllowOnMetered = new SparseBooleanArray();
659 }
660 }
661 if (uidRejectOnQuota != null) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700662 for (int i = 0; i < uidRejectOnQuota.size(); i++) {
Felipe Leme65be3022016-03-22 14:53:13 -0700663 setUidMeteredNetworkBlacklist(uidRejectOnQuota.keyAt(i),
664 uidRejectOnQuota.valueAt(i));
665 }
666 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700667 if (uidAcceptOnQuota != null) {
Felipe Leme65be3022016-03-22 14:53:13 -0700668 for (int i = 0; i < uidAcceptOnQuota.size(); i++) {
669 setUidMeteredNetworkWhitelist(uidAcceptOnQuota.keyAt(i),
670 uidAcceptOnQuota.valueAt(i));
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700671 }
672 }
Jeff Sharkey605eb792014-11-04 13:34:06 -0800673
674 size = mUidCleartextPolicy.size();
675 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800676 if (DBG) Slog.d(TAG, "Pushing " + size + " active UID cleartext policies");
Jeff Sharkey605eb792014-11-04 13:34:06 -0800677 final SparseIntArray local = mUidCleartextPolicy;
678 mUidCleartextPolicy = new SparseIntArray();
679 for (int i = 0; i < local.size(); i++) {
680 setUidCleartextNetworkPolicy(local.keyAt(i), local.valueAt(i));
681 }
682 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700683
Robin Leec3736bc2017-03-10 16:19:54 +0000684 setFirewallEnabled(mFirewallEnabled);
Amith Yamasani15e472352015-04-24 19:06:07 -0700685
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700686 syncFirewallChainLocked(FIREWALL_CHAIN_NONE, "");
687 syncFirewallChainLocked(FIREWALL_CHAIN_STANDBY, "standby ");
688 syncFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, "dozable ");
689 syncFirewallChainLocked(FIREWALL_CHAIN_POWERSAVE, "powersave ");
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700690
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700691 final int[] chains =
692 {FIREWALL_CHAIN_STANDBY, FIREWALL_CHAIN_DOZABLE, FIREWALL_CHAIN_POWERSAVE};
693 for (int chain : chains) {
694 if (getFirewallChainState(chain)) {
695 setFirewallChainEnabled(chain, true);
696 }
Felipe Leme011b98f2016-02-10 17:28:31 -0800697 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700698 }
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900699
Luke Huang56a03a02018-09-07 12:02:16 +0800700
701 try {
702 getBatteryStats().noteNetworkStatsEnabled();
703 } catch (RemoteException e) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900704 }
705
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700706 }
San Mehat4d02d002010-01-22 16:07:46 -0800707
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900708 /**
709 * Notify our observers of a new or updated interface address.
710 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900711 private void notifyAddressUpdated(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900712 invokeForAllObservers(o -> o.addressUpdated(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900713 }
714
715 /**
716 * Notify our observers of a deleted interface address.
717 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900718 private void notifyAddressRemoved(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900719 invokeForAllObservers(o -> o.addressRemoved(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900720 }
721
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900722 /**
723 * Notify our observers of DNS server information received.
724 */
725 private void notifyInterfaceDnsServerInfo(String iface, long lifetime, String[] addresses) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900726 invokeForAllObservers(o -> o.interfaceDnsServerInfo(iface, lifetime, addresses));
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900727 }
728
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900729 /**
730 * Notify our observers of a route change.
731 */
732 private void notifyRouteChange(String action, RouteInfo route) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900733 if (action.equals("updated")) {
734 invokeForAllObservers(o -> o.routeUpdated(route));
735 } else {
736 invokeForAllObservers(o -> o.routeRemoved(route));
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900737 }
738 }
739
San Mehat873f2142010-01-14 10:25:07 -0800740 //
741 // Netd Callback handling
742 //
743
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700744 private class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
745 @Override
San Mehat873f2142010-01-14 10:25:07 -0800746 public void onDaemonConnected() {
Felipe Leme65be3022016-03-22 14:53:13 -0700747 Slog.i(TAG, "onDaemonConnected()");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700748 // event is dispatched from internal NDC thread, so we prepare the
749 // daemon back on main thread.
750 if (mConnectedSignal != null) {
bohu07cc3bb2016-05-03 15:58:01 -0700751 // The system is booting and we're connecting to netd for the first time.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700752 mConnectedSignal.countDown();
753 mConnectedSignal = null;
754 } else {
bohu07cc3bb2016-05-03 15:58:01 -0700755 // We're reconnecting to netd after the socket connection
756 // was interrupted (e.g., if it crashed).
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700757 mFgHandler.post(new Runnable() {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700758 @Override
759 public void run() {
bohu07cc3bb2016-05-03 15:58:01 -0700760 connectNativeNetdService();
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700761 prepareNativeDaemon();
762 }
763 });
764 }
San Mehat873f2142010-01-14 10:25:07 -0800765 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700766
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700767 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800768 public boolean onCheckHoldWakeLock(int code) {
769 return code == NetdResponseCode.InterfaceClassActivity;
770 }
771
772 @Override
San Mehat873f2142010-01-14 10:25:07 -0800773 public boolean onEvent(int code, String raw, String[] cooked) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900774 String errorMessage = String.format("Invalid event from daemon (%s)", raw);
JP Abgrall12b933d2011-07-14 18:09:22 -0700775 switch (code) {
776 case NetdResponseCode.InterfaceChange:
777 /*
778 * a network interface change occured
779 * Format: "NNN Iface added <name>"
780 * "NNN Iface removed <name>"
781 * "NNN Iface changed <name> <up/down>"
782 * "NNN Iface linkstatus <name> <up/down>"
783 */
784 if (cooked.length < 4 || !cooked[1].equals("Iface")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900785 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700786 }
787 if (cooked[2].equals("added")) {
788 notifyInterfaceAdded(cooked[3]);
789 return true;
790 } else if (cooked[2].equals("removed")) {
791 notifyInterfaceRemoved(cooked[3]);
792 return true;
793 } else if (cooked[2].equals("changed") && cooked.length == 5) {
794 notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
795 return true;
796 } else if (cooked[2].equals("linkstate") && cooked.length == 5) {
797 notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
798 return true;
799 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900800 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700801 // break;
802 case NetdResponseCode.BandwidthControl:
803 /*
804 * Bandwidth control needs some attention
805 * Format: "NNN limit alert <alertName> <ifaceName>"
806 */
807 if (cooked.length < 5 || !cooked[1].equals("limit")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900808 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700809 }
810 if (cooked[2].equals("alert")) {
811 notifyLimitReached(cooked[3], cooked[4]);
812 return true;
813 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900814 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700815 // break;
Haoyu Baidb3c8672012-06-20 14:29:57 -0700816 case NetdResponseCode.InterfaceClassActivity:
817 /*
818 * An network interface class state changed (active/idle)
819 * Format: "NNN IfaceClass <active/idle> <label>"
820 */
821 if (cooked.length < 4 || !cooked[1].equals("IfaceClass")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900822 throw new IllegalStateException(errorMessage);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700823 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700824 long timestampNanos = 0;
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700825 int processUid = -1;
826 if (cooked.length >= 5) {
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700827 try {
828 timestampNanos = Long.parseLong(cooked[4]);
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700829 if (cooked.length == 6) {
830 processUid = Integer.parseInt(cooked[5]);
831 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700832 } catch(NumberFormatException ne) {}
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700833 } else {
834 timestampNanos = SystemClock.elapsedRealtimeNanos();
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700835 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700836 boolean isActive = cooked[2].equals("active");
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700837 notifyInterfaceClassActivity(Integer.parseInt(cooked[3]),
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700838 isActive ? DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700839 : DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
840 timestampNanos, processUid, false);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700841 return true;
842 // break;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900843 case NetdResponseCode.InterfaceAddressChange:
844 /*
845 * A network address change occurred
846 * Format: "NNN Address updated <addr> <iface> <flags> <scope>"
847 * "NNN Address removed <addr> <iface> <flags> <scope>"
848 */
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900849 if (cooked.length < 7 || !cooked[1].equals("Address")) {
850 throw new IllegalStateException(errorMessage);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900851 }
852
Lorenzo Colitti64483942013-11-15 18:43:52 +0900853 String iface = cooked[4];
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900854 LinkAddress address;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900855 try {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900856 int flags = Integer.parseInt(cooked[5]);
857 int scope = Integer.parseInt(cooked[6]);
858 address = new LinkAddress(cooked[3], flags, scope);
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900859 } catch(NumberFormatException e) { // Non-numeric lifetime or scope.
860 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti64483942013-11-15 18:43:52 +0900861 } catch(IllegalArgumentException e) { // Malformed/invalid IP address.
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900862 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900863 }
864
865 if (cooked[2].equals("updated")) {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900866 notifyAddressUpdated(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900867 } else {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900868 notifyAddressRemoved(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900869 }
870 return true;
871 // break;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900872 case NetdResponseCode.InterfaceDnsServerInfo:
873 /*
874 * Information about available DNS servers has been received.
875 * Format: "NNN DnsInfo servers <interface> <lifetime> <servers>"
876 */
877 long lifetime; // Actually a 32-bit unsigned integer.
878
879 if (cooked.length == 6 &&
880 cooked[1].equals("DnsInfo") &&
881 cooked[2].equals("servers")) {
882 try {
883 lifetime = Long.parseLong(cooked[4]);
884 } catch (NumberFormatException e) {
885 throw new IllegalStateException(errorMessage);
886 }
887 String[] servers = cooked[5].split(",");
888 notifyInterfaceDnsServerInfo(cooked[3], lifetime, servers);
889 }
890 return true;
891 // break;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900892 case NetdResponseCode.RouteChange:
893 /*
894 * A route has been updated or removed.
895 * Format: "NNN Route <updated|removed> <dst> [via <gateway] [dev <iface>]"
896 */
897 if (!cooked[1].equals("Route") || cooked.length < 6) {
898 throw new IllegalStateException(errorMessage);
899 }
900
901 String via = null;
902 String dev = null;
903 boolean valid = true;
904 for (int i = 4; (i + 1) < cooked.length && valid; i += 2) {
905 if (cooked[i].equals("dev")) {
906 if (dev == null) {
907 dev = cooked[i+1];
908 } else {
909 valid = false; // Duplicate interface.
910 }
911 } else if (cooked[i].equals("via")) {
912 if (via == null) {
913 via = cooked[i+1];
914 } else {
915 valid = false; // Duplicate gateway.
916 }
917 } else {
918 valid = false; // Unknown syntax.
919 }
920 }
921 if (valid) {
922 try {
923 // InetAddress.parseNumericAddress(null) inexplicably returns ::1.
924 InetAddress gateway = null;
925 if (via != null) gateway = InetAddress.parseNumericAddress(via);
926 RouteInfo route = new RouteInfo(new IpPrefix(cooked[3]), gateway, dev);
927 notifyRouteChange(cooked[2], route);
928 return true;
929 } catch (IllegalArgumentException e) {}
930 }
931 throw new IllegalStateException(errorMessage);
932 // break;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800933 case NetdResponseCode.StrictCleartext:
934 final int uid = Integer.parseInt(cooked[1]);
935 final byte[] firstPacket = HexDump.hexStringToByteArray(cooked[2]);
936 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800937 ActivityManager.getService().notifyCleartextNetwork(uid, firstPacket);
Jeff Sharkey605eb792014-11-04 13:34:06 -0800938 } catch (RemoteException ignored) {
939 }
940 break;
JP Abgrall12b933d2011-07-14 18:09:22 -0700941 default: break;
Robert Greenwalte3253922010-02-18 09:23:25 -0800942 }
943 return false;
San Mehat873f2142010-01-14 10:25:07 -0800944 }
945 }
946
San Mehated4fc8a2010-01-22 12:28:36 -0800947
San Mehat873f2142010-01-14 10:25:07 -0800948 //
949 // INetworkManagementService members
950 //
Erik Kline4e37b702016-07-05 11:34:21 +0900951 @Override
952 public INetd getNetdService() throws RemoteException {
953 final CountDownLatch connectedSignal = mConnectedSignal;
954 if (connectedSignal != null) {
955 try {
956 connectedSignal.await();
957 } catch (InterruptedException ignored) {}
958 }
959
960 return mNetdService;
961 }
San Mehat873f2142010-01-14 10:25:07 -0800962
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800963 @Override
964 public String[] listInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800965 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700966 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800967 return NativeDaemonEvent.filterMessageList(
968 mConnector.executeForList("interface", "list"), InterfaceListResult);
Kenny Roota80ce062010-06-01 13:23:53 -0700969 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800970 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700971 }
San Mehated4fc8a2010-01-22 12:28:36 -0800972 }
973
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800974 @Override
975 public InterfaceConfiguration getInterfaceConfig(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800976 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800977
978 final NativeDaemonEvent event;
Kenny Roota80ce062010-06-01 13:23:53 -0700979 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800980 event = mConnector.execute("interface", "getcfg", iface);
Kenny Roota80ce062010-06-01 13:23:53 -0700981 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -0800982 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -0700983 }
San Mehated4fc8a2010-01-22 12:28:36 -0800984
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800985 event.checkCode(InterfaceGetCfgResult);
986
987 // Rsp: 213 xx:xx:xx:xx:xx:xx yyy.yyy.yyy.yyy zzz flag1 flag2 flag3
988 final StringTokenizer st = new StringTokenizer(event.getMessage());
San Mehated4fc8a2010-01-22 12:28:36 -0800989
Kenny Roota80ce062010-06-01 13:23:53 -0700990 InterfaceConfiguration cfg;
San Mehated4fc8a2010-01-22 12:28:36 -0800991 try {
Kenny Roota80ce062010-06-01 13:23:53 -0700992 cfg = new InterfaceConfiguration();
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800993 cfg.setHardwareAddress(st.nextToken(" "));
Robert Greenwalted126402011-01-28 15:34:55 -0800994 InetAddress addr = null;
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800995 int prefixLength = 0;
Kenny Roota80ce062010-06-01 13:23:53 -0700996 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800997 addr = NetworkUtils.numericToInetAddress(st.nextToken());
Robert Greenwalte5903732011-02-22 16:00:42 -0800998 } catch (IllegalArgumentException iae) {
999 Slog.e(TAG, "Failed to parse ipaddr", iae);
Kenny Roota80ce062010-06-01 13:23:53 -07001000 }
1001
1002 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001003 prefixLength = Integer.parseInt(st.nextToken());
Robert Greenwalt2d2afd12011-02-01 15:30:46 -08001004 } catch (NumberFormatException nfe) {
1005 Slog.e(TAG, "Failed to parse prefixLength", nfe);
Kenny Roota80ce062010-06-01 13:23:53 -07001006 }
Robert Greenwalt04808c22010-12-13 17:01:41 -08001007
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001008 cfg.setLinkAddress(new LinkAddress(addr, prefixLength));
1009 while (st.hasMoreTokens()) {
1010 cfg.setFlag(st.nextToken());
1011 }
Kenny Roota80ce062010-06-01 13:23:53 -07001012 } catch (NoSuchElementException nsee) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001013 throw new IllegalStateException("Invalid response from daemon: " + event);
San Mehated4fc8a2010-01-22 12:28:36 -08001014 }
San Mehated4fc8a2010-01-22 12:28:36 -08001015 return cfg;
1016 }
1017
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001018 @Override
1019 public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001020 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001021 LinkAddress linkAddr = cfg.getLinkAddress();
Robert Greenwalt2d2afd12011-02-01 15:30:46 -08001022 if (linkAddr == null || linkAddr.getAddress() == null) {
1023 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -08001024 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001025
1026 final Command cmd = new Command("interface", "setcfg", iface,
Robert Greenwalt2d2afd12011-02-01 15:30:46 -08001027 linkAddr.getAddress().getHostAddress(),
Lorenzo Colitti7dc78cf2014-06-09 22:58:46 +09001028 linkAddr.getPrefixLength());
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001029 for (String flag : cfg.getFlags()) {
1030 cmd.appendArg(flag);
1031 }
1032
Kenny Roota80ce062010-06-01 13:23:53 -07001033 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001034 mConnector.execute(cmd);
Kenny Roota80ce062010-06-01 13:23:53 -07001035 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001036 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001037 }
San Mehat873f2142010-01-14 10:25:07 -08001038 }
1039
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001040 @Override
1041 public void setInterfaceDown(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001042 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001043 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001044 ifcg.setInterfaceDown();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001045 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001046 }
1047
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001048 @Override
1049 public void setInterfaceUp(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001050 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001051 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001052 ifcg.setInterfaceUp();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001053 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001054 }
1055
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001056 @Override
1057 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001058 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sheriff73293612011-09-14 12:31:56 -07001059 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001060 mConnector.execute(
1061 "interface", "ipv6privacyextensions", iface, enable ? "enable" : "disable");
Irfan Sheriff73293612011-09-14 12:31:56 -07001062 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001063 throw e.rethrowAsParcelableException();
Irfan Sheriff73293612011-09-14 12:31:56 -07001064 }
1065 }
1066
Irfan Sherifff5600612011-06-16 10:26:28 -07001067 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
1068 IPv6 addresses on interface down, but we need to do full clean up here */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001069 @Override
1070 public void clearInterfaceAddresses(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001071 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sherifff5600612011-06-16 10:26:28 -07001072 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001073 mConnector.execute("interface", "clearaddrs", iface);
Irfan Sherifff5600612011-06-16 10:26:28 -07001074 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001075 throw e.rethrowAsParcelableException();
Irfan Sherifff5600612011-06-16 10:26:28 -07001076 }
1077 }
1078
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001079 @Override
1080 public void enableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001081 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001082 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001083 mConnector.execute("interface", "ipv6", iface, "enable");
repo sync7960d9f2011-09-29 12:40:02 -07001084 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001085 throw e.rethrowAsParcelableException();
repo sync7960d9f2011-09-29 12:40:02 -07001086 }
1087 }
1088
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001089 @Override
Joel Scherpelz2db10742017-06-07 15:38:38 +09001090 public void setIPv6AddrGenMode(String iface, int mode) throws ServiceSpecificException {
1091 try {
1092 mNetdService.setIPv6AddrGenMode(iface, mode);
1093 } catch (RemoteException e) {
1094 throw e.rethrowAsRuntimeException();
1095 }
1096 }
1097
1098 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001099 public void disableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001100 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001101 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001102 mConnector.execute("interface", "ipv6", iface, "disable");
repo sync7960d9f2011-09-29 12:40:02 -07001103 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001104 throw e.rethrowAsParcelableException();
repo sync7960d9f2011-09-29 12:40:02 -07001105 }
1106 }
1107
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001108 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001109 public void addRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001110 modifyRoute(MODIFY_OPERATION_ADD, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001111 }
1112
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001113 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001114 public void removeRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001115 modifyRoute(MODIFY_OPERATION_REMOVE, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001116 }
1117
Luke Huang8a462ec2018-08-24 20:33:16 +08001118 private void modifyRoute(boolean add, int netId, RouteInfo route) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001119 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001120
Luke Huang8a462ec2018-08-24 20:33:16 +08001121 final String ifName = route.getInterface();
1122 final String dst = route.getDestination().toString();
1123 final String nextHop;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001124
1125 switch (route.getType()) {
1126 case RouteInfo.RTN_UNICAST:
1127 if (route.hasGateway()) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001128 nextHop = route.getGateway().getHostAddress();
1129 } else {
1130 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001131 }
1132 break;
1133 case RouteInfo.RTN_UNREACHABLE:
Luke Huang8a462ec2018-08-24 20:33:16 +08001134 nextHop = INetd.NEXTHOP_UNREACHABLE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001135 break;
1136 case RouteInfo.RTN_THROW:
Luke Huang8a462ec2018-08-24 20:33:16 +08001137 nextHop = INetd.NEXTHOP_THROW;
1138 break;
1139 default:
1140 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001141 break;
Sreeram Ramachandran1fbcb272014-05-22 16:30:48 -07001142 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001143 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08001144 if (add) {
1145 mNetdService.networkAddRoute(netId, ifName, dst, nextHop);
1146 } else {
1147 mNetdService.networkRemoveRoute(netId, ifName, dst, nextHop);
1148 }
1149 } catch (RemoteException | ServiceSpecificException e) {
1150 throw new IllegalStateException(e);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001151 }
1152 }
1153
1154 private ArrayList<String> readRouteList(String filename) {
1155 FileInputStream fstream = null;
Christopher Wiley212b95f2016-08-02 11:38:57 -07001156 ArrayList<String> list = new ArrayList<>();
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001157
1158 try {
1159 fstream = new FileInputStream(filename);
1160 DataInputStream in = new DataInputStream(fstream);
1161 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1162 String s;
1163
1164 // throw away the title line
1165
1166 while (((s = br.readLine()) != null) && (s.length() != 0)) {
1167 list.add(s);
1168 }
1169 } catch (IOException ex) {
1170 // return current list, possibly empty
1171 } finally {
1172 if (fstream != null) {
1173 try {
1174 fstream.close();
1175 } catch (IOException ex) {}
1176 }
1177 }
1178
1179 return list;
1180 }
1181
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001182 @Override
sy.yun9d9b74a2013-09-02 05:24:09 +09001183 public void setMtu(String iface, int mtu) {
1184 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1185
1186 final NativeDaemonEvent event;
1187 try {
1188 event = mConnector.execute("interface", "setmtu", iface, mtu);
1189 } catch (NativeDaemonConnectorException e) {
1190 throw e.rethrowAsParcelableException();
1191 }
1192 }
1193
1194 @Override
San Mehat873f2142010-01-14 10:25:07 -08001195 public void shutdown() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001196 // TODO: remove from aidl if nobody calls externally
1197 mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001198
Felipe Leme03e689d2016-03-02 16:17:38 -08001199 Slog.i(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -08001200 }
1201
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001202 @Override
San Mehat873f2142010-01-14 10:25:07 -08001203 public boolean getIpForwardingEnabled() throws IllegalStateException{
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001204 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001205
Kenny Roota80ce062010-06-01 13:23:53 -07001206 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001207 final boolean isEnabled = mNetdService.ipfwdEnabled();
1208 return isEnabled;
1209 } catch (RemoteException | ServiceSpecificException e) {
1210 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001211 }
San Mehat873f2142010-01-14 10:25:07 -08001212 }
1213
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001214 @Override
1215 public void setIpForwardingEnabled(boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001216 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001217 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001218 if (enable) {
1219 mNetdService.ipfwdEnableForwarding("tethering");
1220 } else {
1221 mNetdService.ipfwdDisableForwarding("tethering");
1222 }
1223 } catch (RemoteException | ServiceSpecificException e) {
1224 throw new IllegalStateException(e);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001225 }
San Mehat873f2142010-01-14 10:25:07 -08001226 }
1227
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001228 @Override
1229 public void startTethering(String[] dhcpRange) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001230 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -07001231 // an odd number of addrs will fail
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001232
Kenny Roota80ce062010-06-01 13:23:53 -07001233 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001234 mNetdService.tetherStart(dhcpRange);
1235 } catch (RemoteException | ServiceSpecificException e) {
1236 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001237 }
San Mehat873f2142010-01-14 10:25:07 -08001238 }
1239
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001240 @Override
1241 public void stopTethering() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001242 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001243 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001244 mNetdService.tetherStop();
1245 } catch (RemoteException | ServiceSpecificException e) {
1246 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001247 }
San Mehat873f2142010-01-14 10:25:07 -08001248 }
1249
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001250 @Override
1251 public boolean isTetheringStarted() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001252 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001253
Kenny Roota80ce062010-06-01 13:23:53 -07001254 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001255 final boolean isEnabled = mNetdService.tetherIsEnabled();
1256 return isEnabled;
1257 } catch (RemoteException | ServiceSpecificException e) {
1258 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001259 }
San Mehat873f2142010-01-14 10:25:07 -08001260 }
Matthew Xiefe19f122012-07-12 16:03:32 -07001261
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001262 @Override
1263 public void tetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001264 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001265 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001266 mNetdService.tetherInterfaceAdd(iface);
1267 } catch (RemoteException | ServiceSpecificException e) {
1268 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001269 }
Christopher Wiley212b95f2016-08-02 11:38:57 -07001270 List<RouteInfo> routes = new ArrayList<>();
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07001271 // The RouteInfo constructor truncates the LinkAddress to a network prefix, thus making it
1272 // suitable to use as a route destination.
1273 routes.add(new RouteInfo(getInterfaceConfig(iface).getLinkAddress(), null, iface));
1274 addInterfaceToLocalNetwork(iface, routes);
San Mehat873f2142010-01-14 10:25:07 -08001275 }
1276
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001277 @Override
San Mehat873f2142010-01-14 10:25:07 -08001278 public void untetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001279 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001280 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001281 mNetdService.tetherInterfaceRemove(iface);
1282 } catch (RemoteException | ServiceSpecificException e) {
1283 throw new IllegalStateException(e);
Erik Kline1f4278a2016-08-16 16:46:33 +09001284 } finally {
1285 removeInterfaceFromLocalNetwork(iface);
Kenny Roota80ce062010-06-01 13:23:53 -07001286 }
San Mehat873f2142010-01-14 10:25:07 -08001287 }
1288
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001289 @Override
1290 public String[] listTetheredInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001291 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001292 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001293 final List<String> result = mNetdService.tetherInterfaceList();
1294 return result.toArray(EMPTY_STRING_ARRAY);
1295 } catch (RemoteException | ServiceSpecificException e) {
1296 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001297 }
San Mehat873f2142010-01-14 10:25:07 -08001298 }
1299
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001300 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001301 public void setDnsForwarders(Network network, String[] dns) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001302 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001303
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001304 int netId = (network != null) ? network.netId : ConnectivityManager.NETID_UNSET;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001305
San Mehat873f2142010-01-14 10:25:07 -08001306 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001307 mNetdService.tetherDnsSet(netId, dns);
1308 } catch (RemoteException | ServiceSpecificException e) {
1309 throw new IllegalStateException(e);
San Mehat873f2142010-01-14 10:25:07 -08001310 }
1311 }
1312
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001313 @Override
1314 public String[] getDnsForwarders() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001315 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001316 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001317 final List<String> result = mNetdService.tetherDnsList();
1318 return result.toArray(EMPTY_STRING_ARRAY);
1319 } catch (RemoteException | ServiceSpecificException e) {
1320 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001321 }
San Mehat873f2142010-01-14 10:25:07 -08001322 }
1323
jiaguo1da35f72014-01-09 16:39:59 +08001324 private List<InterfaceAddress> excludeLinkLocal(List<InterfaceAddress> addresses) {
Christopher Wiley212b95f2016-08-02 11:38:57 -07001325 ArrayList<InterfaceAddress> filtered = new ArrayList<>(addresses.size());
jiaguo1da35f72014-01-09 16:39:59 +08001326 for (InterfaceAddress ia : addresses) {
1327 if (!ia.getAddress().isLinkLocalAddress())
1328 filtered.add(ia);
1329 }
1330 return filtered;
1331 }
1332
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001333 private void modifyInterfaceForward(boolean add, String fromIface, String toIface) {
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001334 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001335 if (add) {
1336 mNetdService.ipfwdAddInterfaceForward(fromIface, toIface);
1337 } else {
1338 mNetdService.ipfwdRemoveInterfaceForward(fromIface, toIface);
1339 }
1340 } catch (RemoteException | ServiceSpecificException e) {
1341 throw new IllegalStateException(e);
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001342 }
1343 }
1344
1345 @Override
1346 public void startInterfaceForwarding(String fromIface, String toIface) {
1347 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1348 modifyInterfaceForward(true, fromIface, toIface);
1349 }
1350
1351 @Override
1352 public void stopInterfaceForwarding(String fromIface, String toIface) {
1353 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1354 modifyInterfaceForward(false, fromIface, toIface);
1355 }
1356
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001357 private void modifyNat(String action, String internalInterface, String externalInterface)
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001358 throws SocketException {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001359 final Command cmd = new Command("nat", action, internalInterface, externalInterface);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001360
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001361 final NetworkInterface internalNetworkInterface = NetworkInterface.getByName(
1362 internalInterface);
Robert Greenwalte83d1812011-11-21 14:44:39 -08001363 if (internalNetworkInterface == null) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001364 cmd.appendArg("0");
Robert Greenwalte83d1812011-11-21 14:44:39 -08001365 } else {
jiaguo1da35f72014-01-09 16:39:59 +08001366 // Don't touch link-local routes, as link-local addresses aren't routable,
1367 // kernel creates link-local routes on all interfaces automatically
1368 List<InterfaceAddress> interfaceAddresses = excludeLinkLocal(
1369 internalNetworkInterface.getInterfaceAddresses());
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001370 cmd.appendArg(interfaceAddresses.size());
Robert Greenwalte83d1812011-11-21 14:44:39 -08001371 for (InterfaceAddress ia : interfaceAddresses) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001372 InetAddress addr = NetworkUtils.getNetworkPart(
1373 ia.getAddress(), ia.getNetworkPrefixLength());
1374 cmd.appendArg(addr.getHostAddress() + "/" + ia.getNetworkPrefixLength());
Robert Greenwalte83d1812011-11-21 14:44:39 -08001375 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001376 }
1377
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001378 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001379 mConnector.execute(cmd);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001380 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001381 throw e.rethrowAsParcelableException();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001382 }
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001383 }
1384
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001385 @Override
1386 public void enableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001387 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001388 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001389 modifyNat("enable", internalInterface, externalInterface);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001390 } catch (SocketException e) {
1391 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001392 }
San Mehat873f2142010-01-14 10:25:07 -08001393 }
1394
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001395 @Override
1396 public void disableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001397 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001398 try {
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001399 modifyNat("disable", internalInterface, externalInterface);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001400 } catch (SocketException e) {
1401 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001402 }
San Mehat873f2142010-01-14 10:25:07 -08001403 }
San Mehat72759df2010-01-19 13:50:37 -08001404
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001405 @Override
1406 public String[] listTtys() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001407 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001408 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001409 return NativeDaemonEvent.filterMessageList(
1410 mConnector.executeForList("list_ttys"), TtyListResult);
Kenny Roota80ce062010-06-01 13:23:53 -07001411 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001412 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001413 }
San Mehat72759df2010-01-19 13:50:37 -08001414 }
1415
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001416 @Override
1417 public void attachPppd(
1418 String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001419 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat72759df2010-01-19 13:50:37 -08001420 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001421 mConnector.execute("pppd", "attach", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -08001422 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
1423 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
1424 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001425 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress());
Kenny Roota80ce062010-06-01 13:23:53 -07001426 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001427 throw e.rethrowAsParcelableException();
San Mehat72759df2010-01-19 13:50:37 -08001428 }
1429 }
1430
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001431 @Override
1432 public void detachPppd(String tty) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001433 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001434 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001435 mConnector.execute("pppd", "detach", tty);
Kenny Roota80ce062010-06-01 13:23:53 -07001436 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001437 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001438 }
San Mehat72759df2010-01-19 13:50:37 -08001439 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -08001440
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001441 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001442 public void addIdleTimer(String iface, int timeout, final int type) {
Haoyu Bai04124232012-06-28 15:26:19 -07001443 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1444
1445 if (DBG) Slog.d(TAG, "Adding idletimer");
1446
1447 synchronized (mIdleTimerLock) {
1448 IdleTimerParams params = mActiveIdleTimers.get(iface);
1449 if (params != null) {
1450 // the interface already has idletimer, update network count
1451 params.networkCount++;
1452 return;
1453 }
1454
1455 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001456 mNetdService.idletimerAddInterface(iface, timeout, Integer.toString(type));
1457 } catch (RemoteException | ServiceSpecificException e) {
1458 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001459 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001460 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
1461
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001462 // Networks start up.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001463 if (ConnectivityManager.isNetworkTypeMobile(type)) {
1464 mNetworkActive = false;
1465 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001466 mDaemonHandler.post(new Runnable() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001467 @Override public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001468 notifyInterfaceClassActivity(type,
1469 DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07001470 SystemClock.elapsedRealtimeNanos(), -1, false);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001471 }
1472 });
Haoyu Bai04124232012-06-28 15:26:19 -07001473 }
1474 }
1475
1476 @Override
1477 public void removeIdleTimer(String iface) {
1478 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1479
1480 if (DBG) Slog.d(TAG, "Removing idletimer");
1481
1482 synchronized (mIdleTimerLock) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001483 final IdleTimerParams params = mActiveIdleTimers.get(iface);
Haoyu Bai04124232012-06-28 15:26:19 -07001484 if (params == null || --(params.networkCount) > 0) {
1485 return;
1486 }
1487
1488 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001489 mNetdService.idletimerRemoveInterface(iface,
1490 params.timeout, Integer.toString(params.type));
1491 } catch (RemoteException | ServiceSpecificException e) {
1492 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001493 }
1494 mActiveIdleTimers.remove(iface);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001495 mDaemonHandler.post(new Runnable() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001496 @Override public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001497 notifyInterfaceClassActivity(params.type,
1498 DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07001499 SystemClock.elapsedRealtimeNanos(), -1, false);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001500 }
1501 });
Haoyu Bai04124232012-06-28 15:26:19 -07001502 }
1503 }
1504
1505 @Override
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001506 public NetworkStats getNetworkStatsSummaryDev() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001507 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001508 try {
1509 return mStatsFactory.readNetworkStatsSummaryDev();
1510 } catch (IOException e) {
1511 throw new IllegalStateException(e);
1512 }
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001513 }
1514
1515 @Override
1516 public NetworkStats getNetworkStatsSummaryXt() {
1517 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001518 try {
1519 return mStatsFactory.readNetworkStatsSummaryXt();
1520 } catch (IOException e) {
1521 throw new IllegalStateException(e);
1522 }
Jeff Sharkeyae2c1812011-10-04 13:11:40 -07001523 }
1524
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001525 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001526 public NetworkStats getNetworkStatsDetail() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001527 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001528 try {
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08001529 return mStatsFactory.readNetworkStatsDetail(UID_ALL, null, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001530 } catch (IOException e) {
1531 throw new IllegalStateException(e);
1532 }
San Mehat91cac642010-03-31 14:31:36 -07001533 }
1534
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001535 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001536 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001537 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001538
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001539 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001540 if (mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001541 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001542 }
1543
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001544 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001545 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001546 mNetdService.bandwidthSetInterfaceQuota(iface, quotaBytes);
1547
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001548 mActiveQuotas.put(iface, quotaBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001549 } catch (RemoteException | ServiceSpecificException e) {
1550 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001551 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001552
1553 synchronized (mTetheringStatsProviders) {
1554 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1555 try {
1556 provider.setInterfaceQuota(iface, quotaBytes);
1557 } catch (RemoteException e) {
1558 Log.e(TAG, "Problem setting tethering data limit on provider " +
1559 mTetheringStatsProviders.get(provider) + ": " + e);
1560 }
1561 }
1562 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001563 }
1564 }
1565
1566 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001567 public void removeInterfaceQuota(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001568 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001569
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001570 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001571 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001572 // TODO: eventually consider throwing
1573 return;
1574 }
1575
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001576 mActiveQuotas.remove(iface);
1577 mActiveAlerts.remove(iface);
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001578
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001579 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001580 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001581 mNetdService.bandwidthRemoveInterfaceQuota(iface);
1582 } catch (RemoteException | ServiceSpecificException e) {
1583 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001584 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001585
1586 synchronized (mTetheringStatsProviders) {
1587 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1588 try {
1589 provider.setInterfaceQuota(iface, ITetheringStatsProvider.QUOTA_UNLIMITED);
1590 } catch (RemoteException e) {
1591 Log.e(TAG, "Problem removing tethering data limit on provider " +
1592 mTetheringStatsProviders.get(provider) + ": " + e);
1593 }
1594 }
1595 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001596 }
1597 }
1598
1599 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001600 public void setInterfaceAlert(String iface, long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001601 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001602
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001603 // quick sanity check
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001604 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001605 throw new IllegalStateException("setting alert requires existing quota on iface");
1606 }
1607
1608 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001609 if (mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001610 throw new IllegalStateException("iface " + iface + " already has alert");
1611 }
1612
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001613 try {
1614 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001615 mNetdService.bandwidthSetInterfaceAlert(iface, alertBytes);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001616 mActiveAlerts.put(iface, alertBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001617 } catch (RemoteException | ServiceSpecificException e) {
1618 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001619 }
1620 }
1621 }
1622
1623 @Override
1624 public void removeInterfaceAlert(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001625 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001626
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001627 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001628 if (!mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001629 // TODO: eventually consider throwing
1630 return;
1631 }
1632
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001633 try {
1634 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001635 mNetdService.bandwidthRemoveInterfaceAlert(iface);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001636 mActiveAlerts.remove(iface);
Luke Huangc7bea8662018-08-07 16:04:26 +08001637 } catch (RemoteException | ServiceSpecificException e) {
1638 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001639 }
1640 }
1641 }
1642
1643 @Override
1644 public void setGlobalAlert(long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001645 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001646
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001647 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001648 mNetdService.bandwidthSetGlobalAlert(alertBytes);
1649 } catch (RemoteException | ServiceSpecificException e) {
1650 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001651 }
1652 }
1653
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001654 private void setUidOnMeteredNetworkList(int uid, boolean blacklist, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001655 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001656
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001657 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001658 boolean oldEnable;
1659 SparseBooleanArray quotaList;
1660 synchronized (mRulesLock) {
1661 quotaList = blacklist ? mUidRejectOnMetered : mUidAllowOnMetered;
1662 oldEnable = quotaList.get(uid, false);
1663 }
Felipe Leme65be3022016-03-22 14:53:13 -07001664 if (oldEnable == enable) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001665 // TODO: eventually consider throwing
1666 return;
1667 }
1668
Felipe Leme29e72ea2016-09-08 13:26:55 -07001669 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "inetd bandwidth");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001670 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001671 if (blacklist) {
1672 if (enable) {
1673 mNetdService.bandwidthAddNaughtyApp(uid);
1674 } else {
1675 mNetdService.bandwidthRemoveNaughtyApp(uid);
1676 }
1677 } else {
1678 if (enable) {
1679 mNetdService.bandwidthAddNiceApp(uid);
1680 } else {
1681 mNetdService.bandwidthRemoveNiceApp(uid);
1682 }
1683 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001684 synchronized (mRulesLock) {
1685 if (enable) {
1686 quotaList.put(uid, true);
1687 } else {
1688 quotaList.delete(uid);
1689 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001690 }
Luke Huangc7bea8662018-08-07 16:04:26 +08001691 } catch (RemoteException | ServiceSpecificException e) {
1692 throw new IllegalStateException(e);
Felipe Leme29e72ea2016-09-08 13:26:55 -07001693 } finally {
1694 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001695 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001696 }
1697 }
1698
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001699 @Override
Felipe Leme65be3022016-03-22 14:53:13 -07001700 public void setUidMeteredNetworkBlacklist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001701 setUidOnMeteredNetworkList(uid, true, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001702 }
1703
1704 @Override
1705 public void setUidMeteredNetworkWhitelist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001706 setUidOnMeteredNetworkList(uid, false, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001707 }
1708
1709 @Override
1710 public boolean setDataSaverModeEnabled(boolean enable) {
Sehee Parka9139bc2017-12-22 13:54:05 +09001711 mContext.enforceCallingOrSelfPermission(NETWORK_SETTINGS, TAG);
1712
Felipe Leme65be3022016-03-22 14:53:13 -07001713 if (DBG) Log.d(TAG, "setDataSaverMode: " + enable);
1714 synchronized (mQuotaLock) {
1715 if (mDataSaverMode == enable) {
1716 Log.w(TAG, "setDataSaverMode(): already " + mDataSaverMode);
1717 return true;
1718 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07001719 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "bandwidthEnableDataSaver");
Felipe Leme65be3022016-03-22 14:53:13 -07001720 try {
1721 final boolean changed = mNetdService.bandwidthEnableDataSaver(enable);
1722 if (changed) {
1723 mDataSaverMode = enable;
1724 } else {
1725 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command silently failed");
1726 }
1727 return changed;
1728 } catch (RemoteException e) {
1729 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command failed", e);
1730 return false;
Felipe Leme29e72ea2016-09-08 13:26:55 -07001731 } finally {
1732 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme65be3022016-03-22 14:53:13 -07001733 }
1734 }
1735 }
1736
1737 @Override
Robin Lee17e61832016-05-09 13:46:28 +01001738 public void setAllowOnlyVpnForUids(boolean add, UidRange[] uidRanges)
1739 throws ServiceSpecificException {
Rubin Xu2ea6c552018-01-11 10:59:19 +00001740 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
1741
Robin Lee17e61832016-05-09 13:46:28 +01001742 try {
1743 mNetdService.networkRejectNonSecureVpn(add, uidRanges);
1744 } catch (ServiceSpecificException e) {
1745 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1746 + ": netd command failed", e);
1747 throw e;
1748 } catch (RemoteException e) {
1749 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1750 + ": netd command failed", e);
1751 throw e.rethrowAsRuntimeException();
1752 }
1753 }
1754
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001755 private void applyUidCleartextNetworkPolicy(int uid, int policy) {
Luke Huang473eb872018-07-26 17:33:14 +08001756 final int policyValue;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001757 switch (policy) {
1758 case StrictMode.NETWORK_POLICY_ACCEPT:
Luke Huang473eb872018-07-26 17:33:14 +08001759 policyValue = INetd.PENALTY_POLICY_ACCEPT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001760 break;
1761 case StrictMode.NETWORK_POLICY_LOG:
Luke Huang473eb872018-07-26 17:33:14 +08001762 policyValue = INetd.PENALTY_POLICY_LOG;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001763 break;
1764 case StrictMode.NETWORK_POLICY_REJECT:
Luke Huang473eb872018-07-26 17:33:14 +08001765 policyValue = INetd.PENALTY_POLICY_REJECT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001766 break;
1767 default:
1768 throw new IllegalArgumentException("Unknown policy " + policy);
1769 }
1770
1771 try {
Luke Huang473eb872018-07-26 17:33:14 +08001772 mNetdService.strictUidCleartextPenalty(uid, policyValue);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001773 mUidCleartextPolicy.put(uid, policy);
Luke Huang473eb872018-07-26 17:33:14 +08001774 } catch (RemoteException | ServiceSpecificException e) {
1775 throw new IllegalStateException(e);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001776 }
1777 }
1778
Robin Lee17e61832016-05-09 13:46:28 +01001779 @Override
Jeff Sharkey605eb792014-11-04 13:34:06 -08001780 public void setUidCleartextNetworkPolicy(int uid, int policy) {
1781 if (Binder.getCallingUid() != uid) {
1782 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1783 }
1784
1785 synchronized (mQuotaLock) {
1786 final int oldPolicy = mUidCleartextPolicy.get(uid, StrictMode.NETWORK_POLICY_ACCEPT);
1787 if (oldPolicy == policy) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001788 // This also ensures we won't needlessly apply an ACCEPT policy if we've just
1789 // enabled strict and the underlying iptables rules are empty.
Jeff Sharkey605eb792014-11-04 13:34:06 -08001790 return;
1791 }
1792
Luke Huang473eb872018-07-26 17:33:14 +08001793 // TODO: remove this code after removing prepareNativeDaemon()
Jeff Sharkey605eb792014-11-04 13:34:06 -08001794 if (!mStrictEnabled) {
1795 // Module isn't enabled yet; stash the requested policy away to
1796 // apply later once the daemon is connected.
1797 mUidCleartextPolicy.put(uid, policy);
1798 return;
1799 }
1800
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001801 // netd does not keep state on strict mode policies, and cannot replace a non-accept
1802 // policy without deleting it first. Rather than add state to netd, just always send
1803 // it an accept policy when switching between two non-accept policies.
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001804 // TODO: consider keeping state in netd so we can simplify this code.
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001805 if (oldPolicy != StrictMode.NETWORK_POLICY_ACCEPT &&
1806 policy != StrictMode.NETWORK_POLICY_ACCEPT) {
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001807 applyUidCleartextNetworkPolicy(uid, StrictMode.NETWORK_POLICY_ACCEPT);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001808 }
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001809
1810 applyUidCleartextNetworkPolicy(uid, policy);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001811 }
1812 }
1813
1814 @Override
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001815 public boolean isBandwidthControlEnabled() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001816 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang56a03a02018-09-07 12:02:16 +08001817 return true;
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001818 }
1819
1820 @Override
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001821 public NetworkStats getNetworkStatsUidDetail(int uid, String[] ifaces) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001822 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001823 try {
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001824 return mStatsFactory.readNetworkStatsDetail(uid, ifaces, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001825 } catch (IOException e) {
1826 throw new IllegalStateException(e);
1827 }
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001828 }
1829
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001830 private class NetdTetheringStatsProvider extends ITetheringStatsProvider.Stub {
1831 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001832 public NetworkStats getTetherStats(int how) {
1833 // We only need to return per-UID stats. Per-device stats are already counted by
1834 // interface counters.
1835 if (how != STATS_PER_UID) {
1836 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
1837 }
1838
Luke Huang13b79e82018-09-26 14:53:42 +08001839 final TetherStatsParcel[] tetherStatsVec;
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001840 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001841 tetherStatsVec = mNetdService.tetherGetStats();
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001842 } catch (RemoteException | ServiceSpecificException e) {
1843 throw new IllegalStateException("problem parsing tethering stats: ", e);
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001844 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001845
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001846 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(),
Luke Huang13b79e82018-09-26 14:53:42 +08001847 tetherStatsVec.length);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001848 final NetworkStats.Entry entry = new NetworkStats.Entry();
1849
Luke Huang13b79e82018-09-26 14:53:42 +08001850 for (TetherStatsParcel tetherStats : tetherStatsVec) {
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001851 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001852 entry.iface = tetherStats.iface;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001853 entry.uid = UID_TETHERING;
1854 entry.set = SET_DEFAULT;
1855 entry.tag = TAG_NONE;
Luke Huang13b79e82018-09-26 14:53:42 +08001856 entry.rxBytes = tetherStats.rxBytes;
1857 entry.rxPackets = tetherStats.rxPackets;
1858 entry.txBytes = tetherStats.txBytes;
1859 entry.txPackets = tetherStats.txPackets;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001860 stats.combineValues(entry);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001861 } catch (ArrayIndexOutOfBoundsException e) {
Luke Huang13b79e82018-09-26 14:53:42 +08001862 throw new IllegalStateException("invalid tethering stats " + e);
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001863 }
1864 }
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001865
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001866 return stats;
1867 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001868
1869 @Override
1870 public void setInterfaceQuota(String iface, long quotaBytes) {
1871 // Do nothing. netd is already informed of quota changes in setInterfaceQuota.
1872 }
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001873 }
1874
1875 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001876 public NetworkStats getNetworkStatsTethering(int how) {
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001877 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1878
1879 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1880 synchronized (mTetheringStatsProviders) {
1881 for (ITetheringStatsProvider provider: mTetheringStatsProviders.keySet()) {
1882 try {
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001883 stats.combineAllValues(provider.getTetherStats(how));
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001884 } catch (RemoteException e) {
1885 Log.e(TAG, "Problem reading tethering stats from " +
1886 mTetheringStatsProviders.get(provider) + ": " + e);
1887 }
1888 }
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001889 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001890 return stats;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001891 }
1892
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001893 @Override
Erik Kline1742fe12017-12-13 19:40:49 +09001894 public void setDnsConfigurationForNetwork(int netId, String[] servers, String[] domains,
Erik Klinee5dac902018-03-04 21:01:01 +09001895 int[] params, String tlsHostname, String[] tlsServers) {
Pierre Imai8e48e672016-04-21 13:30:43 +09001896 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1897
Ben Schwartz6ec28df2017-10-02 13:08:06 -04001898 final String[] tlsFingerprints = new String[0];
Pierre Imai8e48e672016-04-21 13:30:43 +09001899 try {
Erik Kline1742fe12017-12-13 19:40:49 +09001900 mNetdService.setResolverConfiguration(
Erik Klinee5dac902018-03-04 21:01:01 +09001901 netId, servers, domains, params, tlsHostname, tlsServers, tlsFingerprints);
Pierre Imai8e48e672016-04-21 13:30:43 +09001902 } catch (RemoteException e) {
1903 throw new RuntimeException(e);
1904 }
1905 }
1906
1907 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001908 public void addVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001909 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001910
1911 try {
1912 mNetdService.networkAddUidRanges(netId, ranges);
1913 } catch (RemoteException | ServiceSpecificException e) {
1914 throw new IllegalStateException(e);
Chad Brubaker3277620a2013-06-12 13:37:30 -07001915 }
1916 }
1917
1918 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001919 public void removeVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001920 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001921 try {
1922 mNetdService.networkRemoveUidRanges(netId, ranges);
1923 } catch (RemoteException | ServiceSpecificException e) {
1924 throw new IllegalStateException(e);
Chad Brubakercca54c42013-06-27 17:41:38 -07001925 }
1926 }
1927
1928 @Override
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001929 public void setFirewallEnabled(boolean enabled) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001930 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001931 try {
Luke Huanga241db92018-07-31 20:15:24 +08001932 mNetdService.firewallSetFirewallType(
1933 enabled ? INetd.FIREWALL_WHITELIST : INetd.FIREWALL_BLACKLIST);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001934 mFirewallEnabled = enabled;
Luke Huanga241db92018-07-31 20:15:24 +08001935 } catch (RemoteException | ServiceSpecificException e) {
1936 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001937 }
1938 }
1939
1940 @Override
1941 public boolean isFirewallEnabled() {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001942 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001943 return mFirewallEnabled;
1944 }
1945
1946 @Override
Jeff Sharkey2c092982012-08-24 11:44:40 -07001947 public void setFirewallInterfaceRule(String iface, boolean allow) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001948 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001949 Preconditions.checkState(mFirewallEnabled);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001950 try {
Luke Huanga241db92018-07-31 20:15:24 +08001951 mNetdService.firewallSetInterfaceRule(iface,
1952 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
1953 } catch (RemoteException | ServiceSpecificException e) {
1954 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001955 }
1956 }
1957
Lorenzo Colitti3fef7232016-04-29 18:00:03 +09001958 private void closeSocketsForFirewallChainLocked(int chain, String chainName) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001959 // UID ranges to close sockets on.
1960 UidRange[] ranges;
1961 // UID ranges whose sockets we won't touch.
1962 int[] exemptUids;
1963
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001964 int numUids = 0;
Luke Huanga241db92018-07-31 20:15:24 +08001965 if (DBG) Slog.d(TAG, "Closing sockets after enabling chain " + chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001966 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
1967 // Close all sockets on all non-system UIDs...
1968 ranges = new UidRange[] {
1969 // TODO: is there a better way of finding all existing users? If so, we could
1970 // specify their ranges here.
1971 new UidRange(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE),
1972 };
1973 // ... except for the UIDs that have allow rules.
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001974 synchronized (mRulesLock) {
1975 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1976 exemptUids = new int[rules.size()];
1977 for (int i = 0; i < exemptUids.length; i++) {
1978 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
1979 exemptUids[numUids] = rules.keyAt(i);
1980 numUids++;
1981 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001982 }
1983 }
1984 // Normally, whitelist chains only contain deny rules, so numUids == exemptUids.length.
1985 // But the code does not guarantee this in any way, and at least in one case - if we add
1986 // a UID rule to the firewall, and then disable the firewall - the chains can contain
1987 // the wrong type of rule. In this case, don't close connections that we shouldn't.
1988 //
1989 // TODO: tighten up this code by ensuring we never set the wrong type of rule, and
1990 // fix setFirewallEnabled to grab mQuotaLock and clear rules.
1991 if (numUids != exemptUids.length) {
1992 exemptUids = Arrays.copyOf(exemptUids, numUids);
1993 }
1994 } else {
1995 // Close sockets for every UID that has a deny rule...
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001996 synchronized (mRulesLock) {
1997 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1998 ranges = new UidRange[rules.size()];
1999 for (int i = 0; i < ranges.length; i++) {
2000 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_DENY) {
2001 int uid = rules.keyAt(i);
2002 ranges[numUids] = new UidRange(uid, uid);
2003 numUids++;
2004 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002005 }
2006 }
2007 // As above; usually numUids == ranges.length, but not always.
2008 if (numUids != ranges.length) {
2009 ranges = Arrays.copyOf(ranges, numUids);
2010 }
2011 // ... with no exceptions.
2012 exemptUids = new int[0];
2013 }
2014
2015 try {
2016 mNetdService.socketDestroy(ranges, exemptUids);
2017 } catch(RemoteException | ServiceSpecificException e) {
2018 Slog.e(TAG, "Error closing sockets after enabling chain " + chainName + ": " + e);
2019 }
2020 }
2021
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002022 @Override
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002023 public void setFirewallChainEnabled(int chain, boolean enable) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07002024 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002025 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002026 synchronized (mRulesLock) {
2027 if (getFirewallChainState(chain) == enable) {
2028 // All is the same, nothing to do. This relies on the fact that netd has child
2029 // chains default detached.
2030 return;
2031 }
2032 setFirewallChainState(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002033 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002034
Luke Huang615e1022018-10-25 11:54:05 +09002035 final String chainName = getFirewallChainName(chain);
Luke Huanga241db92018-07-31 20:15:24 +08002036 if (chain == FIREWALL_CHAIN_NONE) {
Luke Huang615e1022018-10-25 11:54:05 +09002037 throw new IllegalArgumentException("Bad child chain: " + chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002038 }
2039
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002040 try {
Luke Huanga241db92018-07-31 20:15:24 +08002041 mNetdService.firewallEnableChildChain(chain, enable);
2042 } catch (RemoteException | ServiceSpecificException e) {
2043 throw new IllegalStateException(e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002044 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002045
2046 // Close any sockets that were opened by the affected UIDs. This has to be done after
2047 // disabling network connectivity, in case they react to the socket close by reopening
2048 // the connection and race with the iptables commands that enable the firewall. All
2049 // whitelist and blacklist chains allow RSTs through.
2050 if (enable) {
Luke Huang615e1022018-10-25 11:54:05 +09002051 closeSocketsForFirewallChainLocked(chain, chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002052 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002053 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002054 }
2055
Luke Huanga241db92018-07-31 20:15:24 +08002056 private String getFirewallChainName(int chain) {
2057 switch (chain) {
2058 case FIREWALL_CHAIN_STANDBY:
2059 return FIREWALL_CHAIN_NAME_STANDBY;
2060 case FIREWALL_CHAIN_DOZABLE:
2061 return FIREWALL_CHAIN_NAME_DOZABLE;
2062 case FIREWALL_CHAIN_POWERSAVE:
2063 return FIREWALL_CHAIN_NAME_POWERSAVE;
2064 default:
2065 throw new IllegalArgumentException("Bad child chain: " + chain);
2066 }
2067 }
2068
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002069 private int getFirewallType(int chain) {
2070 switch (chain) {
2071 case FIREWALL_CHAIN_STANDBY:
2072 return FIREWALL_TYPE_BLACKLIST;
2073 case FIREWALL_CHAIN_DOZABLE:
2074 return FIREWALL_TYPE_WHITELIST;
Felipe Leme011b98f2016-02-10 17:28:31 -08002075 case FIREWALL_CHAIN_POWERSAVE:
2076 return FIREWALL_TYPE_WHITELIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002077 default:
2078 return isFirewallEnabled() ? FIREWALL_TYPE_WHITELIST : FIREWALL_TYPE_BLACKLIST;
2079 }
2080 }
2081
2082 @Override
2083 public void setFirewallUidRules(int chain, int[] uids, int[] rules) {
2084 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002085 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002086 synchronized (mRulesLock) {
2087 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
2088 SparseIntArray newRules = new SparseIntArray();
2089 // apply new set of rules
2090 for (int index = uids.length - 1; index >= 0; --index) {
2091 int uid = uids[index];
2092 int rule = rules[index];
2093 updateFirewallUidRuleLocked(chain, uid, rule);
2094 newRules.put(uid, rule);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002095 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002096 // collect the rules to remove.
2097 SparseIntArray rulesToRemove = new SparseIntArray();
2098 for (int index = uidFirewallRules.size() - 1; index >= 0; --index) {
2099 int uid = uidFirewallRules.keyAt(index);
2100 if (newRules.indexOfKey(uid) < 0) {
2101 rulesToRemove.put(uid, FIREWALL_RULE_DEFAULT);
2102 }
2103 }
2104 // remove dead rules
2105 for (int index = rulesToRemove.size() - 1; index >= 0; --index) {
2106 int uid = rulesToRemove.keyAt(index);
2107 updateFirewallUidRuleLocked(chain, uid, FIREWALL_RULE_DEFAULT);
2108 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002109 }
2110 try {
2111 switch (chain) {
2112 case FIREWALL_CHAIN_DOZABLE:
2113 mNetdService.firewallReplaceUidChain("fw_dozable", true, uids);
2114 break;
2115 case FIREWALL_CHAIN_STANDBY:
2116 mNetdService.firewallReplaceUidChain("fw_standby", false, uids);
2117 break;
2118 case FIREWALL_CHAIN_POWERSAVE:
2119 mNetdService.firewallReplaceUidChain("fw_powersave", true, uids);
2120 break;
2121 case FIREWALL_CHAIN_NONE:
2122 default:
2123 Slog.d(TAG, "setFirewallUidRules() called on invalid chain: " + chain);
2124 }
2125 } catch (RemoteException e) {
2126 Slog.w(TAG, "Error flushing firewall chain " + chain, e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002127 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002128 }
2129 }
2130
2131 @Override
2132 public void setFirewallUidRule(int chain, int uid, int rule) {
2133 enforceSystemUid();
Felipe Lemea701cad2016-05-12 09:58:14 -07002134 synchronized (mQuotaLock) {
2135 setFirewallUidRuleLocked(chain, uid, rule);
2136 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002137 }
2138
Felipe Lemea701cad2016-05-12 09:58:14 -07002139 private void setFirewallUidRuleLocked(int chain, int uid, int rule) {
2140 if (updateFirewallUidRuleLocked(chain, uid, rule)) {
Luke Huanga241db92018-07-31 20:15:24 +08002141 final int ruleType = getFirewallRuleType(chain, rule);
Amith Yamasani15e472352015-04-24 19:06:07 -07002142 try {
Luke Huanga241db92018-07-31 20:15:24 +08002143 mNetdService.firewallSetUidRule(chain, uid, ruleType);
2144 } catch (RemoteException | ServiceSpecificException e) {
2145 throw new IllegalStateException(e);
Amith Yamasani15e472352015-04-24 19:06:07 -07002146 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002147 }
2148 }
2149
Felipe Lemea701cad2016-05-12 09:58:14 -07002150 // TODO: now that netd supports batching, NMS should not keep these data structures anymore...
2151 private boolean updateFirewallUidRuleLocked(int chain, int uid, int rule) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002152 synchronized (mRulesLock) {
2153 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Felipe Lemea701cad2016-05-12 09:58:14 -07002154
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002155 final int oldUidFirewallRule = uidFirewallRules.get(uid, FIREWALL_RULE_DEFAULT);
2156 if (DBG) {
2157 Slog.d(TAG, "oldRule = " + oldUidFirewallRule
2158 + ", newRule=" + rule + " for uid=" + uid + " on chain " + chain);
2159 }
2160 if (oldUidFirewallRule == rule) {
2161 if (DBG) Slog.d(TAG, "!!!!! Skipping change");
2162 // TODO: eventually consider throwing
2163 return false;
2164 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002165
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002166 String ruleName = getFirewallRuleName(chain, rule);
2167 String oldRuleName = getFirewallRuleName(chain, oldUidFirewallRule);
Felipe Lemea701cad2016-05-12 09:58:14 -07002168
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002169 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
2170 uidFirewallRules.delete(uid);
2171 } else {
2172 uidFirewallRules.put(uid, rule);
2173 }
2174 return !ruleName.equals(oldRuleName);
Felipe Lemea701cad2016-05-12 09:58:14 -07002175 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002176 }
2177
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002178 private @NonNull String getFirewallRuleName(int chain, int rule) {
2179 String ruleName;
2180 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
2181 if (rule == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
2182 ruleName = "allow";
2183 } else {
2184 ruleName = "deny";
2185 }
2186 } else { // Blacklist mode
2187 if (rule == NetworkPolicyManager.FIREWALL_RULE_DENY) {
2188 ruleName = "deny";
2189 } else {
2190 ruleName = "allow";
2191 }
2192 }
2193 return ruleName;
2194 }
2195
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002196 private @NonNull SparseIntArray getUidFirewallRulesLR(int chain) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002197 switch (chain) {
2198 case FIREWALL_CHAIN_STANDBY:
2199 return mUidFirewallStandbyRules;
2200 case FIREWALL_CHAIN_DOZABLE:
2201 return mUidFirewallDozableRules;
Felipe Leme011b98f2016-02-10 17:28:31 -08002202 case FIREWALL_CHAIN_POWERSAVE:
2203 return mUidFirewallPowerSaveRules;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002204 case FIREWALL_CHAIN_NONE:
2205 return mUidFirewallRules;
2206 default:
2207 throw new IllegalArgumentException("Unknown chain:" + chain);
2208 }
2209 }
2210
Luke Huanga241db92018-07-31 20:15:24 +08002211 private int getFirewallRuleType(int chain, int rule) {
Luke Huang615e1022018-10-25 11:54:05 +09002212 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
2213 return getFirewallType(chain) == FIREWALL_TYPE_WHITELIST
2214 ? INetd.FIREWALL_RULE_DENY : INetd.FIREWALL_RULE_ALLOW;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002215 }
Luke Huang615e1022018-10-25 11:54:05 +09002216 return rule;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002217 }
2218
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07002219 private static void enforceSystemUid() {
2220 final int uid = Binder.getCallingUid();
2221 if (uid != Process.SYSTEM_UID) {
2222 throw new SecurityException("Only available to AID_SYSTEM");
2223 }
2224 }
2225
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002226 @Override
Lorenzo Colitti79751842013-02-28 16:16:03 +09002227 public void startClatd(String interfaceName) throws IllegalStateException {
2228 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2229
2230 try {
Luke Huang69369f32018-08-02 15:51:41 +08002231 mNetdService.clatdStart(interfaceName);
2232 } catch (RemoteException | ServiceSpecificException e) {
2233 throw new IllegalStateException(e);
Lorenzo Colitti79751842013-02-28 16:16:03 +09002234 }
2235 }
2236
2237 @Override
Lorenzo Colitti95439462014-10-09 13:44:48 +09002238 public void stopClatd(String interfaceName) throws IllegalStateException {
Lorenzo Colitti79751842013-02-28 16:16:03 +09002239 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2240
2241 try {
Luke Huang69369f32018-08-02 15:51:41 +08002242 mNetdService.clatdStop(interfaceName);
2243 } catch (RemoteException | ServiceSpecificException e) {
2244 throw new IllegalStateException(e);
Lorenzo Colitti79751842013-02-28 16:16:03 +09002245 }
2246 }
2247
2248 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002249 public void registerNetworkActivityListener(INetworkActivityListener listener) {
2250 mNetworkActivityListeners.register(listener);
2251 }
2252
2253 @Override
2254 public void unregisterNetworkActivityListener(INetworkActivityListener listener) {
2255 mNetworkActivityListeners.unregister(listener);
2256 }
2257
2258 @Override
2259 public boolean isNetworkActive() {
2260 synchronized (mNetworkActivityListeners) {
2261 return mNetworkActive || mActiveIdleTimers.isEmpty();
2262 }
2263 }
2264
2265 private void reportNetworkActive() {
2266 final int length = mNetworkActivityListeners.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002267 try {
2268 for (int i = 0; i < length; i++) {
2269 try {
2270 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
Felipe Leme03e689d2016-03-02 16:17:38 -08002271 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002272 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002273 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002274 } finally {
2275 mNetworkActivityListeners.finishBroadcast();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002276 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002277 }
2278
Mattias Falk8b47b362011-08-23 14:15:13 +02002279 /** {@inheritDoc} */
Jeff Sharkey7b4596f2013-02-25 10:55:29 -08002280 @Override
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002281 public void monitor() {
2282 if (mConnector != null) {
2283 mConnector.monitor();
2284 }
2285 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002286
2287 @Override
2288 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002289 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002290
Robert Greenwalt470fd722012-01-18 12:51:15 -08002291 pw.println("NetworkManagementService NativeDaemonConnector Log:");
2292 mConnector.dump(fd, pw, args);
2293 pw.println();
2294
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07002295 pw.print("mMobileActivityFromRadio="); pw.print(mMobileActivityFromRadio);
2296 pw.print(" mLastPowerStateFromRadio="); pw.println(mLastPowerStateFromRadio);
2297 pw.print("mNetworkActive="); pw.println(mNetworkActive);
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002298
2299 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07002300 pw.print("Active quota ifaces: "); pw.println(mActiveQuotas.toString());
2301 pw.print("Active alert ifaces: "); pw.println(mActiveAlerts.toString());
Felipe Leme65be3022016-03-22 14:53:13 -07002302 pw.print("Data saver mode: "); pw.println(mDataSaverMode);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002303 synchronized (mRulesLock) {
2304 dumpUidRuleOnQuotaLocked(pw, "blacklist", mUidRejectOnMetered);
2305 dumpUidRuleOnQuotaLocked(pw, "whitelist", mUidAllowOnMetered);
2306 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002307 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002308
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002309 synchronized (mRulesLock) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002310 dumpUidFirewallRule(pw, "", mUidFirewallRules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002311
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002312 pw.print("UID firewall standby chain enabled: "); pw.println(
2313 getFirewallChainState(FIREWALL_CHAIN_STANDBY));
Felipe Leme011b98f2016-02-10 17:28:31 -08002314 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_STANDBY, mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002315
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002316 pw.print("UID firewall dozable chain enabled: "); pw.println(
2317 getFirewallChainState(FIREWALL_CHAIN_DOZABLE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002318 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_DOZABLE, mUidFirewallDozableRules);
Felipe Leme011b98f2016-02-10 17:28:31 -08002319
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002320 pw.println("UID firewall powersave chain enabled: " +
2321 getFirewallChainState(FIREWALL_CHAIN_POWERSAVE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002322 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_POWERSAVE, mUidFirewallPowerSaveRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002323 }
2324
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002325 synchronized (mIdleTimerLock) {
2326 pw.println("Idle timers:");
2327 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
2328 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
2329 IdleTimerParams params = ent.getValue();
2330 pw.print(" timeout="); pw.print(params.timeout);
2331 pw.print(" type="); pw.print(params.type);
2332 pw.print(" networkCount="); pw.println(params.networkCount);
2333 }
2334 }
2335
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002336 pw.print("Firewall enabled: "); pw.println(mFirewallEnabled);
Felipe Leme65be3022016-03-22 14:53:13 -07002337 pw.print("Netd service status: " );
2338 if (mNetdService == null) {
2339 pw.println("disconnected");
2340 } else {
2341 try {
2342 final boolean alive = mNetdService.isAlive();
2343 pw.println(alive ? "alive": "dead");
2344 } catch (RemoteException e) {
2345 pw.println("unreachable");
2346 }
2347 }
2348 }
2349
2350 private void dumpUidRuleOnQuotaLocked(PrintWriter pw, String name, SparseBooleanArray list) {
2351 pw.print("UID bandwith control ");
2352 pw.print(name);
2353 pw.print(" rule: [");
2354 final int size = list.size();
2355 for (int i = 0; i < size; i++) {
2356 pw.print(list.keyAt(i));
2357 if (i < size - 1) pw.print(",");
2358 }
2359 pw.println("]");
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002360 }
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002361
Felipe Leme011b98f2016-02-10 17:28:31 -08002362 private void dumpUidFirewallRule(PrintWriter pw, String name, SparseIntArray rules) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002363 pw.print("UID firewall ");
Felipe Leme011b98f2016-02-10 17:28:31 -08002364 pw.print(name);
2365 pw.print(" rule: [");
2366 final int size = rules.size();
2367 for (int i = 0; i < size; i++) {
2368 pw.print(rules.keyAt(i));
2369 pw.print(":");
2370 pw.print(rules.valueAt(i));
2371 if (i < size - 1) pw.print(",");
2372 }
2373 pw.println("]");
2374 }
2375
Robert Greenwalt568891d2014-04-04 13:38:00 -07002376 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002377 public void createPhysicalNetwork(int netId, int permission) {
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002378 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2379
2380 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002381 mNetdService.networkCreatePhysical(netId, permission);
2382 } catch (RemoteException | ServiceSpecificException e) {
2383 throw new IllegalStateException(e);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002384 }
2385 }
2386
Robert Greenwalt568891d2014-04-04 13:38:00 -07002387 @Override
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07002388 public void createVirtualNetwork(int netId, boolean hasDNS, boolean secure) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002389 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2390
2391 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002392 mNetdService.networkCreateVpn(netId, hasDNS, secure);
2393 } catch (RemoteException | ServiceSpecificException e) {
2394 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002395 }
2396 }
2397
2398 @Override
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002399 public void removeNetwork(int netId) {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002400 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002401
2402 try {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002403 mNetdService.networkDestroy(netId);
2404 } catch (ServiceSpecificException e) {
2405 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2406 throw e;
2407 } catch (RemoteException e) {
2408 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2409 throw e.rethrowAsRuntimeException();
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002410 }
2411 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002412
2413 @Override
Paul Jensen992f2522014-04-28 10:33:11 -04002414 public void addInterfaceToNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002415 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, netId, iface);
Paul Jensen992f2522014-04-28 10:33:11 -04002416 }
2417
2418 @Override
2419 public void removeInterfaceFromNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002420 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, netId, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002421 }
Paul Jensen992f2522014-04-28 10:33:11 -04002422
Luke Huang8a462ec2018-08-24 20:33:16 +08002423 private void modifyInterfaceInNetwork(boolean add, int netId, String iface) {
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002424 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Paul Jensen992f2522014-04-28 10:33:11 -04002425 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002426 if (add) {
2427 mNetdService.networkAddInterface(netId, iface);
2428 } else {
2429 mNetdService.networkRemoveInterface(netId, iface);
2430 }
2431 } catch (RemoteException | ServiceSpecificException e) {
2432 throw new IllegalStateException(e);
Paul Jensen992f2522014-04-28 10:33:11 -04002433 }
2434 }
2435
2436 @Override
Robert Greenwalt913c8952014-04-07 17:36:35 -07002437 public void addLegacyRouteForNetId(int netId, RouteInfo routeInfo, int uid) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002438 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2439
Sreeram Ramachandrancc91c7b2014-06-03 18:41:43 -07002440 final LinkAddress la = routeInfo.getDestinationLinkAddress();
Luke Huang8a462ec2018-08-24 20:33:16 +08002441 final String ifName = routeInfo.getInterface();
2442 final String dst = la.toString();
2443 final String nextHop;
Robert Greenwalt568891d2014-04-04 13:38:00 -07002444
Luke Huang8a462ec2018-08-24 20:33:16 +08002445 if (routeInfo.hasGateway()) {
2446 nextHop = routeInfo.getGateway().getHostAddress();
2447 } else {
2448 nextHop = "";
2449 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002450 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002451 mNetdService.networkAddLegacyRoute(netId, ifName, dst, nextHop, uid);
2452 } catch (RemoteException | ServiceSpecificException e) {
2453 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002454 }
2455 }
2456
2457 @Override
Sreeram Ramachandranf047f2a2014-04-15 16:04:26 -07002458 public void setDefaultNetId(int netId) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002459 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2460
2461 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002462 mNetdService.networkSetDefault(netId);
2463 } catch (RemoteException | ServiceSpecificException e) {
2464 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002465 }
2466 }
2467
2468 @Override
2469 public void clearDefaultNetId() {
2470 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2471
2472 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002473 mNetdService.networkClearDefault();
2474 } catch (RemoteException | ServiceSpecificException e) {
2475 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002476 }
2477 }
2478
2479 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002480 public void setNetworkPermission(int netId, int permission) {
Paul Jensen487ffe72015-07-24 15:57:11 -04002481 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2482
2483 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002484 mNetdService.networkSetPermissionForNetwork(netId, permission);
2485 } catch (RemoteException | ServiceSpecificException e) {
2486 throw new IllegalStateException(e);
Paul Jensen487ffe72015-07-24 15:57:11 -04002487 }
2488 }
2489
Luke Huang8a462ec2018-08-24 20:33:16 +08002490 private int parsePermission(String permission) {
2491 if (permission.equals("NETWORK")) {
2492 return INetd.PERMISSION_NETWORK;
2493 }
2494 if (permission.equals("SYSTEM")) {
2495 return INetd.PERMISSION_SYSTEM;
2496 }
2497 return INetd.PERMISSION_NONE;
2498 }
Paul Jensen487ffe72015-07-24 15:57:11 -04002499
2500 @Override
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002501 public void setPermission(String permission, int[] uids) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002502 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2503
Luke Huang8a462ec2018-08-24 20:33:16 +08002504 try {
2505 mNetdService.networkSetPermissionForUser(parsePermission(permission), uids);
2506 } catch (RemoteException | ServiceSpecificException e) {
2507 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002508 }
2509 }
2510
2511 @Override
2512 public void clearPermission(int[] uids) {
2513 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2514
Luke Huang8a462ec2018-08-24 20:33:16 +08002515 try {
2516 mNetdService.networkClearPermissionForUser(uids);
2517 } catch (RemoteException | ServiceSpecificException e) {
2518 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002519 }
2520 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002521
2522 @Override
2523 public void allowProtect(int uid) {
2524 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2525
2526 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002527 mNetdService.networkSetProtectAllow(uid);
2528 } catch (RemoteException | ServiceSpecificException e) {
2529 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002530 }
2531 }
2532
2533 @Override
2534 public void denyProtect(int uid) {
2535 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2536
2537 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002538 mNetdService.networkSetProtectDeny(uid);
2539 } catch (RemoteException | ServiceSpecificException e) {
2540 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002541 }
2542 }
2543
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002544 @Override
2545 public void addInterfaceToLocalNetwork(String iface, List<RouteInfo> routes) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002546 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002547
2548 for (RouteInfo route : routes) {
2549 if (!route.isDefaultRoute()) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002550 modifyRoute(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID, route);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002551 }
2552 }
2553 }
2554
2555 @Override
2556 public void removeInterfaceFromLocalNetwork(String iface) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002557 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, INetd.LOCAL_NET_ID, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002558 }
Erik Kline6599ee82016-07-17 21:28:39 +09002559
2560 @Override
2561 public int removeRoutesFromLocalNetwork(List<RouteInfo> routes) {
2562 int failures = 0;
2563
2564 for (RouteInfo route : routes) {
2565 try {
Luke Huang706d7ab2018-10-16 15:42:15 +08002566 modifyRoute(MODIFY_OPERATION_REMOVE, INetd.LOCAL_NET_ID, route);
Erik Kline6599ee82016-07-17 21:28:39 +09002567 } catch (IllegalStateException e) {
2568 failures++;
2569 }
2570 }
2571
2572 return failures;
2573 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002574
Sudheer Shankab8f23162017-08-04 13:30:10 -07002575 @Override
2576 public boolean isNetworkRestricted(int uid) {
2577 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2578 return isNetworkRestrictedInternal(uid);
2579 }
2580
2581 private boolean isNetworkRestrictedInternal(int uid) {
2582 synchronized (mRulesLock) {
2583 if (getFirewallChainState(FIREWALL_CHAIN_STANDBY)
2584 && mUidFirewallStandbyRules.get(uid) == FIREWALL_RULE_DENY) {
2585 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of app standby mode");
2586 return true;
2587 }
2588 if (getFirewallChainState(FIREWALL_CHAIN_DOZABLE)
2589 && mUidFirewallDozableRules.get(uid) != FIREWALL_RULE_ALLOW) {
2590 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of device idle mode");
2591 return true;
2592 }
2593 if (getFirewallChainState(FIREWALL_CHAIN_POWERSAVE)
2594 && mUidFirewallPowerSaveRules.get(uid) != FIREWALL_RULE_ALLOW) {
2595 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of power saver mode");
2596 return true;
2597 }
2598 if (mUidRejectOnMetered.get(uid)) {
2599 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of no metered data"
2600 + " in the background");
2601 return true;
2602 }
2603 if (mDataSaverMode && !mUidAllowOnMetered.get(uid)) {
2604 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of data saver mode");
2605 return true;
2606 }
2607 return false;
2608 }
2609 }
2610
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002611 private void setFirewallChainState(int chain, boolean state) {
2612 synchronized (mRulesLock) {
2613 mFirewallChainStates.put(chain, state);
2614 }
2615 }
2616
2617 private boolean getFirewallChainState(int chain) {
2618 synchronized (mRulesLock) {
2619 return mFirewallChainStates.get(chain);
2620 }
2621 }
2622
2623 @VisibleForTesting
2624 class LocalService extends NetworkManagementInternal {
2625 @Override
2626 public boolean isNetworkRestrictedForUid(int uid) {
Sudheer Shankab8f23162017-08-04 13:30:10 -07002627 return isNetworkRestrictedInternal(uid);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002628 }
2629 }
2630
2631 @VisibleForTesting
2632 Injector getInjector() {
2633 return new Injector();
2634 }
2635
2636 @VisibleForTesting
2637 class Injector {
2638 void setDataSaverMode(boolean dataSaverMode) {
2639 mDataSaverMode = dataSaverMode;
2640 }
2641
2642 void setFirewallChainState(int chain, boolean state) {
2643 NetworkManagementService.this.setFirewallChainState(chain, state);
2644 }
2645
2646 void setFirewallRule(int chain, int uid, int rule) {
2647 synchronized (mRulesLock) {
2648 getUidFirewallRulesLR(chain).put(uid, rule);
2649 }
2650 }
2651
2652 void setUidOnMeteredNetworkList(boolean blacklist, int uid, boolean enable) {
2653 synchronized (mRulesLock) {
2654 if (blacklist) {
2655 mUidRejectOnMetered.put(uid, enable);
2656 } else {
2657 mUidAllowOnMetered.put(uid, enable);
2658 }
2659 }
2660 }
2661
2662 void reset() {
2663 synchronized (mRulesLock) {
2664 setDataSaverMode(false);
2665 final int[] chains = {
2666 FIREWALL_CHAIN_DOZABLE,
2667 FIREWALL_CHAIN_STANDBY,
2668 FIREWALL_CHAIN_POWERSAVE
2669 };
2670 for (int chain : chains) {
2671 setFirewallChainState(chain, false);
2672 getUidFirewallRulesLR(chain).clear();
2673 }
2674 mUidAllowOnMetered.clear();
2675 mUidRejectOnMetered.clear();
2676 }
2677 }
2678 }
San Mehat873f2142010-01-14 10:25:07 -08002679}