blob: b0ca2df20f1f4a2f5a503e6f8a385a47a39039a1 [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;
Luke Huang14f75442018-08-15 19:22:54 +080064import android.net.InterfaceConfigurationParcel;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +090065import android.net.IpPrefix;
Robert Greenwalted126402011-01-28 15:34:55 -080066import android.net.LinkAddress;
Lorenzo Colittib57edc52014-08-22 17:10:50 -070067import android.net.Network;
Amith Yamasani15e472352015-04-24 19:06:07 -070068import android.net.NetworkPolicyManager;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070069import android.net.NetworkStats;
Robert Greenwalted126402011-01-28 15:34:55 -080070import android.net.NetworkUtils;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070071import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040072import android.net.UidRange;
Luke Huang77017912018-10-19 15:57:05 +090073import android.net.UidRangeParcel;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +090074import android.net.util.NetdService;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080075import android.net.wifi.WifiConfiguration;
76import android.net.wifi.WifiConfiguration.KeyMgmt;
Dianne Hackborn91268cf2013-06-13 19:06:50 -070077import android.os.BatteryStats;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070078import android.os.Binder;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -070079import android.os.Handler;
Lorenzo Colittia0868002017-07-11 02:29:28 +090080import android.os.IBinder;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080081import android.os.INetworkActivityListener;
San Mehat873f2142010-01-14 10:25:07 -080082import android.os.INetworkManagementService;
Lorenzo Colitti563dc452017-09-01 17:12:34 +090083import android.os.PersistableBundle;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080084import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070085import android.os.Process;
Jeff Sharkey3df273e2011-12-15 15:47:12 -080086import android.os.RemoteCallbackList;
87import android.os.RemoteException;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070088import android.os.ServiceManager;
Lorenzo Colitti4cb42402016-04-24 12:52:00 +090089import android.os.ServiceSpecificException;
Jeff Sharkey605eb792014-11-04 13:34:06 -080090import android.os.StrictMode;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070091import android.os.SystemClock;
Marco Nelissen62dbb222010-02-18 10:56:30 -080092import android.os.SystemProperties;
Felipe Leme29e72ea2016-09-08 13:26:55 -070093import android.os.Trace;
Pierre Imai8e48e672016-04-21 13:30:43 +090094import android.provider.Settings;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070095import android.telephony.DataConnectionRealTimeInfo;
96import android.telephony.PhoneStateListener;
Wink Savillefb40dd42014-06-12 17:02:31 -070097import android.telephony.SubscriptionManager;
Wink Saville67e07892014-06-18 16:43:14 -070098import android.telephony.TelephonyManager;
Erik Kline4d092232017-10-30 15:29:44 +090099import android.text.TextUtils;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -0800100import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800101import android.util.Slog;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700102import android.util.SparseBooleanArray;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800103import android.util.SparseIntArray;
Bookatz0b028b12018-05-31 16:51:17 -0700104import android.util.StatsLog;
San Mehat873f2142010-01-14 10:25:07 -0800105
Jeff Sharkey605eb792014-11-04 13:34:06 -0800106import com.android.internal.annotations.GuardedBy;
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700107import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -0700108import com.android.internal.app.IBatteryStats;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700109import com.android.internal.net.NetworkStatsFactory;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600110import com.android.internal.util.DumpUtils;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800111import com.android.internal.util.HexDump;
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700112import com.android.internal.util.Preconditions;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800113import com.android.server.NativeDaemonConnector.Command;
Jeff Sharkey56cd6462013-06-07 15:09:15 -0700114import com.android.server.NativeDaemonConnector.SensitiveArg;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700115import com.google.android.collect.Maps;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700116
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700117import java.io.BufferedReader;
118import java.io.DataInputStream;
San Mehat873f2142010-01-14 10:25:07 -0800119import java.io.File;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700120import java.io.FileDescriptor;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700121import java.io.FileInputStream;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700122import java.io.IOException;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700123import java.io.InputStreamReader;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700124import java.io.PrintWriter;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700125import java.net.InetAddress;
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700126import java.net.InterfaceAddress;
127import java.net.NetworkInterface;
128import java.net.SocketException;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700129import java.util.ArrayList;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400130import java.util.Arrays;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700131import java.util.HashMap;
jiaguo1da35f72014-01-09 16:39:59 +0800132import java.util.List;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700133import java.util.Map;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700134import java.util.NoSuchElementException;
135import java.util.StringTokenizer;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700136import java.util.concurrent.CountDownLatch;
San Mehat873f2142010-01-14 10:25:07 -0800137
138/**
139 * @hide
140 */
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700141public class NetworkManagementService extends INetworkManagementService.Stub
142 implements Watchdog.Monitor {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900143
144 /**
145 * Helper class that encapsulates NetworkManagementService dependencies and makes them
146 * easier to mock in unit tests.
147 */
148 static class SystemServices {
149 public IBinder getService(String name) {
150 return ServiceManager.getService(name);
151 }
152 public void registerLocalService(NetworkManagementInternal nmi) {
153 LocalServices.addService(NetworkManagementInternal.class, nmi);
154 }
155 public INetd getNetd() {
156 return NetdService.get();
157 }
158 }
159
Amith Yamasani15e472352015-04-24 19:06:07 -0700160 private static final String TAG = "NetworkManagement";
161 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Kenny Root305bcbf2010-09-03 07:56:38 -0700162 private static final String NETD_TAG = "NetdConnector";
Lorenzo Colittia0868002017-07-11 02:29:28 +0900163 static final String NETD_SERVICE_NAME = "netd";
Kenny Root305bcbf2010-09-03 07:56:38 -0700164
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400165 private static final int MAX_UID_RANGES_PER_COMMAND = 10;
166
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700167 /**
168 * Name representing {@link #setGlobalAlert(long)} limit when delivered to
169 * {@link INetworkManagementEventObserver#limitReached(String, String)}.
170 */
171 public static final String LIMIT_GLOBAL_ALERT = "globalAlert";
172
Andrew Scull45f533c2017-05-19 15:37:20 +0100173 static class NetdResponseCode {
Sreeram Ramachandran03666c72014-07-19 23:21:46 -0700174 /* Keep in sync with system/netd/server/ResponseCode.h */
San Mehat873f2142010-01-14 10:25:07 -0800175 public static final int InterfaceListResult = 110;
176 public static final int TetherInterfaceListResult = 111;
177 public static final int TetherDnsFwdTgtListResult = 112;
San Mehat72759df2010-01-19 13:50:37 -0800178 public static final int TtyListResult = 113;
Jeff Sharkeye4984be2013-09-10 21:03:27 -0700179 public static final int TetheringStatsListResult = 114;
San Mehat873f2142010-01-14 10:25:07 -0800180
181 public static final int TetherStatusResult = 210;
182 public static final int IpFwdStatusResult = 211;
San Mehated4fc8a2010-01-22 12:28:36 -0800183 public static final int InterfaceGetCfgResult = 213;
Robert Greenwalte3253922010-02-18 09:23:25 -0800184 public static final int SoftapStatusResult = 214;
San Mehat91cac642010-03-31 14:31:36 -0700185 public static final int InterfaceRxCounterResult = 216;
186 public static final int InterfaceTxCounterResult = 217;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -0700187 public static final int QuotaCounterResult = 220;
188 public static final int TetheringStatsResult = 221;
Selim Gurun84c00c62012-02-27 15:42:38 -0800189 public static final int DnsProxyQueryResult = 222;
Lorenzo Colitti79751842013-02-28 16:16:03 +0900190 public static final int ClatdStatusResult = 223;
Robert Greenwalte3253922010-02-18 09:23:25 -0800191
192 public static final int InterfaceChange = 600;
JP Abgrall12b933d2011-07-14 18:09:22 -0700193 public static final int BandwidthControl = 601;
Haoyu Bai6b7358d2012-07-17 16:36:50 -0700194 public static final int InterfaceClassActivity = 613;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900195 public static final int InterfaceAddressChange = 614;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900196 public static final int InterfaceDnsServerInfo = 615;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900197 public static final int RouteChange = 616;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800198 public static final int StrictCleartext = 617;
San Mehat873f2142010-01-14 10:25:07 -0800199 }
200
Rebecca Silbersteine2ec94f2016-03-24 13:29:00 -0700201 /**
202 * String indicating a softap command.
203 */
204 static final String SOFT_AP_COMMAND = "softap";
205
206 /**
207 * String passed back to netd connector indicating softap command success.
208 */
209 static final String SOFT_AP_COMMAND_SUCCESS = "Ok";
210
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700211 static final int DAEMON_MSG_MOBILE_CONN_REAL_TIME_INFO = 1;
212
Luke Huang8a462ec2018-08-24 20:33:16 +0800213 static final boolean MODIFY_OPERATION_ADD = true;
214 static final boolean MODIFY_OPERATION_REMOVE = false;
215
San Mehat873f2142010-01-14 10:25:07 -0800216 /**
217 * Binder context for this service
218 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700219 private final Context mContext;
San Mehat873f2142010-01-14 10:25:07 -0800220
221 /**
222 * connector object for communicating with netd
223 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700224 private final NativeDaemonConnector mConnector;
San Mehat873f2142010-01-14 10:25:07 -0800225
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700226 private final Handler mFgHandler;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700227 private final Handler mDaemonHandler;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700228
Lorenzo Colittia0868002017-07-11 02:29:28 +0900229 private final SystemServices mServices;
230
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900231 private INetd mNetdService;
232
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800233 private IBatteryStats mBatteryStats;
234
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700235 private final Thread mThread;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700236 private CountDownLatch mConnectedSignal = new CountDownLatch(1);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700237
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800238 private final RemoteCallbackList<INetworkManagementEventObserver> mObservers =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700239 new RemoteCallbackList<>();
San Mehat4d02d002010-01-22 16:07:46 -0800240
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700241 private final NetworkStatsFactory mStatsFactory = new NetworkStatsFactory();
242
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900243 @GuardedBy("mTetheringStatsProviders")
244 private final HashMap<ITetheringStatsProvider, String>
245 mTetheringStatsProviders = Maps.newHashMap();
246
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700247 /**
248 * If both locks need to be held, then they should be obtained in the order:
249 * first {@link #mQuotaLock} and then {@link #mRulesLock}.
250 */
Andrew Scull45f533c2017-05-19 15:37:20 +0100251 private final Object mQuotaLock = new Object();
Andrew Scull519291f2017-05-23 13:11:03 +0100252 private final Object mRulesLock = new Object();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800253
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700254 /** Set of interfaces with active quotas. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800255 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700256 private HashMap<String, Long> mActiveQuotas = Maps.newHashMap();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700257 /** Set of interfaces with active alerts. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800258 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700259 private HashMap<String, Long> mActiveAlerts = Maps.newHashMap();
Felipe Leme65be3022016-03-22 14:53:13 -0700260 /** Set of UIDs blacklisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700261 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700262 private SparseBooleanArray mUidRejectOnMetered = new SparseBooleanArray();
263 /** Set of UIDs whitelisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700264 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700265 private SparseBooleanArray mUidAllowOnMetered = new SparseBooleanArray();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800266 /** Set of UIDs with cleartext penalties. */
267 @GuardedBy("mQuotaLock")
268 private SparseIntArray mUidCleartextPolicy = new SparseIntArray();
Amith Yamasani15e472352015-04-24 19:06:07 -0700269 /** Set of UIDs that are to be blocked/allowed by firewall controller. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700270 @GuardedBy("mRulesLock")
Amith Yamasani15e472352015-04-24 19:06:07 -0700271 private SparseIntArray mUidFirewallRules = new SparseIntArray();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700272 /**
273 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
274 * to application idles.
275 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700276 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700277 private SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
278 /**
279 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
280 * to device idles.
281 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700282 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700283 private SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800284 /**
285 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
286 * to device on power-save mode.
287 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700288 @GuardedBy("mRulesLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800289 private SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700290 /** Set of states for the child firewall chains. True if the chain is active. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700291 @GuardedBy("mRulesLock")
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700292 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700293
Felipe Leme65be3022016-03-22 14:53:13 -0700294 @GuardedBy("mQuotaLock")
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700295 private volatile boolean mDataSaverMode;
Felipe Leme65be3022016-03-22 14:53:13 -0700296
Andrew Scull45f533c2017-05-19 15:37:20 +0100297 private final Object mIdleTimerLock = new Object();
Haoyu Bai04124232012-06-28 15:26:19 -0700298 /** Set of interfaces with active idle timers. */
299 private static class IdleTimerParams {
300 public final int timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800301 public final int type;
Haoyu Bai04124232012-06-28 15:26:19 -0700302 public int networkCount;
303
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800304 IdleTimerParams(int timeout, int type) {
Haoyu Bai04124232012-06-28 15:26:19 -0700305 this.timeout = timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800306 this.type = type;
Haoyu Bai04124232012-06-28 15:26:19 -0700307 this.networkCount = 1;
308 }
309 }
310 private HashMap<String, IdleTimerParams> mActiveIdleTimers = Maps.newHashMap();
311
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700312 private volatile boolean mFirewallEnabled;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800313 private volatile boolean mStrictEnabled;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700314
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700315 private boolean mMobileActivityFromRadio = false;
316 private int mLastPowerStateFromRadio = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Adam Lesinskie08af192015-03-25 16:42:59 -0700317 private int mLastPowerStateFromWifi = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700318
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800319 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700320 new RemoteCallbackList<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800321 private boolean mNetworkActive;
322
San Mehat873f2142010-01-14 10:25:07 -0800323 /**
324 * Constructs a new NetworkManagementService instance
325 *
326 * @param context Binder context for this service
327 */
Lorenzo Colittia0868002017-07-11 02:29:28 +0900328 private NetworkManagementService(
329 Context context, String socket, SystemServices services) {
San Mehat873f2142010-01-14 10:25:07 -0800330 mContext = context;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900331 mServices = services;
San Mehat4d02d002010-01-22 16:07:46 -0800332
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700333 // make sure this is on the same looper as our NativeDaemonConnector for sync purposes
334 mFgHandler = new Handler(FgThread.get().getLooper());
335
Dianne Hackborn4590e522014-03-24 13:36:46 -0700336 // Don't need this wake lock, since we now have a time stamp for when
337 // the network actually went inactive. (It might be nice to still do this,
338 // but I don't want to do it through the power manager because that pollutes the
339 // battery stats history with pointless noise.)
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700340 //PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
Dianne Hackborn4590e522014-03-24 13:36:46 -0700341 PowerManager.WakeLock wl = null; //pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, NETD_TAG);
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800342
San Mehat873f2142010-01-14 10:25:07 -0800343 mConnector = new NativeDaemonConnector(
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700344 new NetdCallbackReceiver(), socket, 10, NETD_TAG, 160, wl,
345 FgThread.get().getLooper());
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700346 mThread = new Thread(mConnector, NETD_TAG);
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700347
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700348 mDaemonHandler = new Handler(FgThread.get().getLooper());
Wink Saville67e07892014-06-18 16:43:14 -0700349
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700350 // Add ourself to the Watchdog monitors.
351 Watchdog.getInstance().addMonitor(this);
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700352
Lorenzo Colittia0868002017-07-11 02:29:28 +0900353 mServices.registerLocalService(new LocalService());
Lorenzo Colitti8228eb32017-07-19 06:17:33 +0900354
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900355 synchronized (mTetheringStatsProviders) {
356 mTetheringStatsProviders.put(new NetdTetheringStatsProvider(), "netd");
357 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700358 }
359
360 @VisibleForTesting
361 NetworkManagementService() {
362 mConnector = null;
363 mContext = null;
364 mDaemonHandler = null;
365 mFgHandler = null;
366 mThread = null;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900367 mServices = null;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700368 }
369
Lorenzo Colittia0868002017-07-11 02:29:28 +0900370 static NetworkManagementService create(Context context, String socket, SystemServices services)
Felipe Leme03e689d2016-03-02 16:17:38 -0800371 throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900372 final NetworkManagementService service =
373 new NetworkManagementService(context, socket, services);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700374 final CountDownLatch connectedSignal = service.mConnectedSignal;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700375 if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
376 service.mThread.start();
377 if (DBG) Slog.d(TAG, "Awaiting socket connection");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700378 connectedSignal.await();
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700379 if (DBG) Slog.d(TAG, "Connected");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900380 if (DBG) Slog.d(TAG, "Connecting native netd service");
bohu07cc3bb2016-05-03 15:58:01 -0700381 service.connectNativeNetdService();
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900382 if (DBG) Slog.d(TAG, "Connected");
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700383 return service;
San Mehat873f2142010-01-14 10:25:07 -0800384 }
385
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900386 public static NetworkManagementService create(Context context) throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900387 return create(context, NETD_SERVICE_NAME, new SystemServices());
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900388 }
389
Jeff Sharkey350083e2011-06-29 10:45:16 -0700390 public void systemReady() {
Felipe Leme03e689d2016-03-02 16:17:38 -0800391 if (DBG) {
392 final long start = System.currentTimeMillis();
393 prepareNativeDaemon();
394 final long delta = System.currentTimeMillis() - start;
395 Slog.d(TAG, "Prepared in " + delta + "ms");
396 return;
397 } else {
398 prepareNativeDaemon();
399 }
Jeff Sharkey350083e2011-06-29 10:45:16 -0700400 }
401
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800402 private IBatteryStats getBatteryStats() {
403 synchronized (this) {
404 if (mBatteryStats != null) {
405 return mBatteryStats;
406 }
Lorenzo Colittia0868002017-07-11 02:29:28 +0900407 mBatteryStats =
408 IBatteryStats.Stub.asInterface(mServices.getService(BatteryStats.SERVICE_NAME));
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800409 return mBatteryStats;
410 }
411 }
412
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800413 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800414 public void registerObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800415 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800416 mObservers.register(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800417 }
418
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800419 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800420 public void unregisterObserver(INetworkManagementEventObserver observer) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800421 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800422 mObservers.unregister(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800423 }
424
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900425 @FunctionalInterface
426 private interface NetworkManagementEventCallback {
427 public void sendCallback(INetworkManagementEventObserver o) throws RemoteException;
428 }
429
430 private void invokeForAllObservers(NetworkManagementEventCallback eventCallback) {
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800431 final int length = mObservers.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700432 try {
433 for (int i = 0; i < length; i++) {
434 try {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900435 eventCallback.sendCallback(mObservers.getBroadcastItem(i));
Felipe Leme03e689d2016-03-02 16:17:38 -0800436 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700437 }
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700438 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700439 } finally {
440 mObservers.finishBroadcast();
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700441 }
442 }
443
444 /**
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900445 * Notify our observers of an interface status change
446 */
447 private void notifyInterfaceStatusChanged(String iface, boolean up) {
448 invokeForAllObservers(o -> o.interfaceStatusChanged(iface, up));
449 }
450
451 /**
Mike J. Chenf59c7d02011-06-23 15:33:15 -0700452 * Notify our observers of an interface link state change
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700453 * (typically, an Ethernet cable has been plugged-in or unplugged).
454 */
455 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900456 invokeForAllObservers(o -> o.interfaceLinkStateChanged(iface, up));
San Mehat4d02d002010-01-22 16:07:46 -0800457 }
458
459 /**
460 * Notify our observers of an interface addition.
461 */
462 private void notifyInterfaceAdded(String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900463 invokeForAllObservers(o -> o.interfaceAdded(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800464 }
465
466 /**
467 * Notify our observers of an interface removal.
468 */
469 private void notifyInterfaceRemoved(String iface) {
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700470 // netd already clears out quota and alerts for removed ifaces; update
471 // our sanity-checking state.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700472 mActiveAlerts.remove(iface);
473 mActiveQuotas.remove(iface);
Jeff Sharkey89b8a212011-10-11 11:58:11 -0700474
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900475 invokeForAllObservers(o -> o.interfaceRemoved(iface));
San Mehat4d02d002010-01-22 16:07:46 -0800476 }
477
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700478 /**
JP Abgrall12b933d2011-07-14 18:09:22 -0700479 * Notify our observers of a limit reached.
480 */
481 private void notifyLimitReached(String limitName, String iface) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900482 invokeForAllObservers(o -> o.limitReached(limitName, iface));
JP Abgrall12b933d2011-07-14 18:09:22 -0700483 }
484
485 /**
Haoyu Baidb3c8672012-06-20 14:29:57 -0700486 * Notify our observers of a change in the data activity state of the interface
487 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700488 private void notifyInterfaceClassActivity(int type, int powerState, long tsNanos,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700489 int uid, boolean fromRadio) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700490 final boolean isMobile = ConnectivityManager.isNetworkTypeMobile(type);
491 if (isMobile) {
492 if (!fromRadio) {
493 if (mMobileActivityFromRadio) {
494 // If this call is not coming from a report from the radio itself, but we
495 // have previously received reports from the radio, then we will take the
496 // power state to just be whatever the radio last reported.
497 powerState = mLastPowerStateFromRadio;
498 }
499 } else {
500 mMobileActivityFromRadio = true;
501 }
502 if (mLastPowerStateFromRadio != powerState) {
503 mLastPowerStateFromRadio = powerState;
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700504 try {
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700505 getBatteryStats().noteMobileRadioPowerState(powerState, tsNanos, uid);
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700506 } catch (RemoteException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700507 }
Bookatz0b028b12018-05-31 16:51:17 -0700508 StatsLog.write_non_chained(StatsLog.MOBILE_RADIO_POWER_STATE_CHANGED, uid, null,
509 powerState);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700510 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700511 }
512
Adam Lesinskie08af192015-03-25 16:42:59 -0700513 if (ConnectivityManager.isNetworkTypeWifi(type)) {
514 if (mLastPowerStateFromWifi != powerState) {
515 mLastPowerStateFromWifi = powerState;
516 try {
Adam Lesinski5f056f62016-07-14 16:56:08 -0700517 getBatteryStats().noteWifiRadioPowerState(powerState, tsNanos, uid);
Adam Lesinskie08af192015-03-25 16:42:59 -0700518 } catch (RemoteException e) {
519 }
Bookatz0b028b12018-05-31 16:51:17 -0700520 StatsLog.write_non_chained(StatsLog.WIFI_RADIO_POWER_STATE_CHANGED, uid, null,
521 powerState);
Adam Lesinskie08af192015-03-25 16:42:59 -0700522 }
523 }
524
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700525 boolean isActive = powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_MEDIUM
526 || powerState == DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH;
527
528 if (!isMobile || fromRadio || !mMobileActivityFromRadio) {
529 // Report the change in data activity. We don't do this if this is a change
530 // on the mobile network, that is not coming from the radio itself, and we
531 // have previously seen change reports from the radio. In that case only
532 // the radio is the authority for the current state.
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900533 final boolean active = isActive;
534 invokeForAllObservers(o -> o.interfaceClassDataActivityChanged(
535 Integer.toString(type), active, tsNanos));
Haoyu Baidb3c8672012-06-20 14:29:57 -0700536 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800537
538 boolean report = false;
539 synchronized (mIdleTimerLock) {
540 if (mActiveIdleTimers.isEmpty()) {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700541 // If there are no idle timers, we are not monitoring activity, so we
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800542 // are always considered active.
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700543 isActive = true;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800544 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700545 if (mNetworkActive != isActive) {
546 mNetworkActive = isActive;
547 report = isActive;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800548 }
549 }
550 if (report) {
551 reportNetworkActive();
552 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700553 }
554
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900555 @Override
556 public void registerTetheringStatsProvider(ITetheringStatsProvider provider, String name) {
557 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
558 Preconditions.checkNotNull(provider);
559 synchronized(mTetheringStatsProviders) {
560 mTetheringStatsProviders.put(provider, name);
561 }
562 }
563
564 @Override
565 public void unregisterTetheringStatsProvider(ITetheringStatsProvider provider) {
566 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
567 synchronized(mTetheringStatsProviders) {
568 mTetheringStatsProviders.remove(provider);
569 }
570 }
571
Lorenzo Colitti9f0baa92017-08-15 19:25:51 +0900572 @Override
573 public void tetherLimitReached(ITetheringStatsProvider provider) {
574 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
575 synchronized(mTetheringStatsProviders) {
576 if (!mTetheringStatsProviders.containsKey(provider)) {
577 return;
578 }
579 // No current code examines the interface parameter in a global alert. Just pass null.
580 notifyLimitReached(LIMIT_GLOBAL_ALERT, null);
581 }
582 }
583
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900584 // Sync the state of the given chain with the native daemon.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700585 private void syncFirewallChainLocked(int chain, String name) {
586 SparseIntArray rules;
587 synchronized (mRulesLock) {
588 final SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900589 // Make a copy of the current rules, and then clear them. This is because
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700590 // setFirewallUidRuleInternal only pushes down rules to the native daemon if they
591 // are different from the current rules stored in the mUidFirewall*Rules array for
592 // the specified chain. If we don't clear the rules, setFirewallUidRuleInternal
593 // will do nothing.
594 rules = uidFirewallRules.clone();
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900595 uidFirewallRules.clear();
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700596 }
597 if (rules.size() > 0) {
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900598 // Now push the rules. setFirewallUidRuleInternal will push each of these down to the
599 // native daemon, and also add them to the mUidFirewall*Rules array for the specified
600 // chain.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700601 if (DBG) Slog.d(TAG, "Pushing " + rules.size() + " active firewall "
602 + name + "UID rules");
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900603 for (int i = 0; i < rules.size(); i++) {
Felipe Lemea701cad2016-05-12 09:58:14 -0700604 setFirewallUidRuleLocked(chain, rules.keyAt(i), rules.valueAt(i));
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900605 }
606 }
607 }
608
bohu07cc3bb2016-05-03 15:58:01 -0700609 private void connectNativeNetdService() {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900610 mNetdService = mServices.getNetd();
bohu07cc3bb2016-05-03 15:58:01 -0700611 }
612
613 /**
614 * Prepare native daemon once connected, enabling modules and pushing any
615 * existing in-memory rules.
616 */
617 private void prepareNativeDaemon() {
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900618
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700619 // push any existing quota or UID rules
620 synchronized (mQuotaLock) {
Felipe Leme65be3022016-03-22 14:53:13 -0700621
Luke Huang56a03a02018-09-07 12:02:16 +0800622 // Netd unconditionally enable bandwidth control
623 SystemProperties.set(PROP_QTAGUID_ENABLED, "1");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900624
Luke Huang473eb872018-07-26 17:33:14 +0800625 mStrictEnabled = true;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900626
Felipe Leme65be3022016-03-22 14:53:13 -0700627 setDataSaverModeEnabled(mDataSaverMode);
628
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700629 int size = mActiveQuotas.size();
630 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800631 if (DBG) Slog.d(TAG, "Pushing " + size + " active quota rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700632 final HashMap<String, Long> activeQuotas = mActiveQuotas;
633 mActiveQuotas = Maps.newHashMap();
634 for (Map.Entry<String, Long> entry : activeQuotas.entrySet()) {
635 setInterfaceQuota(entry.getKey(), entry.getValue());
636 }
637 }
638
639 size = mActiveAlerts.size();
640 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800641 if (DBG) Slog.d(TAG, "Pushing " + size + " active alert rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700642 final HashMap<String, Long> activeAlerts = mActiveAlerts;
643 mActiveAlerts = Maps.newHashMap();
644 for (Map.Entry<String, Long> entry : activeAlerts.entrySet()) {
645 setInterfaceAlert(entry.getKey(), entry.getValue());
646 }
647 }
648
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700649 SparseBooleanArray uidRejectOnQuota = null;
650 SparseBooleanArray uidAcceptOnQuota = null;
651 synchronized (mRulesLock) {
652 size = mUidRejectOnMetered.size();
653 if (size > 0) {
654 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered blacklist rules");
655 uidRejectOnQuota = mUidRejectOnMetered;
656 mUidRejectOnMetered = new SparseBooleanArray();
657 }
658
659 size = mUidAllowOnMetered.size();
660 if (size > 0) {
661 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered whitelist rules");
662 uidAcceptOnQuota = mUidAllowOnMetered;
663 mUidAllowOnMetered = new SparseBooleanArray();
664 }
665 }
666 if (uidRejectOnQuota != null) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700667 for (int i = 0; i < uidRejectOnQuota.size(); i++) {
Felipe Leme65be3022016-03-22 14:53:13 -0700668 setUidMeteredNetworkBlacklist(uidRejectOnQuota.keyAt(i),
669 uidRejectOnQuota.valueAt(i));
670 }
671 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700672 if (uidAcceptOnQuota != null) {
Felipe Leme65be3022016-03-22 14:53:13 -0700673 for (int i = 0; i < uidAcceptOnQuota.size(); i++) {
674 setUidMeteredNetworkWhitelist(uidAcceptOnQuota.keyAt(i),
675 uidAcceptOnQuota.valueAt(i));
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700676 }
677 }
Jeff Sharkey605eb792014-11-04 13:34:06 -0800678
679 size = mUidCleartextPolicy.size();
680 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800681 if (DBG) Slog.d(TAG, "Pushing " + size + " active UID cleartext policies");
Jeff Sharkey605eb792014-11-04 13:34:06 -0800682 final SparseIntArray local = mUidCleartextPolicy;
683 mUidCleartextPolicy = new SparseIntArray();
684 for (int i = 0; i < local.size(); i++) {
685 setUidCleartextNetworkPolicy(local.keyAt(i), local.valueAt(i));
686 }
687 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700688
Robin Leec3736bc2017-03-10 16:19:54 +0000689 setFirewallEnabled(mFirewallEnabled);
Amith Yamasani15e472352015-04-24 19:06:07 -0700690
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700691 syncFirewallChainLocked(FIREWALL_CHAIN_NONE, "");
692 syncFirewallChainLocked(FIREWALL_CHAIN_STANDBY, "standby ");
693 syncFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, "dozable ");
694 syncFirewallChainLocked(FIREWALL_CHAIN_POWERSAVE, "powersave ");
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700695
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700696 final int[] chains =
697 {FIREWALL_CHAIN_STANDBY, FIREWALL_CHAIN_DOZABLE, FIREWALL_CHAIN_POWERSAVE};
698 for (int chain : chains) {
699 if (getFirewallChainState(chain)) {
700 setFirewallChainEnabled(chain, true);
701 }
Felipe Leme011b98f2016-02-10 17:28:31 -0800702 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700703 }
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900704
Luke Huang56a03a02018-09-07 12:02:16 +0800705
706 try {
707 getBatteryStats().noteNetworkStatsEnabled();
708 } catch (RemoteException e) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900709 }
710
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700711 }
San Mehat4d02d002010-01-22 16:07:46 -0800712
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900713 /**
714 * Notify our observers of a new or updated interface address.
715 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900716 private void notifyAddressUpdated(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900717 invokeForAllObservers(o -> o.addressUpdated(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900718 }
719
720 /**
721 * Notify our observers of a deleted interface address.
722 */
Lorenzo Colitti64483942013-11-15 18:43:52 +0900723 private void notifyAddressRemoved(String iface, LinkAddress address) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900724 invokeForAllObservers(o -> o.addressRemoved(iface, address));
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900725 }
726
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900727 /**
728 * Notify our observers of DNS server information received.
729 */
730 private void notifyInterfaceDnsServerInfo(String iface, long lifetime, String[] addresses) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900731 invokeForAllObservers(o -> o.interfaceDnsServerInfo(iface, lifetime, addresses));
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900732 }
733
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900734 /**
735 * Notify our observers of a route change.
736 */
737 private void notifyRouteChange(String action, RouteInfo route) {
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900738 if (action.equals("updated")) {
739 invokeForAllObservers(o -> o.routeUpdated(route));
740 } else {
741 invokeForAllObservers(o -> o.routeRemoved(route));
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900742 }
743 }
744
San Mehat873f2142010-01-14 10:25:07 -0800745 //
746 // Netd Callback handling
747 //
748
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700749 private class NetdCallbackReceiver implements INativeDaemonConnectorCallbacks {
750 @Override
San Mehat873f2142010-01-14 10:25:07 -0800751 public void onDaemonConnected() {
Felipe Leme65be3022016-03-22 14:53:13 -0700752 Slog.i(TAG, "onDaemonConnected()");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700753 // event is dispatched from internal NDC thread, so we prepare the
754 // daemon back on main thread.
755 if (mConnectedSignal != null) {
bohu07cc3bb2016-05-03 15:58:01 -0700756 // The system is booting and we're connecting to netd for the first time.
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700757 mConnectedSignal.countDown();
758 mConnectedSignal = null;
759 } else {
bohu07cc3bb2016-05-03 15:58:01 -0700760 // We're reconnecting to netd after the socket connection
761 // was interrupted (e.g., if it crashed).
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700762 mFgHandler.post(new Runnable() {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700763 @Override
764 public void run() {
bohu07cc3bb2016-05-03 15:58:01 -0700765 connectNativeNetdService();
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700766 prepareNativeDaemon();
767 }
768 });
769 }
San Mehat873f2142010-01-14 10:25:07 -0800770 }
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -0700771
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700772 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800773 public boolean onCheckHoldWakeLock(int code) {
774 return code == NetdResponseCode.InterfaceClassActivity;
775 }
776
777 @Override
San Mehat873f2142010-01-14 10:25:07 -0800778 public boolean onEvent(int code, String raw, String[] cooked) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900779 String errorMessage = String.format("Invalid event from daemon (%s)", raw);
JP Abgrall12b933d2011-07-14 18:09:22 -0700780 switch (code) {
781 case NetdResponseCode.InterfaceChange:
782 /*
783 * a network interface change occured
784 * Format: "NNN Iface added <name>"
785 * "NNN Iface removed <name>"
786 * "NNN Iface changed <name> <up/down>"
787 * "NNN Iface linkstatus <name> <up/down>"
788 */
789 if (cooked.length < 4 || !cooked[1].equals("Iface")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900790 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700791 }
792 if (cooked[2].equals("added")) {
793 notifyInterfaceAdded(cooked[3]);
794 return true;
795 } else if (cooked[2].equals("removed")) {
796 notifyInterfaceRemoved(cooked[3]);
797 return true;
798 } else if (cooked[2].equals("changed") && cooked.length == 5) {
799 notifyInterfaceStatusChanged(cooked[3], cooked[4].equals("up"));
800 return true;
801 } else if (cooked[2].equals("linkstate") && cooked.length == 5) {
802 notifyInterfaceLinkStateChanged(cooked[3], cooked[4].equals("up"));
803 return true;
804 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900805 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700806 // break;
807 case NetdResponseCode.BandwidthControl:
808 /*
809 * Bandwidth control needs some attention
810 * Format: "NNN limit alert <alertName> <ifaceName>"
811 */
812 if (cooked.length < 5 || !cooked[1].equals("limit")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900813 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700814 }
815 if (cooked[2].equals("alert")) {
816 notifyLimitReached(cooked[3], cooked[4]);
817 return true;
818 }
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900819 throw new IllegalStateException(errorMessage);
JP Abgrall12b933d2011-07-14 18:09:22 -0700820 // break;
Haoyu Baidb3c8672012-06-20 14:29:57 -0700821 case NetdResponseCode.InterfaceClassActivity:
822 /*
823 * An network interface class state changed (active/idle)
824 * Format: "NNN IfaceClass <active/idle> <label>"
825 */
826 if (cooked.length < 4 || !cooked[1].equals("IfaceClass")) {
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900827 throw new IllegalStateException(errorMessage);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700828 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700829 long timestampNanos = 0;
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700830 int processUid = -1;
831 if (cooked.length >= 5) {
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700832 try {
833 timestampNanos = Long.parseLong(cooked[4]);
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700834 if (cooked.length == 6) {
835 processUid = Integer.parseInt(cooked[5]);
836 }
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700837 } catch(NumberFormatException ne) {}
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700838 } else {
839 timestampNanos = SystemClock.elapsedRealtimeNanos();
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700840 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700841 boolean isActive = cooked[2].equals("active");
Ashish Sharma0535a9f2014-03-12 18:42:23 -0700842 notifyInterfaceClassActivity(Integer.parseInt(cooked[3]),
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700843 isActive ? DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -0700844 : DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
845 timestampNanos, processUid, false);
Haoyu Baidb3c8672012-06-20 14:29:57 -0700846 return true;
847 // break;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900848 case NetdResponseCode.InterfaceAddressChange:
849 /*
850 * A network address change occurred
851 * Format: "NNN Address updated <addr> <iface> <flags> <scope>"
852 * "NNN Address removed <addr> <iface> <flags> <scope>"
853 */
Lorenzo Colittia9626c12013-11-04 17:44:09 +0900854 if (cooked.length < 7 || !cooked[1].equals("Address")) {
855 throw new IllegalStateException(errorMessage);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900856 }
857
Lorenzo Colitti64483942013-11-15 18:43:52 +0900858 String iface = cooked[4];
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900859 LinkAddress address;
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900860 try {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900861 int flags = Integer.parseInt(cooked[5]);
862 int scope = Integer.parseInt(cooked[6]);
863 address = new LinkAddress(cooked[3], flags, scope);
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900864 } catch(NumberFormatException e) { // Non-numeric lifetime or scope.
865 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti64483942013-11-15 18:43:52 +0900866 } catch(IllegalArgumentException e) { // Malformed/invalid IP address.
Lorenzo Colitti5ad421a2013-11-17 15:05:02 +0900867 throw new IllegalStateException(errorMessage, e);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900868 }
869
870 if (cooked[2].equals("updated")) {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900871 notifyAddressUpdated(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900872 } else {
Lorenzo Colitti64483942013-11-15 18:43:52 +0900873 notifyAddressRemoved(iface, address);
Lorenzo Colitti5c7daac2013-08-05 10:39:37 +0900874 }
875 return true;
876 // break;
Lorenzo Colitti5ae4a532013-10-31 11:59:46 +0900877 case NetdResponseCode.InterfaceDnsServerInfo:
878 /*
879 * Information about available DNS servers has been received.
880 * Format: "NNN DnsInfo servers <interface> <lifetime> <servers>"
881 */
882 long lifetime; // Actually a 32-bit unsigned integer.
883
884 if (cooked.length == 6 &&
885 cooked[1].equals("DnsInfo") &&
886 cooked[2].equals("servers")) {
887 try {
888 lifetime = Long.parseLong(cooked[4]);
889 } catch (NumberFormatException e) {
890 throw new IllegalStateException(errorMessage);
891 }
892 String[] servers = cooked[5].split(",");
893 notifyInterfaceDnsServerInfo(cooked[3], lifetime, servers);
894 }
895 return true;
896 // break;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +0900897 case NetdResponseCode.RouteChange:
898 /*
899 * A route has been updated or removed.
900 * Format: "NNN Route <updated|removed> <dst> [via <gateway] [dev <iface>]"
901 */
902 if (!cooked[1].equals("Route") || cooked.length < 6) {
903 throw new IllegalStateException(errorMessage);
904 }
905
906 String via = null;
907 String dev = null;
908 boolean valid = true;
909 for (int i = 4; (i + 1) < cooked.length && valid; i += 2) {
910 if (cooked[i].equals("dev")) {
911 if (dev == null) {
912 dev = cooked[i+1];
913 } else {
914 valid = false; // Duplicate interface.
915 }
916 } else if (cooked[i].equals("via")) {
917 if (via == null) {
918 via = cooked[i+1];
919 } else {
920 valid = false; // Duplicate gateway.
921 }
922 } else {
923 valid = false; // Unknown syntax.
924 }
925 }
926 if (valid) {
927 try {
928 // InetAddress.parseNumericAddress(null) inexplicably returns ::1.
929 InetAddress gateway = null;
930 if (via != null) gateway = InetAddress.parseNumericAddress(via);
931 RouteInfo route = new RouteInfo(new IpPrefix(cooked[3]), gateway, dev);
932 notifyRouteChange(cooked[2], route);
933 return true;
934 } catch (IllegalArgumentException e) {}
935 }
936 throw new IllegalStateException(errorMessage);
937 // break;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800938 case NetdResponseCode.StrictCleartext:
939 final int uid = Integer.parseInt(cooked[1]);
940 final byte[] firstPacket = HexDump.hexStringToByteArray(cooked[2]);
941 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -0800942 ActivityManager.getService().notifyCleartextNetwork(uid, firstPacket);
Jeff Sharkey605eb792014-11-04 13:34:06 -0800943 } catch (RemoteException ignored) {
944 }
945 break;
JP Abgrall12b933d2011-07-14 18:09:22 -0700946 default: break;
Robert Greenwalte3253922010-02-18 09:23:25 -0800947 }
948 return false;
San Mehat873f2142010-01-14 10:25:07 -0800949 }
950 }
951
San Mehated4fc8a2010-01-22 12:28:36 -0800952
San Mehat873f2142010-01-14 10:25:07 -0800953 //
954 // INetworkManagementService members
955 //
Erik Kline4e37b702016-07-05 11:34:21 +0900956 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800957 public String[] listInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800958 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700959 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +0800960 return mNetdService.interfaceGetList();
Luke Huang14f75442018-08-15 19:22:54 +0800961 } catch (RemoteException | ServiceSpecificException e) {
962 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700963 }
San Mehated4fc8a2010-01-22 12:28:36 -0800964 }
965
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800966 @Override
967 public InterfaceConfiguration getInterfaceConfig(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800968 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang14f75442018-08-15 19:22:54 +0800969 final InterfaceConfigurationParcel result;
Kenny Roota80ce062010-06-01 13:23:53 -0700970 try {
Luke Huang14f75442018-08-15 19:22:54 +0800971 result = mNetdService.interfaceGetCfg(iface);
972 } catch (RemoteException | ServiceSpecificException e) {
973 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700974 }
San Mehated4fc8a2010-01-22 12:28:36 -0800975
San Mehated4fc8a2010-01-22 12:28:36 -0800976 try {
Luke Huang14f75442018-08-15 19:22:54 +0800977 final InterfaceConfiguration cfg = InterfaceConfiguration.fromParcel(result);
978 return cfg;
979 } catch (IllegalArgumentException iae) {
980 throw new IllegalStateException("Invalid InterfaceConfigurationParcel", iae);
San Mehated4fc8a2010-01-22 12:28:36 -0800981 }
San Mehated4fc8a2010-01-22 12:28:36 -0800982 }
983
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800984 @Override
985 public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800986 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800987 LinkAddress linkAddr = cfg.getLinkAddress();
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800988 if (linkAddr == null || linkAddr.getAddress() == null) {
989 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -0800990 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800991
Luke Huang14f75442018-08-15 19:22:54 +0800992 final InterfaceConfigurationParcel cfgParcel = cfg.toParcel(iface);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800993
Kenny Roota80ce062010-06-01 13:23:53 -0700994 try {
Luke Huang14f75442018-08-15 19:22:54 +0800995 mNetdService.interfaceSetCfg(cfgParcel);
996 } catch (RemoteException | ServiceSpecificException e) {
997 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700998 }
San Mehat873f2142010-01-14 10:25:07 -0800999 }
1000
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001001 @Override
1002 public void setInterfaceDown(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001003 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001004 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001005 ifcg.setInterfaceDown();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001006 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001007 }
1008
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001009 @Override
1010 public void setInterfaceUp(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001011 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001012 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -08001013 ifcg.setInterfaceUp();
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001014 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -07001015 }
1016
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001017 @Override
1018 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001019 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sheriff73293612011-09-14 12:31:56 -07001020 try {
Luke Huang14f75442018-08-15 19:22:54 +08001021 mNetdService.interfaceSetIPv6PrivacyExtensions(iface, enable);
1022 } catch (RemoteException | ServiceSpecificException e) {
1023 throw new IllegalStateException(e);
Irfan Sheriff73293612011-09-14 12:31:56 -07001024 }
1025 }
1026
Irfan Sherifff5600612011-06-16 10:26:28 -07001027 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
1028 IPv6 addresses on interface down, but we need to do full clean up here */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001029 @Override
1030 public void clearInterfaceAddresses(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001031 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sherifff5600612011-06-16 10:26:28 -07001032 try {
Luke Huang14f75442018-08-15 19:22:54 +08001033 mNetdService.interfaceClearAddrs(iface);
1034 } catch (RemoteException | ServiceSpecificException e) {
1035 throw new IllegalStateException(e);
Irfan Sherifff5600612011-06-16 10:26:28 -07001036 }
1037 }
1038
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001039 @Override
1040 public void enableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001041 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001042 try {
Luke Huang14f75442018-08-15 19:22:54 +08001043 mNetdService.interfaceSetEnableIPv6(iface, true);
1044 } catch (RemoteException | ServiceSpecificException e) {
1045 throw new IllegalStateException(e);
repo sync7960d9f2011-09-29 12:40:02 -07001046 }
1047 }
1048
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001049 @Override
Joel Scherpelz2db10742017-06-07 15:38:38 +09001050 public void setIPv6AddrGenMode(String iface, int mode) throws ServiceSpecificException {
1051 try {
1052 mNetdService.setIPv6AddrGenMode(iface, mode);
1053 } catch (RemoteException e) {
1054 throw e.rethrowAsRuntimeException();
1055 }
1056 }
1057
1058 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001059 public void disableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001060 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -07001061 try {
Luke Huang14f75442018-08-15 19:22:54 +08001062 mNetdService.interfaceSetEnableIPv6(iface, false);
1063 } catch (RemoteException | ServiceSpecificException e) {
1064 throw new IllegalStateException(e);
repo sync7960d9f2011-09-29 12:40:02 -07001065 }
1066 }
1067
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001068 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001069 public void addRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001070 modifyRoute(MODIFY_OPERATION_ADD, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001071 }
1072
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001073 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -07001074 public void removeRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001075 modifyRoute(MODIFY_OPERATION_REMOVE, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001076 }
1077
Luke Huang8a462ec2018-08-24 20:33:16 +08001078 private void modifyRoute(boolean add, int netId, RouteInfo route) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001079 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -07001080
Luke Huang8a462ec2018-08-24 20:33:16 +08001081 final String ifName = route.getInterface();
1082 final String dst = route.getDestination().toString();
1083 final String nextHop;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001084
1085 switch (route.getType()) {
1086 case RouteInfo.RTN_UNICAST:
1087 if (route.hasGateway()) {
Luke Huang8a462ec2018-08-24 20:33:16 +08001088 nextHop = route.getGateway().getHostAddress();
1089 } else {
1090 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001091 }
1092 break;
1093 case RouteInfo.RTN_UNREACHABLE:
Luke Huang8a462ec2018-08-24 20:33:16 +08001094 nextHop = INetd.NEXTHOP_UNREACHABLE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001095 break;
1096 case RouteInfo.RTN_THROW:
Luke Huang8a462ec2018-08-24 20:33:16 +08001097 nextHop = INetd.NEXTHOP_THROW;
1098 break;
1099 default:
1100 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +09001101 break;
Sreeram Ramachandran1fbcb272014-05-22 16:30:48 -07001102 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001103 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08001104 if (add) {
1105 mNetdService.networkAddRoute(netId, ifName, dst, nextHop);
1106 } else {
1107 mNetdService.networkRemoveRoute(netId, ifName, dst, nextHop);
1108 }
1109 } catch (RemoteException | ServiceSpecificException e) {
1110 throw new IllegalStateException(e);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001111 }
1112 }
1113
1114 private ArrayList<String> readRouteList(String filename) {
1115 FileInputStream fstream = null;
Christopher Wiley212b95f2016-08-02 11:38:57 -07001116 ArrayList<String> list = new ArrayList<>();
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -07001117
1118 try {
1119 fstream = new FileInputStream(filename);
1120 DataInputStream in = new DataInputStream(fstream);
1121 BufferedReader br = new BufferedReader(new InputStreamReader(in));
1122 String s;
1123
1124 // throw away the title line
1125
1126 while (((s = br.readLine()) != null) && (s.length() != 0)) {
1127 list.add(s);
1128 }
1129 } catch (IOException ex) {
1130 // return current list, possibly empty
1131 } finally {
1132 if (fstream != null) {
1133 try {
1134 fstream.close();
1135 } catch (IOException ex) {}
1136 }
1137 }
1138
1139 return list;
1140 }
1141
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001142 @Override
sy.yun9d9b74a2013-09-02 05:24:09 +09001143 public void setMtu(String iface, int mtu) {
1144 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1145
sy.yun9d9b74a2013-09-02 05:24:09 +09001146 try {
Luke Huang14f75442018-08-15 19:22:54 +08001147 mNetdService.interfaceSetMtu(iface, mtu);
1148 } catch (RemoteException | ServiceSpecificException e) {
1149 throw new IllegalStateException(e);
sy.yun9d9b74a2013-09-02 05:24:09 +09001150 }
1151 }
1152
1153 @Override
San Mehat873f2142010-01-14 10:25:07 -08001154 public void shutdown() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001155 // TODO: remove from aidl if nobody calls externally
1156 mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001157
Felipe Leme03e689d2016-03-02 16:17:38 -08001158 Slog.i(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -08001159 }
1160
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001161 @Override
San Mehat873f2142010-01-14 10:25:07 -08001162 public boolean getIpForwardingEnabled() throws IllegalStateException{
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001163 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001164
Kenny Roota80ce062010-06-01 13:23:53 -07001165 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001166 final boolean isEnabled = mNetdService.ipfwdEnabled();
1167 return isEnabled;
1168 } catch (RemoteException | ServiceSpecificException e) {
1169 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001170 }
San Mehat873f2142010-01-14 10:25:07 -08001171 }
1172
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001173 @Override
1174 public void setIpForwardingEnabled(boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001175 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001176 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001177 if (enable) {
1178 mNetdService.ipfwdEnableForwarding("tethering");
1179 } else {
1180 mNetdService.ipfwdDisableForwarding("tethering");
1181 }
1182 } catch (RemoteException | ServiceSpecificException e) {
1183 throw new IllegalStateException(e);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001184 }
San Mehat873f2142010-01-14 10:25:07 -08001185 }
1186
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001187 @Override
1188 public void startTethering(String[] dhcpRange) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001189 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -07001190 // an odd number of addrs will fail
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001191
Kenny Roota80ce062010-06-01 13:23:53 -07001192 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001193 mNetdService.tetherStart(dhcpRange);
1194 } catch (RemoteException | ServiceSpecificException e) {
1195 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001196 }
San Mehat873f2142010-01-14 10:25:07 -08001197 }
1198
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001199 @Override
1200 public void stopTethering() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001201 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001202 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001203 mNetdService.tetherStop();
1204 } catch (RemoteException | ServiceSpecificException e) {
1205 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001206 }
San Mehat873f2142010-01-14 10:25:07 -08001207 }
1208
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001209 @Override
1210 public boolean isTetheringStarted() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001211 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001212
Kenny Roota80ce062010-06-01 13:23:53 -07001213 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001214 final boolean isEnabled = mNetdService.tetherIsEnabled();
1215 return isEnabled;
1216 } catch (RemoteException | ServiceSpecificException e) {
1217 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001218 }
San Mehat873f2142010-01-14 10:25:07 -08001219 }
Matthew Xiefe19f122012-07-12 16:03:32 -07001220
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001221 @Override
1222 public void tetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001223 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001224 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001225 mNetdService.tetherInterfaceAdd(iface);
1226 } catch (RemoteException | ServiceSpecificException e) {
1227 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001228 }
Christopher Wiley212b95f2016-08-02 11:38:57 -07001229 List<RouteInfo> routes = new ArrayList<>();
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07001230 // The RouteInfo constructor truncates the LinkAddress to a network prefix, thus making it
1231 // suitable to use as a route destination.
1232 routes.add(new RouteInfo(getInterfaceConfig(iface).getLinkAddress(), null, iface));
1233 addInterfaceToLocalNetwork(iface, routes);
San Mehat873f2142010-01-14 10:25:07 -08001234 }
1235
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001236 @Override
San Mehat873f2142010-01-14 10:25:07 -08001237 public void untetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001238 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001239 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001240 mNetdService.tetherInterfaceRemove(iface);
1241 } catch (RemoteException | ServiceSpecificException e) {
1242 throw new IllegalStateException(e);
Erik Kline1f4278a2016-08-16 16:46:33 +09001243 } finally {
1244 removeInterfaceFromLocalNetwork(iface);
Kenny Roota80ce062010-06-01 13:23:53 -07001245 }
San Mehat873f2142010-01-14 10:25:07 -08001246 }
1247
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001248 @Override
1249 public String[] listTetheredInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001250 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001251 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +08001252 return mNetdService.tetherInterfaceList();
Luke Huang4a32bf42018-08-21 19:09:45 +08001253 } catch (RemoteException | ServiceSpecificException e) {
1254 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001255 }
San Mehat873f2142010-01-14 10:25:07 -08001256 }
1257
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001258 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001259 public void setDnsForwarders(Network network, String[] dns) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001260 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001261
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001262 int netId = (network != null) ? network.netId : ConnectivityManager.NETID_UNSET;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001263
San Mehat873f2142010-01-14 10:25:07 -08001264 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001265 mNetdService.tetherDnsSet(netId, dns);
1266 } catch (RemoteException | ServiceSpecificException e) {
1267 throw new IllegalStateException(e);
San Mehat873f2142010-01-14 10:25:07 -08001268 }
1269 }
1270
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001271 @Override
1272 public String[] getDnsForwarders() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001273 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001274 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +08001275 return mNetdService.tetherDnsList();
Luke Huang4a32bf42018-08-21 19:09:45 +08001276 } catch (RemoteException | ServiceSpecificException e) {
1277 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001278 }
San Mehat873f2142010-01-14 10:25:07 -08001279 }
1280
jiaguo1da35f72014-01-09 16:39:59 +08001281 private List<InterfaceAddress> excludeLinkLocal(List<InterfaceAddress> addresses) {
Christopher Wiley212b95f2016-08-02 11:38:57 -07001282 ArrayList<InterfaceAddress> filtered = new ArrayList<>(addresses.size());
jiaguo1da35f72014-01-09 16:39:59 +08001283 for (InterfaceAddress ia : addresses) {
1284 if (!ia.getAddress().isLinkLocalAddress())
1285 filtered.add(ia);
1286 }
1287 return filtered;
1288 }
1289
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001290 private void modifyInterfaceForward(boolean add, String fromIface, String toIface) {
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001291 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001292 if (add) {
1293 mNetdService.ipfwdAddInterfaceForward(fromIface, toIface);
1294 } else {
1295 mNetdService.ipfwdRemoveInterfaceForward(fromIface, toIface);
1296 }
1297 } catch (RemoteException | ServiceSpecificException e) {
1298 throw new IllegalStateException(e);
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001299 }
1300 }
1301
1302 @Override
1303 public void startInterfaceForwarding(String fromIface, String toIface) {
1304 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1305 modifyInterfaceForward(true, fromIface, toIface);
1306 }
1307
1308 @Override
1309 public void stopInterfaceForwarding(String fromIface, String toIface) {
1310 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1311 modifyInterfaceForward(false, fromIface, toIface);
1312 }
1313
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001314 @Override
1315 public void enableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001316 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001317 try {
Luke Huanga31e0732018-10-22 13:23:10 +09001318 mNetdService.tetherAddForward(internalInterface, externalInterface);
1319 } catch (RemoteException | ServiceSpecificException e) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001320 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001321 }
San Mehat873f2142010-01-14 10:25:07 -08001322 }
1323
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001324 @Override
1325 public void disableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001326 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001327 try {
Luke Huanga31e0732018-10-22 13:23:10 +09001328 mNetdService.tetherRemoveForward(internalInterface, externalInterface);
1329 } catch (RemoteException | ServiceSpecificException e) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001330 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001331 }
San Mehat873f2142010-01-14 10:25:07 -08001332 }
San Mehat72759df2010-01-19 13:50:37 -08001333
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001334 @Override
1335 public String[] listTtys() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001336 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001337 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001338 return NativeDaemonEvent.filterMessageList(
1339 mConnector.executeForList("list_ttys"), TtyListResult);
Kenny Roota80ce062010-06-01 13:23:53 -07001340 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001341 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001342 }
San Mehat72759df2010-01-19 13:50:37 -08001343 }
1344
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001345 @Override
1346 public void attachPppd(
1347 String tty, String localAddr, String remoteAddr, String dns1Addr, String dns2Addr) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001348 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat72759df2010-01-19 13:50:37 -08001349 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001350 mConnector.execute("pppd", "attach", tty,
Robert Greenwalte5903732011-02-22 16:00:42 -08001351 NetworkUtils.numericToInetAddress(localAddr).getHostAddress(),
1352 NetworkUtils.numericToInetAddress(remoteAddr).getHostAddress(),
1353 NetworkUtils.numericToInetAddress(dns1Addr).getHostAddress(),
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001354 NetworkUtils.numericToInetAddress(dns2Addr).getHostAddress());
Kenny Roota80ce062010-06-01 13:23:53 -07001355 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001356 throw e.rethrowAsParcelableException();
San Mehat72759df2010-01-19 13:50:37 -08001357 }
1358 }
1359
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001360 @Override
1361 public void detachPppd(String tty) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001362 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001363 try {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001364 mConnector.execute("pppd", "detach", tty);
Kenny Roota80ce062010-06-01 13:23:53 -07001365 } catch (NativeDaemonConnectorException e) {
Jeff Sharkey276642b2011-12-01 11:24:24 -08001366 throw e.rethrowAsParcelableException();
Kenny Roota80ce062010-06-01 13:23:53 -07001367 }
San Mehat72759df2010-01-19 13:50:37 -08001368 }
Robert Greenwaltce1200d2010-02-18 11:25:54 -08001369
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001370 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001371 public void addIdleTimer(String iface, int timeout, final int type) {
Haoyu Bai04124232012-06-28 15:26:19 -07001372 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1373
1374 if (DBG) Slog.d(TAG, "Adding idletimer");
1375
1376 synchronized (mIdleTimerLock) {
1377 IdleTimerParams params = mActiveIdleTimers.get(iface);
1378 if (params != null) {
1379 // the interface already has idletimer, update network count
1380 params.networkCount++;
1381 return;
1382 }
1383
1384 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001385 mNetdService.idletimerAddInterface(iface, timeout, Integer.toString(type));
1386 } catch (RemoteException | ServiceSpecificException e) {
1387 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001388 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001389 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
1390
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001391 // Networks start up.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001392 if (ConnectivityManager.isNetworkTypeMobile(type)) {
1393 mNetworkActive = false;
1394 }
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001395 mDaemonHandler.post(new Runnable() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001396 @Override public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001397 notifyInterfaceClassActivity(type,
1398 DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07001399 SystemClock.elapsedRealtimeNanos(), -1, false);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001400 }
1401 });
Haoyu Bai04124232012-06-28 15:26:19 -07001402 }
1403 }
1404
1405 @Override
1406 public void removeIdleTimer(String iface) {
1407 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1408
1409 if (DBG) Slog.d(TAG, "Removing idletimer");
1410
1411 synchronized (mIdleTimerLock) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001412 final IdleTimerParams params = mActiveIdleTimers.get(iface);
Haoyu Bai04124232012-06-28 15:26:19 -07001413 if (params == null || --(params.networkCount) > 0) {
1414 return;
1415 }
1416
1417 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001418 mNetdService.idletimerRemoveInterface(iface,
1419 params.timeout, Integer.toString(params.type));
1420 } catch (RemoteException | ServiceSpecificException e) {
1421 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001422 }
1423 mActiveIdleTimers.remove(iface);
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001424 mDaemonHandler.post(new Runnable() {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001425 @Override public void run() {
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001426 notifyInterfaceClassActivity(params.type,
1427 DataConnectionRealTimeInfo.DC_POWER_STATE_LOW,
Ruchi Kandoifa97fcf2016-05-13 15:10:39 -07001428 SystemClock.elapsedRealtimeNanos(), -1, false);
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001429 }
1430 });
Haoyu Bai04124232012-06-28 15:26:19 -07001431 }
1432 }
1433
1434 @Override
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001435 public NetworkStats getNetworkStatsSummaryDev() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001436 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001437 try {
1438 return mStatsFactory.readNetworkStatsSummaryDev();
1439 } catch (IOException e) {
1440 throw new IllegalStateException(e);
1441 }
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001442 }
1443
1444 @Override
1445 public NetworkStats getNetworkStatsSummaryXt() {
1446 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001447 try {
1448 return mStatsFactory.readNetworkStatsSummaryXt();
1449 } catch (IOException e) {
1450 throw new IllegalStateException(e);
1451 }
Jeff Sharkeyae2c1812011-10-04 13:11:40 -07001452 }
1453
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001454 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001455 public NetworkStats getNetworkStatsDetail() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001456 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001457 try {
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08001458 return mStatsFactory.readNetworkStatsDetail(UID_ALL, null, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001459 } catch (IOException e) {
1460 throw new IllegalStateException(e);
1461 }
San Mehat91cac642010-03-31 14:31:36 -07001462 }
1463
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001464 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001465 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001466 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001467
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001468 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001469 if (mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001470 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001471 }
1472
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001473 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001474 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001475 mNetdService.bandwidthSetInterfaceQuota(iface, quotaBytes);
1476
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001477 mActiveQuotas.put(iface, quotaBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001478 } catch (RemoteException | ServiceSpecificException e) {
1479 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001480 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001481
1482 synchronized (mTetheringStatsProviders) {
1483 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1484 try {
1485 provider.setInterfaceQuota(iface, quotaBytes);
1486 } catch (RemoteException e) {
1487 Log.e(TAG, "Problem setting tethering data limit on provider " +
1488 mTetheringStatsProviders.get(provider) + ": " + e);
1489 }
1490 }
1491 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001492 }
1493 }
1494
1495 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001496 public void removeInterfaceQuota(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001497 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001498
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001499 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001500 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001501 // TODO: eventually consider throwing
1502 return;
1503 }
1504
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001505 mActiveQuotas.remove(iface);
1506 mActiveAlerts.remove(iface);
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001507
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001508 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001509 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001510 mNetdService.bandwidthRemoveInterfaceQuota(iface);
1511 } catch (RemoteException | ServiceSpecificException e) {
1512 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001513 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001514
1515 synchronized (mTetheringStatsProviders) {
1516 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1517 try {
1518 provider.setInterfaceQuota(iface, ITetheringStatsProvider.QUOTA_UNLIMITED);
1519 } catch (RemoteException e) {
1520 Log.e(TAG, "Problem removing tethering data limit on provider " +
1521 mTetheringStatsProviders.get(provider) + ": " + e);
1522 }
1523 }
1524 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001525 }
1526 }
1527
1528 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001529 public void setInterfaceAlert(String iface, long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001530 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001531
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001532 // quick sanity check
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001533 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001534 throw new IllegalStateException("setting alert requires existing quota on iface");
1535 }
1536
1537 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001538 if (mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001539 throw new IllegalStateException("iface " + iface + " already has alert");
1540 }
1541
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001542 try {
1543 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001544 mNetdService.bandwidthSetInterfaceAlert(iface, alertBytes);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001545 mActiveAlerts.put(iface, alertBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001546 } catch (RemoteException | ServiceSpecificException e) {
1547 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001548 }
1549 }
1550 }
1551
1552 @Override
1553 public void removeInterfaceAlert(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001554 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001555
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001556 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001557 if (!mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001558 // TODO: eventually consider throwing
1559 return;
1560 }
1561
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001562 try {
1563 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001564 mNetdService.bandwidthRemoveInterfaceAlert(iface);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001565 mActiveAlerts.remove(iface);
Luke Huangc7bea8662018-08-07 16:04:26 +08001566 } catch (RemoteException | ServiceSpecificException e) {
1567 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001568 }
1569 }
1570 }
1571
1572 @Override
1573 public void setGlobalAlert(long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001574 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001575
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001576 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001577 mNetdService.bandwidthSetGlobalAlert(alertBytes);
1578 } catch (RemoteException | ServiceSpecificException e) {
1579 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001580 }
1581 }
1582
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001583 private void setUidOnMeteredNetworkList(int uid, boolean blacklist, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001584 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001585
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001586 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001587 boolean oldEnable;
1588 SparseBooleanArray quotaList;
1589 synchronized (mRulesLock) {
1590 quotaList = blacklist ? mUidRejectOnMetered : mUidAllowOnMetered;
1591 oldEnable = quotaList.get(uid, false);
1592 }
Felipe Leme65be3022016-03-22 14:53:13 -07001593 if (oldEnable == enable) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001594 // TODO: eventually consider throwing
1595 return;
1596 }
1597
Felipe Leme29e72ea2016-09-08 13:26:55 -07001598 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "inetd bandwidth");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001599 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001600 if (blacklist) {
1601 if (enable) {
1602 mNetdService.bandwidthAddNaughtyApp(uid);
1603 } else {
1604 mNetdService.bandwidthRemoveNaughtyApp(uid);
1605 }
1606 } else {
1607 if (enable) {
1608 mNetdService.bandwidthAddNiceApp(uid);
1609 } else {
1610 mNetdService.bandwidthRemoveNiceApp(uid);
1611 }
1612 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001613 synchronized (mRulesLock) {
1614 if (enable) {
1615 quotaList.put(uid, true);
1616 } else {
1617 quotaList.delete(uid);
1618 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001619 }
Luke Huangc7bea8662018-08-07 16:04:26 +08001620 } catch (RemoteException | ServiceSpecificException e) {
1621 throw new IllegalStateException(e);
Felipe Leme29e72ea2016-09-08 13:26:55 -07001622 } finally {
1623 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001624 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001625 }
1626 }
1627
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001628 @Override
Felipe Leme65be3022016-03-22 14:53:13 -07001629 public void setUidMeteredNetworkBlacklist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001630 setUidOnMeteredNetworkList(uid, true, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001631 }
1632
1633 @Override
1634 public void setUidMeteredNetworkWhitelist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001635 setUidOnMeteredNetworkList(uid, false, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001636 }
1637
1638 @Override
1639 public boolean setDataSaverModeEnabled(boolean enable) {
Sehee Parka9139bc2017-12-22 13:54:05 +09001640 mContext.enforceCallingOrSelfPermission(NETWORK_SETTINGS, TAG);
1641
Felipe Leme65be3022016-03-22 14:53:13 -07001642 if (DBG) Log.d(TAG, "setDataSaverMode: " + enable);
1643 synchronized (mQuotaLock) {
1644 if (mDataSaverMode == enable) {
1645 Log.w(TAG, "setDataSaverMode(): already " + mDataSaverMode);
1646 return true;
1647 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07001648 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "bandwidthEnableDataSaver");
Felipe Leme65be3022016-03-22 14:53:13 -07001649 try {
1650 final boolean changed = mNetdService.bandwidthEnableDataSaver(enable);
1651 if (changed) {
1652 mDataSaverMode = enable;
1653 } else {
1654 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command silently failed");
1655 }
1656 return changed;
1657 } catch (RemoteException e) {
1658 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command failed", e);
1659 return false;
Felipe Leme29e72ea2016-09-08 13:26:55 -07001660 } finally {
1661 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme65be3022016-03-22 14:53:13 -07001662 }
1663 }
1664 }
1665
1666 @Override
Robin Lee17e61832016-05-09 13:46:28 +01001667 public void setAllowOnlyVpnForUids(boolean add, UidRange[] uidRanges)
1668 throws ServiceSpecificException {
Rubin Xube806662018-01-11 10:59:19 +00001669 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robin Lee17e61832016-05-09 13:46:28 +01001670 try {
1671 mNetdService.networkRejectNonSecureVpn(add, uidRanges);
1672 } catch (ServiceSpecificException e) {
1673 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1674 + ": netd command failed", e);
1675 throw e;
1676 } catch (RemoteException e) {
1677 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1678 + ": netd command failed", e);
1679 throw e.rethrowAsRuntimeException();
1680 }
1681 }
1682
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001683 private void applyUidCleartextNetworkPolicy(int uid, int policy) {
Luke Huang473eb872018-07-26 17:33:14 +08001684 final int policyValue;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001685 switch (policy) {
1686 case StrictMode.NETWORK_POLICY_ACCEPT:
Luke Huang473eb872018-07-26 17:33:14 +08001687 policyValue = INetd.PENALTY_POLICY_ACCEPT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001688 break;
1689 case StrictMode.NETWORK_POLICY_LOG:
Luke Huang473eb872018-07-26 17:33:14 +08001690 policyValue = INetd.PENALTY_POLICY_LOG;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001691 break;
1692 case StrictMode.NETWORK_POLICY_REJECT:
Luke Huang473eb872018-07-26 17:33:14 +08001693 policyValue = INetd.PENALTY_POLICY_REJECT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001694 break;
1695 default:
1696 throw new IllegalArgumentException("Unknown policy " + policy);
1697 }
1698
1699 try {
Luke Huang473eb872018-07-26 17:33:14 +08001700 mNetdService.strictUidCleartextPenalty(uid, policyValue);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001701 mUidCleartextPolicy.put(uid, policy);
Luke Huang473eb872018-07-26 17:33:14 +08001702 } catch (RemoteException | ServiceSpecificException e) {
1703 throw new IllegalStateException(e);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001704 }
1705 }
1706
Robin Lee17e61832016-05-09 13:46:28 +01001707 @Override
Jeff Sharkey605eb792014-11-04 13:34:06 -08001708 public void setUidCleartextNetworkPolicy(int uid, int policy) {
1709 if (Binder.getCallingUid() != uid) {
1710 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1711 }
1712
1713 synchronized (mQuotaLock) {
1714 final int oldPolicy = mUidCleartextPolicy.get(uid, StrictMode.NETWORK_POLICY_ACCEPT);
1715 if (oldPolicy == policy) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001716 // This also ensures we won't needlessly apply an ACCEPT policy if we've just
1717 // enabled strict and the underlying iptables rules are empty.
Jeff Sharkey605eb792014-11-04 13:34:06 -08001718 return;
1719 }
1720
Luke Huang473eb872018-07-26 17:33:14 +08001721 // TODO: remove this code after removing prepareNativeDaemon()
Jeff Sharkey605eb792014-11-04 13:34:06 -08001722 if (!mStrictEnabled) {
1723 // Module isn't enabled yet; stash the requested policy away to
1724 // apply later once the daemon is connected.
1725 mUidCleartextPolicy.put(uid, policy);
1726 return;
1727 }
1728
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001729 // netd does not keep state on strict mode policies, and cannot replace a non-accept
1730 // policy without deleting it first. Rather than add state to netd, just always send
1731 // it an accept policy when switching between two non-accept policies.
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001732 // TODO: consider keeping state in netd so we can simplify this code.
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001733 if (oldPolicy != StrictMode.NETWORK_POLICY_ACCEPT &&
1734 policy != StrictMode.NETWORK_POLICY_ACCEPT) {
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001735 applyUidCleartextNetworkPolicy(uid, StrictMode.NETWORK_POLICY_ACCEPT);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001736 }
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001737
1738 applyUidCleartextNetworkPolicy(uid, policy);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001739 }
1740 }
1741
1742 @Override
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001743 public boolean isBandwidthControlEnabled() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001744 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang56a03a02018-09-07 12:02:16 +08001745 return true;
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001746 }
1747
1748 @Override
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001749 public NetworkStats getNetworkStatsUidDetail(int uid, String[] ifaces) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001750 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001751 try {
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001752 return mStatsFactory.readNetworkStatsDetail(uid, ifaces, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001753 } catch (IOException e) {
1754 throw new IllegalStateException(e);
1755 }
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001756 }
1757
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001758 private class NetdTetheringStatsProvider extends ITetheringStatsProvider.Stub {
1759 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001760 public NetworkStats getTetherStats(int how) {
1761 // We only need to return per-UID stats. Per-device stats are already counted by
1762 // interface counters.
1763 if (how != STATS_PER_UID) {
1764 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
1765 }
1766
Luke Huang13b79e82018-09-26 14:53:42 +08001767 final TetherStatsParcel[] tetherStatsVec;
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001768 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001769 tetherStatsVec = mNetdService.tetherGetStats();
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001770 } catch (RemoteException | ServiceSpecificException e) {
1771 throw new IllegalStateException("problem parsing tethering stats: ", e);
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001772 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001773
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001774 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(),
Luke Huang13b79e82018-09-26 14:53:42 +08001775 tetherStatsVec.length);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001776 final NetworkStats.Entry entry = new NetworkStats.Entry();
1777
Luke Huang13b79e82018-09-26 14:53:42 +08001778 for (TetherStatsParcel tetherStats : tetherStatsVec) {
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001779 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001780 entry.iface = tetherStats.iface;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001781 entry.uid = UID_TETHERING;
1782 entry.set = SET_DEFAULT;
1783 entry.tag = TAG_NONE;
Luke Huang13b79e82018-09-26 14:53:42 +08001784 entry.rxBytes = tetherStats.rxBytes;
1785 entry.rxPackets = tetherStats.rxPackets;
1786 entry.txBytes = tetherStats.txBytes;
1787 entry.txPackets = tetherStats.txPackets;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001788 stats.combineValues(entry);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001789 } catch (ArrayIndexOutOfBoundsException e) {
Luke Huang13b79e82018-09-26 14:53:42 +08001790 throw new IllegalStateException("invalid tethering stats " + e);
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001791 }
1792 }
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001793
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001794 return stats;
1795 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001796
1797 @Override
1798 public void setInterfaceQuota(String iface, long quotaBytes) {
1799 // Do nothing. netd is already informed of quota changes in setInterfaceQuota.
1800 }
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001801 }
1802
1803 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001804 public NetworkStats getNetworkStatsTethering(int how) {
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001805 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1806
1807 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1808 synchronized (mTetheringStatsProviders) {
1809 for (ITetheringStatsProvider provider: mTetheringStatsProviders.keySet()) {
1810 try {
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001811 stats.combineAllValues(provider.getTetherStats(how));
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001812 } catch (RemoteException e) {
1813 Log.e(TAG, "Problem reading tethering stats from " +
1814 mTetheringStatsProviders.get(provider) + ": " + e);
1815 }
1816 }
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001817 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001818 return stats;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001819 }
1820
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001821 @Override
Erik Kline1742fe12017-12-13 19:40:49 +09001822 public void setDnsConfigurationForNetwork(int netId, String[] servers, String[] domains,
Erik Klinee5dac902018-03-04 21:01:01 +09001823 int[] params, String tlsHostname, String[] tlsServers) {
Pierre Imai8e48e672016-04-21 13:30:43 +09001824 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1825
Ben Schwartz6ec28df2017-10-02 13:08:06 -04001826 final String[] tlsFingerprints = new String[0];
Pierre Imai8e48e672016-04-21 13:30:43 +09001827 try {
Erik Kline1742fe12017-12-13 19:40:49 +09001828 mNetdService.setResolverConfiguration(
Erik Klinee5dac902018-03-04 21:01:01 +09001829 netId, servers, domains, params, tlsHostname, tlsServers, tlsFingerprints);
Pierre Imai8e48e672016-04-21 13:30:43 +09001830 } catch (RemoteException e) {
1831 throw new RuntimeException(e);
1832 }
1833 }
1834
1835 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001836 public void addVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001837 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001838
1839 try {
1840 mNetdService.networkAddUidRanges(netId, ranges);
1841 } catch (RemoteException | ServiceSpecificException e) {
1842 throw new IllegalStateException(e);
Chad Brubaker3277620a2013-06-12 13:37:30 -07001843 }
1844 }
1845
1846 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001847 public void removeVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001848 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001849 try {
1850 mNetdService.networkRemoveUidRanges(netId, ranges);
1851 } catch (RemoteException | ServiceSpecificException e) {
1852 throw new IllegalStateException(e);
Chad Brubakercca54c42013-06-27 17:41:38 -07001853 }
1854 }
1855
1856 @Override
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001857 public void setFirewallEnabled(boolean enabled) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001858 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001859 try {
Luke Huanga241db92018-07-31 20:15:24 +08001860 mNetdService.firewallSetFirewallType(
1861 enabled ? INetd.FIREWALL_WHITELIST : INetd.FIREWALL_BLACKLIST);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001862 mFirewallEnabled = enabled;
Luke Huanga241db92018-07-31 20:15:24 +08001863 } catch (RemoteException | ServiceSpecificException e) {
1864 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001865 }
1866 }
1867
1868 @Override
1869 public boolean isFirewallEnabled() {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001870 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001871 return mFirewallEnabled;
1872 }
1873
1874 @Override
Jeff Sharkey2c092982012-08-24 11:44:40 -07001875 public void setFirewallInterfaceRule(String iface, boolean allow) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001876 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001877 Preconditions.checkState(mFirewallEnabled);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001878 try {
Luke Huanga241db92018-07-31 20:15:24 +08001879 mNetdService.firewallSetInterfaceRule(iface,
1880 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
1881 } catch (RemoteException | ServiceSpecificException e) {
1882 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001883 }
1884 }
1885
Lorenzo Colitti3fef7232016-04-29 18:00:03 +09001886 private void closeSocketsForFirewallChainLocked(int chain, String chainName) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001887 // UID ranges to close sockets on.
1888 UidRange[] ranges;
1889 // UID ranges whose sockets we won't touch.
1890 int[] exemptUids;
1891
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001892 int numUids = 0;
Luke Huanga241db92018-07-31 20:15:24 +08001893 if (DBG) Slog.d(TAG, "Closing sockets after enabling chain " + chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001894 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
1895 // Close all sockets on all non-system UIDs...
1896 ranges = new UidRange[] {
1897 // TODO: is there a better way of finding all existing users? If so, we could
1898 // specify their ranges here.
1899 new UidRange(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE),
1900 };
1901 // ... except for the UIDs that have allow rules.
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001902 synchronized (mRulesLock) {
1903 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1904 exemptUids = new int[rules.size()];
1905 for (int i = 0; i < exemptUids.length; i++) {
1906 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
1907 exemptUids[numUids] = rules.keyAt(i);
1908 numUids++;
1909 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001910 }
1911 }
1912 // Normally, whitelist chains only contain deny rules, so numUids == exemptUids.length.
1913 // But the code does not guarantee this in any way, and at least in one case - if we add
1914 // a UID rule to the firewall, and then disable the firewall - the chains can contain
1915 // the wrong type of rule. In this case, don't close connections that we shouldn't.
1916 //
1917 // TODO: tighten up this code by ensuring we never set the wrong type of rule, and
1918 // fix setFirewallEnabled to grab mQuotaLock and clear rules.
1919 if (numUids != exemptUids.length) {
1920 exemptUids = Arrays.copyOf(exemptUids, numUids);
1921 }
1922 } else {
1923 // Close sockets for every UID that has a deny rule...
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001924 synchronized (mRulesLock) {
1925 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1926 ranges = new UidRange[rules.size()];
1927 for (int i = 0; i < ranges.length; i++) {
1928 if (rules.valueAt(i) == NetworkPolicyManager.FIREWALL_RULE_DENY) {
1929 int uid = rules.keyAt(i);
1930 ranges[numUids] = new UidRange(uid, uid);
1931 numUids++;
1932 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001933 }
1934 }
1935 // As above; usually numUids == ranges.length, but not always.
1936 if (numUids != ranges.length) {
1937 ranges = Arrays.copyOf(ranges, numUids);
1938 }
1939 // ... with no exceptions.
1940 exemptUids = new int[0];
1941 }
1942
1943 try {
1944 mNetdService.socketDestroy(ranges, exemptUids);
1945 } catch(RemoteException | ServiceSpecificException e) {
1946 Slog.e(TAG, "Error closing sockets after enabling chain " + chainName + ": " + e);
1947 }
1948 }
1949
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001950 @Override
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001951 public void setFirewallChainEnabled(int chain, boolean enable) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001952 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001953 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001954 synchronized (mRulesLock) {
1955 if (getFirewallChainState(chain) == enable) {
1956 // All is the same, nothing to do. This relies on the fact that netd has child
1957 // chains default detached.
1958 return;
1959 }
1960 setFirewallChainState(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001961 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001962
Luke Huang615e1022018-10-25 11:54:05 +09001963 final String chainName = getFirewallChainName(chain);
Luke Huanga241db92018-07-31 20:15:24 +08001964 if (chain == FIREWALL_CHAIN_NONE) {
Luke Huang615e1022018-10-25 11:54:05 +09001965 throw new IllegalArgumentException("Bad child chain: " + chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001966 }
1967
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001968 try {
Luke Huanga241db92018-07-31 20:15:24 +08001969 mNetdService.firewallEnableChildChain(chain, enable);
1970 } catch (RemoteException | ServiceSpecificException e) {
1971 throw new IllegalStateException(e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001972 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001973
1974 // Close any sockets that were opened by the affected UIDs. This has to be done after
1975 // disabling network connectivity, in case they react to the socket close by reopening
1976 // the connection and race with the iptables commands that enable the firewall. All
1977 // whitelist and blacklist chains allow RSTs through.
1978 if (enable) {
Luke Huang615e1022018-10-25 11:54:05 +09001979 closeSocketsForFirewallChainLocked(chain, chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001980 }
Amith Yamasani15e472352015-04-24 19:06:07 -07001981 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001982 }
1983
Luke Huanga241db92018-07-31 20:15:24 +08001984 private String getFirewallChainName(int chain) {
1985 switch (chain) {
1986 case FIREWALL_CHAIN_STANDBY:
1987 return FIREWALL_CHAIN_NAME_STANDBY;
1988 case FIREWALL_CHAIN_DOZABLE:
1989 return FIREWALL_CHAIN_NAME_DOZABLE;
1990 case FIREWALL_CHAIN_POWERSAVE:
1991 return FIREWALL_CHAIN_NAME_POWERSAVE;
1992 default:
1993 throw new IllegalArgumentException("Bad child chain: " + chain);
1994 }
1995 }
1996
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001997 private int getFirewallType(int chain) {
1998 switch (chain) {
1999 case FIREWALL_CHAIN_STANDBY:
2000 return FIREWALL_TYPE_BLACKLIST;
2001 case FIREWALL_CHAIN_DOZABLE:
2002 return FIREWALL_TYPE_WHITELIST;
Felipe Leme011b98f2016-02-10 17:28:31 -08002003 case FIREWALL_CHAIN_POWERSAVE:
2004 return FIREWALL_TYPE_WHITELIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002005 default:
2006 return isFirewallEnabled() ? FIREWALL_TYPE_WHITELIST : FIREWALL_TYPE_BLACKLIST;
2007 }
2008 }
2009
2010 @Override
2011 public void setFirewallUidRules(int chain, int[] uids, int[] rules) {
2012 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002013 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002014 synchronized (mRulesLock) {
2015 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
2016 SparseIntArray newRules = new SparseIntArray();
2017 // apply new set of rules
2018 for (int index = uids.length - 1; index >= 0; --index) {
2019 int uid = uids[index];
2020 int rule = rules[index];
2021 updateFirewallUidRuleLocked(chain, uid, rule);
2022 newRules.put(uid, rule);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002023 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002024 // collect the rules to remove.
2025 SparseIntArray rulesToRemove = new SparseIntArray();
2026 for (int index = uidFirewallRules.size() - 1; index >= 0; --index) {
2027 int uid = uidFirewallRules.keyAt(index);
2028 if (newRules.indexOfKey(uid) < 0) {
2029 rulesToRemove.put(uid, FIREWALL_RULE_DEFAULT);
2030 }
2031 }
2032 // remove dead rules
2033 for (int index = rulesToRemove.size() - 1; index >= 0; --index) {
2034 int uid = rulesToRemove.keyAt(index);
2035 updateFirewallUidRuleLocked(chain, uid, FIREWALL_RULE_DEFAULT);
2036 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002037 }
2038 try {
2039 switch (chain) {
2040 case FIREWALL_CHAIN_DOZABLE:
2041 mNetdService.firewallReplaceUidChain("fw_dozable", true, uids);
2042 break;
2043 case FIREWALL_CHAIN_STANDBY:
2044 mNetdService.firewallReplaceUidChain("fw_standby", false, uids);
2045 break;
2046 case FIREWALL_CHAIN_POWERSAVE:
2047 mNetdService.firewallReplaceUidChain("fw_powersave", true, uids);
2048 break;
2049 case FIREWALL_CHAIN_NONE:
2050 default:
2051 Slog.d(TAG, "setFirewallUidRules() called on invalid chain: " + chain);
2052 }
2053 } catch (RemoteException e) {
2054 Slog.w(TAG, "Error flushing firewall chain " + chain, e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002055 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002056 }
2057 }
2058
2059 @Override
2060 public void setFirewallUidRule(int chain, int uid, int rule) {
2061 enforceSystemUid();
Felipe Lemea701cad2016-05-12 09:58:14 -07002062 synchronized (mQuotaLock) {
2063 setFirewallUidRuleLocked(chain, uid, rule);
2064 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002065 }
2066
Felipe Lemea701cad2016-05-12 09:58:14 -07002067 private void setFirewallUidRuleLocked(int chain, int uid, int rule) {
2068 if (updateFirewallUidRuleLocked(chain, uid, rule)) {
Luke Huanga241db92018-07-31 20:15:24 +08002069 final int ruleType = getFirewallRuleType(chain, rule);
Amith Yamasani15e472352015-04-24 19:06:07 -07002070 try {
Luke Huanga241db92018-07-31 20:15:24 +08002071 mNetdService.firewallSetUidRule(chain, uid, ruleType);
2072 } catch (RemoteException | ServiceSpecificException e) {
2073 throw new IllegalStateException(e);
Amith Yamasani15e472352015-04-24 19:06:07 -07002074 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002075 }
2076 }
2077
Felipe Lemea701cad2016-05-12 09:58:14 -07002078 // TODO: now that netd supports batching, NMS should not keep these data structures anymore...
2079 private boolean updateFirewallUidRuleLocked(int chain, int uid, int rule) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002080 synchronized (mRulesLock) {
2081 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Felipe Lemea701cad2016-05-12 09:58:14 -07002082
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002083 final int oldUidFirewallRule = uidFirewallRules.get(uid, FIREWALL_RULE_DEFAULT);
2084 if (DBG) {
2085 Slog.d(TAG, "oldRule = " + oldUidFirewallRule
2086 + ", newRule=" + rule + " for uid=" + uid + " on chain " + chain);
2087 }
2088 if (oldUidFirewallRule == rule) {
2089 if (DBG) Slog.d(TAG, "!!!!! Skipping change");
2090 // TODO: eventually consider throwing
2091 return false;
2092 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002093
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002094 String ruleName = getFirewallRuleName(chain, rule);
2095 String oldRuleName = getFirewallRuleName(chain, oldUidFirewallRule);
Felipe Lemea701cad2016-05-12 09:58:14 -07002096
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002097 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
2098 uidFirewallRules.delete(uid);
2099 } else {
2100 uidFirewallRules.put(uid, rule);
2101 }
2102 return !ruleName.equals(oldRuleName);
Felipe Lemea701cad2016-05-12 09:58:14 -07002103 }
Felipe Lemea701cad2016-05-12 09:58:14 -07002104 }
2105
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002106 private @NonNull String getFirewallRuleName(int chain, int rule) {
2107 String ruleName;
2108 if (getFirewallType(chain) == FIREWALL_TYPE_WHITELIST) {
2109 if (rule == NetworkPolicyManager.FIREWALL_RULE_ALLOW) {
2110 ruleName = "allow";
2111 } else {
2112 ruleName = "deny";
2113 }
2114 } else { // Blacklist mode
2115 if (rule == NetworkPolicyManager.FIREWALL_RULE_DENY) {
2116 ruleName = "deny";
2117 } else {
2118 ruleName = "allow";
2119 }
2120 }
2121 return ruleName;
2122 }
2123
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002124 @GuardedBy("mRulesLock")
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002125 private @NonNull SparseIntArray getUidFirewallRulesLR(int chain) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002126 switch (chain) {
2127 case FIREWALL_CHAIN_STANDBY:
2128 return mUidFirewallStandbyRules;
2129 case FIREWALL_CHAIN_DOZABLE:
2130 return mUidFirewallDozableRules;
Felipe Leme011b98f2016-02-10 17:28:31 -08002131 case FIREWALL_CHAIN_POWERSAVE:
2132 return mUidFirewallPowerSaveRules;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002133 case FIREWALL_CHAIN_NONE:
2134 return mUidFirewallRules;
2135 default:
2136 throw new IllegalArgumentException("Unknown chain:" + chain);
2137 }
2138 }
2139
Luke Huanga241db92018-07-31 20:15:24 +08002140 private int getFirewallRuleType(int chain, int rule) {
Luke Huang615e1022018-10-25 11:54:05 +09002141 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
2142 return getFirewallType(chain) == FIREWALL_TYPE_WHITELIST
2143 ? INetd.FIREWALL_RULE_DENY : INetd.FIREWALL_RULE_ALLOW;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002144 }
Luke Huang615e1022018-10-25 11:54:05 +09002145 return rule;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002146 }
2147
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07002148 private static void enforceSystemUid() {
2149 final int uid = Binder.getCallingUid();
2150 if (uid != Process.SYSTEM_UID) {
2151 throw new SecurityException("Only available to AID_SYSTEM");
2152 }
2153 }
2154
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002155 @Override
Lorenzo Colitti79751842013-02-28 16:16:03 +09002156 public void startClatd(String interfaceName) throws IllegalStateException {
2157 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2158
2159 try {
Luke Huang69369f32018-08-02 15:51:41 +08002160 mNetdService.clatdStart(interfaceName);
2161 } catch (RemoteException | ServiceSpecificException e) {
2162 throw new IllegalStateException(e);
Lorenzo Colitti79751842013-02-28 16:16:03 +09002163 }
2164 }
2165
2166 @Override
Lorenzo Colitti95439462014-10-09 13:44:48 +09002167 public void stopClatd(String interfaceName) throws IllegalStateException {
Lorenzo Colitti79751842013-02-28 16:16:03 +09002168 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2169
2170 try {
Luke Huang69369f32018-08-02 15:51:41 +08002171 mNetdService.clatdStop(interfaceName);
2172 } catch (RemoteException | ServiceSpecificException e) {
2173 throw new IllegalStateException(e);
Lorenzo Colitti79751842013-02-28 16:16:03 +09002174 }
2175 }
2176
2177 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002178 public void registerNetworkActivityListener(INetworkActivityListener listener) {
2179 mNetworkActivityListeners.register(listener);
2180 }
2181
2182 @Override
2183 public void unregisterNetworkActivityListener(INetworkActivityListener listener) {
2184 mNetworkActivityListeners.unregister(listener);
2185 }
2186
2187 @Override
2188 public boolean isNetworkActive() {
2189 synchronized (mNetworkActivityListeners) {
2190 return mNetworkActive || mActiveIdleTimers.isEmpty();
2191 }
2192 }
2193
2194 private void reportNetworkActive() {
2195 final int length = mNetworkActivityListeners.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002196 try {
2197 for (int i = 0; i < length; i++) {
2198 try {
2199 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
Felipe Leme03e689d2016-03-02 16:17:38 -08002200 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002201 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002202 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07002203 } finally {
2204 mNetworkActivityListeners.finishBroadcast();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002205 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002206 }
2207
Mattias Falk8b47b362011-08-23 14:15:13 +02002208 /** {@inheritDoc} */
Jeff Sharkey7b4596f2013-02-25 10:55:29 -08002209 @Override
Jeff Sharkeyfa23c5a2011-08-09 21:44:24 -07002210 public void monitor() {
2211 if (mConnector != null) {
2212 mConnector.monitor();
2213 }
2214 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002215
2216 @Override
2217 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002218 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002219
Robert Greenwalt470fd722012-01-18 12:51:15 -08002220 pw.println("NetworkManagementService NativeDaemonConnector Log:");
2221 mConnector.dump(fd, pw, args);
2222 pw.println();
2223
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07002224 pw.print("mMobileActivityFromRadio="); pw.print(mMobileActivityFromRadio);
2225 pw.print(" mLastPowerStateFromRadio="); pw.println(mLastPowerStateFromRadio);
2226 pw.print("mNetworkActive="); pw.println(mNetworkActive);
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002227
2228 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07002229 pw.print("Active quota ifaces: "); pw.println(mActiveQuotas.toString());
2230 pw.print("Active alert ifaces: "); pw.println(mActiveAlerts.toString());
Felipe Leme65be3022016-03-22 14:53:13 -07002231 pw.print("Data saver mode: "); pw.println(mDataSaverMode);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002232 synchronized (mRulesLock) {
2233 dumpUidRuleOnQuotaLocked(pw, "blacklist", mUidRejectOnMetered);
2234 dumpUidRuleOnQuotaLocked(pw, "whitelist", mUidAllowOnMetered);
2235 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002236 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002237
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002238 synchronized (mRulesLock) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002239 dumpUidFirewallRule(pw, "", mUidFirewallRules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002240
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002241 pw.print("UID firewall standby chain enabled: "); pw.println(
2242 getFirewallChainState(FIREWALL_CHAIN_STANDBY));
Felipe Leme011b98f2016-02-10 17:28:31 -08002243 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_STANDBY, mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002244
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002245 pw.print("UID firewall dozable chain enabled: "); pw.println(
2246 getFirewallChainState(FIREWALL_CHAIN_DOZABLE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002247 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_DOZABLE, mUidFirewallDozableRules);
Felipe Leme011b98f2016-02-10 17:28:31 -08002248
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002249 pw.println("UID firewall powersave chain enabled: " +
2250 getFirewallChainState(FIREWALL_CHAIN_POWERSAVE));
Felipe Leme011b98f2016-02-10 17:28:31 -08002251 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_POWERSAVE, mUidFirewallPowerSaveRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002252 }
2253
Dianne Hackborn77b987f2014-02-26 16:20:52 -08002254 synchronized (mIdleTimerLock) {
2255 pw.println("Idle timers:");
2256 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
2257 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
2258 IdleTimerParams params = ent.getValue();
2259 pw.print(" timeout="); pw.print(params.timeout);
2260 pw.print(" type="); pw.print(params.type);
2261 pw.print(" networkCount="); pw.println(params.networkCount);
2262 }
2263 }
2264
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002265 pw.print("Firewall enabled: "); pw.println(mFirewallEnabled);
Felipe Leme65be3022016-03-22 14:53:13 -07002266 pw.print("Netd service status: " );
2267 if (mNetdService == null) {
2268 pw.println("disconnected");
2269 } else {
2270 try {
2271 final boolean alive = mNetdService.isAlive();
2272 pw.println(alive ? "alive": "dead");
2273 } catch (RemoteException e) {
2274 pw.println("unreachable");
2275 }
2276 }
2277 }
2278
2279 private void dumpUidRuleOnQuotaLocked(PrintWriter pw, String name, SparseBooleanArray list) {
2280 pw.print("UID bandwith control ");
2281 pw.print(name);
2282 pw.print(" rule: [");
2283 final int size = list.size();
2284 for (int i = 0; i < size; i++) {
2285 pw.print(list.keyAt(i));
2286 if (i < size - 1) pw.print(",");
2287 }
2288 pw.println("]");
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002289 }
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002290
Felipe Leme011b98f2016-02-10 17:28:31 -08002291 private void dumpUidFirewallRule(PrintWriter pw, String name, SparseIntArray rules) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002292 pw.print("UID firewall ");
Felipe Leme011b98f2016-02-10 17:28:31 -08002293 pw.print(name);
2294 pw.print(" rule: [");
2295 final int size = rules.size();
2296 for (int i = 0; i < size; i++) {
2297 pw.print(rules.keyAt(i));
2298 pw.print(":");
2299 pw.print(rules.valueAt(i));
2300 if (i < size - 1) pw.print(",");
2301 }
2302 pw.println("]");
2303 }
2304
Robert Greenwalt568891d2014-04-04 13:38:00 -07002305 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002306 public void createPhysicalNetwork(int netId, int permission) {
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002307 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2308
2309 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002310 mNetdService.networkCreatePhysical(netId, permission);
2311 } catch (RemoteException | ServiceSpecificException e) {
2312 throw new IllegalStateException(e);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002313 }
2314 }
2315
Robert Greenwalt568891d2014-04-04 13:38:00 -07002316 @Override
ckenbed368e2018-12-05 20:32:30 +09002317 public void createVirtualNetwork(int netId, boolean secure) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002318 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2319
2320 try {
ckenbed368e2018-12-05 20:32:30 +09002321 mNetdService.networkCreateVpn(netId, secure);
Luke Huang8a462ec2018-08-24 20:33:16 +08002322 } catch (RemoteException | ServiceSpecificException e) {
2323 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002324 }
2325 }
2326
2327 @Override
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002328 public void removeNetwork(int netId) {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002329 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002330
2331 try {
Erik Kline33d8e5c2018-01-15 17:05:07 +09002332 mNetdService.networkDestroy(netId);
2333 } catch (ServiceSpecificException e) {
2334 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2335 throw e;
2336 } catch (RemoteException e) {
2337 Log.w(TAG, "removeNetwork(" + netId + "): ", e);
2338 throw e.rethrowAsRuntimeException();
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002339 }
2340 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002341
2342 @Override
Paul Jensen992f2522014-04-28 10:33:11 -04002343 public void addInterfaceToNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002344 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, netId, iface);
Paul Jensen992f2522014-04-28 10:33:11 -04002345 }
2346
2347 @Override
2348 public void removeInterfaceFromNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002349 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, netId, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002350 }
Paul Jensen992f2522014-04-28 10:33:11 -04002351
Luke Huang8a462ec2018-08-24 20:33:16 +08002352 private void modifyInterfaceInNetwork(boolean add, int netId, String iface) {
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002353 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Paul Jensen992f2522014-04-28 10:33:11 -04002354 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002355 if (add) {
2356 mNetdService.networkAddInterface(netId, iface);
2357 } else {
2358 mNetdService.networkRemoveInterface(netId, iface);
2359 }
2360 } catch (RemoteException | ServiceSpecificException e) {
2361 throw new IllegalStateException(e);
Paul Jensen992f2522014-04-28 10:33:11 -04002362 }
2363 }
2364
2365 @Override
Robert Greenwalt913c8952014-04-07 17:36:35 -07002366 public void addLegacyRouteForNetId(int netId, RouteInfo routeInfo, int uid) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002367 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2368
Sreeram Ramachandrancc91c7b2014-06-03 18:41:43 -07002369 final LinkAddress la = routeInfo.getDestinationLinkAddress();
Luke Huang8a462ec2018-08-24 20:33:16 +08002370 final String ifName = routeInfo.getInterface();
2371 final String dst = la.toString();
2372 final String nextHop;
Robert Greenwalt568891d2014-04-04 13:38:00 -07002373
Luke Huang8a462ec2018-08-24 20:33:16 +08002374 if (routeInfo.hasGateway()) {
2375 nextHop = routeInfo.getGateway().getHostAddress();
2376 } else {
2377 nextHop = "";
2378 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002379 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002380 mNetdService.networkAddLegacyRoute(netId, ifName, dst, nextHop, uid);
2381 } catch (RemoteException | ServiceSpecificException e) {
2382 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002383 }
2384 }
2385
2386 @Override
Sreeram Ramachandranf047f2a2014-04-15 16:04:26 -07002387 public void setDefaultNetId(int netId) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002388 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2389
2390 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002391 mNetdService.networkSetDefault(netId);
2392 } catch (RemoteException | ServiceSpecificException e) {
2393 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002394 }
2395 }
2396
2397 @Override
2398 public void clearDefaultNetId() {
2399 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2400
2401 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002402 mNetdService.networkClearDefault();
2403 } catch (RemoteException | ServiceSpecificException e) {
2404 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002405 }
2406 }
2407
2408 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002409 public void setNetworkPermission(int netId, int permission) {
Paul Jensen487ffe72015-07-24 15:57:11 -04002410 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2411
2412 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002413 mNetdService.networkSetPermissionForNetwork(netId, permission);
2414 } catch (RemoteException | ServiceSpecificException e) {
2415 throw new IllegalStateException(e);
Paul Jensen487ffe72015-07-24 15:57:11 -04002416 }
2417 }
2418
Luke Huang8a462ec2018-08-24 20:33:16 +08002419 private int parsePermission(String permission) {
2420 if (permission.equals("NETWORK")) {
2421 return INetd.PERMISSION_NETWORK;
2422 }
2423 if (permission.equals("SYSTEM")) {
2424 return INetd.PERMISSION_SYSTEM;
2425 }
2426 return INetd.PERMISSION_NONE;
2427 }
Paul Jensen487ffe72015-07-24 15:57:11 -04002428
2429 @Override
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002430 public void setPermission(String permission, int[] uids) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002431 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2432
Luke Huang8a462ec2018-08-24 20:33:16 +08002433 try {
2434 mNetdService.networkSetPermissionForUser(parsePermission(permission), uids);
2435 } catch (RemoteException | ServiceSpecificException e) {
2436 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002437 }
2438 }
2439
2440 @Override
2441 public void clearPermission(int[] uids) {
2442 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2443
Luke Huang8a462ec2018-08-24 20:33:16 +08002444 try {
2445 mNetdService.networkClearPermissionForUser(uids);
2446 } catch (RemoteException | ServiceSpecificException e) {
2447 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002448 }
2449 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002450
2451 @Override
2452 public void allowProtect(int uid) {
2453 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2454
2455 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002456 mNetdService.networkSetProtectAllow(uid);
2457 } catch (RemoteException | ServiceSpecificException e) {
2458 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002459 }
2460 }
2461
2462 @Override
2463 public void denyProtect(int uid) {
2464 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2465
2466 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002467 mNetdService.networkSetProtectDeny(uid);
2468 } catch (RemoteException | ServiceSpecificException e) {
2469 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002470 }
2471 }
2472
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002473 @Override
2474 public void addInterfaceToLocalNetwork(String iface, List<RouteInfo> routes) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002475 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002476
2477 for (RouteInfo route : routes) {
2478 if (!route.isDefaultRoute()) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002479 modifyRoute(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID, route);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002480 }
2481 }
2482 }
2483
2484 @Override
2485 public void removeInterfaceFromLocalNetwork(String iface) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002486 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, INetd.LOCAL_NET_ID, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002487 }
Erik Kline6599ee82016-07-17 21:28:39 +09002488
2489 @Override
2490 public int removeRoutesFromLocalNetwork(List<RouteInfo> routes) {
2491 int failures = 0;
2492
2493 for (RouteInfo route : routes) {
2494 try {
Luke Huang706d7ab2018-10-16 15:42:15 +08002495 modifyRoute(MODIFY_OPERATION_REMOVE, INetd.LOCAL_NET_ID, route);
Erik Kline6599ee82016-07-17 21:28:39 +09002496 } catch (IllegalStateException e) {
2497 failures++;
2498 }
2499 }
2500
2501 return failures;
2502 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002503
Sudheer Shankab8f23162017-08-04 13:30:10 -07002504 @Override
2505 public boolean isNetworkRestricted(int uid) {
2506 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2507 return isNetworkRestrictedInternal(uid);
2508 }
2509
2510 private boolean isNetworkRestrictedInternal(int uid) {
2511 synchronized (mRulesLock) {
2512 if (getFirewallChainState(FIREWALL_CHAIN_STANDBY)
2513 && mUidFirewallStandbyRules.get(uid) == FIREWALL_RULE_DENY) {
2514 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of app standby mode");
2515 return true;
2516 }
2517 if (getFirewallChainState(FIREWALL_CHAIN_DOZABLE)
2518 && mUidFirewallDozableRules.get(uid) != FIREWALL_RULE_ALLOW) {
2519 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of device idle mode");
2520 return true;
2521 }
2522 if (getFirewallChainState(FIREWALL_CHAIN_POWERSAVE)
2523 && mUidFirewallPowerSaveRules.get(uid) != FIREWALL_RULE_ALLOW) {
2524 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of power saver mode");
2525 return true;
2526 }
2527 if (mUidRejectOnMetered.get(uid)) {
2528 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of no metered data"
2529 + " in the background");
2530 return true;
2531 }
2532 if (mDataSaverMode && !mUidAllowOnMetered.get(uid)) {
2533 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of data saver mode");
2534 return true;
2535 }
2536 return false;
2537 }
2538 }
2539
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002540 private void setFirewallChainState(int chain, boolean state) {
2541 synchronized (mRulesLock) {
2542 mFirewallChainStates.put(chain, state);
2543 }
2544 }
2545
2546 private boolean getFirewallChainState(int chain) {
2547 synchronized (mRulesLock) {
2548 return mFirewallChainStates.get(chain);
2549 }
2550 }
2551
2552 @VisibleForTesting
2553 class LocalService extends NetworkManagementInternal {
2554 @Override
2555 public boolean isNetworkRestrictedForUid(int uid) {
Sudheer Shankab8f23162017-08-04 13:30:10 -07002556 return isNetworkRestrictedInternal(uid);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002557 }
2558 }
2559
2560 @VisibleForTesting
2561 Injector getInjector() {
2562 return new Injector();
2563 }
2564
2565 @VisibleForTesting
2566 class Injector {
2567 void setDataSaverMode(boolean dataSaverMode) {
2568 mDataSaverMode = dataSaverMode;
2569 }
2570
2571 void setFirewallChainState(int chain, boolean state) {
2572 NetworkManagementService.this.setFirewallChainState(chain, state);
2573 }
2574
2575 void setFirewallRule(int chain, int uid, int rule) {
2576 synchronized (mRulesLock) {
2577 getUidFirewallRulesLR(chain).put(uid, rule);
2578 }
2579 }
2580
2581 void setUidOnMeteredNetworkList(boolean blacklist, int uid, boolean enable) {
2582 synchronized (mRulesLock) {
2583 if (blacklist) {
2584 mUidRejectOnMetered.put(uid, enable);
2585 } else {
2586 mUidAllowOnMetered.put(uid, enable);
2587 }
2588 }
2589 }
2590
2591 void reset() {
2592 synchronized (mRulesLock) {
2593 setDataSaverMode(false);
2594 final int[] chains = {
2595 FIREWALL_CHAIN_DOZABLE,
2596 FIREWALL_CHAIN_STANDBY,
2597 FIREWALL_CHAIN_POWERSAVE
2598 };
2599 for (int chain : chains) {
2600 setFirewallChainState(chain, false);
2601 getUidFirewallRulesLR(chain).clear();
2602 }
2603 mUidAllowOnMetered.clear();
2604 mUidRejectOnMetered.clear();
2605 }
2606 }
2607 }
San Mehat873f2142010-01-14 10:25:07 -08002608}