blob: 1ff50b240672e0a5899e545ba6197487da2c2e0b [file] [log] [blame]
San Mehat873f2142010-01-14 10:25:07 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey4529bb62011-12-14 10:31:54 -080019import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Sehee Parka9139bc2017-12-22 13:54:05 +090020import static android.Manifest.permission.NETWORK_SETTINGS;
Lorenzo Colitti07f13042017-07-10 19:06:57 +090021import static android.Manifest.permission.NETWORK_STACK;
Jeff Sharkeyaf75c332011-11-18 12:41:12 -080022import static android.Manifest.permission.SHUTDOWN;
Remi NGUYEN VANdacee142019-02-13 18:28:35 +090023import static android.net.INetd.FIREWALL_BLACKLIST;
24import static android.net.INetd.FIREWALL_CHAIN_DOZABLE;
25import static android.net.INetd.FIREWALL_CHAIN_NONE;
26import static android.net.INetd.FIREWALL_CHAIN_POWERSAVE;
27import static android.net.INetd.FIREWALL_CHAIN_STANDBY;
28import static android.net.INetd.FIREWALL_RULE_ALLOW;
29import static android.net.INetd.FIREWALL_RULE_DENY;
30import static android.net.INetd.FIREWALL_WHITELIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070031import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080032import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070033import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_NAME_STANDBY;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070034import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -070035import static android.net.NetworkStats.SET_DEFAULT;
Lorenzo Colittif1912ca2017-08-17 19:23:08 +090036import static android.net.NetworkStats.STATS_PER_UID;
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -080037import static android.net.NetworkStats.TAG_ALL;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070038import static android.net.NetworkStats.TAG_NONE;
39import static android.net.NetworkStats.UID_ALL;
Jeff Sharkeyae2c1812011-10-04 13:11:40 -070040import static android.net.TrafficStats.UID_TETHERING;
Lorenzo Colitti9307ca22019-01-12 01:54:23 +090041
Jeff Sharkeya63ba592011-07-19 23:47:12 -070042import static com.android.server.NetworkManagementSocketTagger.PROP_QTAGUID_ENABLED;
Erik Klineb2cfdfb2017-01-18 20:54:14 +090043
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070044import android.annotation.NonNull;
Sudheer Shankadc589ac2016-11-10 15:30:17 -080045import android.app.ActivityManager;
San Mehat873f2142010-01-14 10:25:07 -080046import android.content.Context;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080047import android.net.ConnectivityManager;
Lorenzo Colitti58967ba2016-02-02 17:21:21 +090048import android.net.INetd;
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +000049import android.net.INetdUnsolicitedEventListener;
San Mehat4d02d002010-01-22 16:07:46 -080050import android.net.INetworkManagementEventObserver;
Lorenzo Colitti07f13042017-07-10 19:06:57 +090051import android.net.ITetheringStatsProvider;
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +000052import android.net.InetAddresses;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070053import android.net.InterfaceConfiguration;
Luke Huang14f75442018-08-15 19:22:54 +080054import android.net.InterfaceConfigurationParcel;
Lorenzo Colittic18cbfd2014-06-13 21:21:03 +090055import android.net.IpPrefix;
Robert Greenwalted126402011-01-28 15:34:55 -080056import android.net.LinkAddress;
Lorenzo Colittib57edc52014-08-22 17:10:50 -070057import android.net.Network;
Amith Yamasani15e472352015-04-24 19:06:07 -070058import android.net.NetworkPolicyManager;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -070059import android.net.NetworkStats;
Robert Greenwalted126402011-01-28 15:34:55 -080060import android.net.NetworkUtils;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070061import android.net.RouteInfo;
Lorenzo Colitti9307ca22019-01-12 01:54:23 +090062import android.net.TetherStatsParcel;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040063import android.net.UidRange;
Lorenzo Colittib90ad242019-03-18 23:50:34 +090064import android.net.UidRangeParcel;
Remi NGUYEN VAN231b52b2019-01-29 15:38:52 +090065import android.net.util.NetdService;
Dianne Hackborn91268cf2013-06-13 19:06:50 -070066import android.os.BatteryStats;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070067import android.os.Binder;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -070068import android.os.Handler;
Lorenzo Colittia0868002017-07-11 02:29:28 +090069import android.os.IBinder;
Dianne Hackborn77b987f2014-02-26 16:20:52 -080070import android.os.INetworkActivityListener;
San Mehat873f2142010-01-14 10:25:07 -080071import android.os.INetworkManagementService;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070072import android.os.Process;
Jeff Sharkey3df273e2011-12-15 15:47:12 -080073import android.os.RemoteCallbackList;
74import android.os.RemoteException;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070075import android.os.ServiceManager;
Lorenzo Colitti4cb42402016-04-24 12:52:00 +090076import android.os.ServiceSpecificException;
Jeff Sharkey605eb792014-11-04 13:34:06 -080077import android.os.StrictMode;
Jeff Sharkey9a13f362011-04-26 16:25:36 -070078import android.os.SystemClock;
Marco Nelissen62dbb222010-02-18 10:56:30 -080079import android.os.SystemProperties;
Felipe Leme29e72ea2016-09-08 13:26:55 -070080import android.os.Trace;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -070081import android.telephony.DataConnectionRealTimeInfo;
Lorenzo Colittib90ad242019-03-18 23:50:34 +090082import android.text.TextUtils;
Irfan Sheriff9ab518ad2010-03-12 15:48:17 -080083import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080084import android.util.Slog;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070085import android.util.SparseBooleanArray;
Jeff Sharkey605eb792014-11-04 13:34:06 -080086import android.util.SparseIntArray;
San Mehat873f2142010-01-14 10:25:07 -080087
Jeff Sharkey605eb792014-11-04 13:34:06 -080088import com.android.internal.annotations.GuardedBy;
Sudheer Shanka62f5c172017-03-17 16:25:55 -070089import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey7a1c3fc2013-06-04 12:29:00 -070090import com.android.internal.app.IBatteryStats;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060091import com.android.internal.util.DumpUtils;
Jeff Sharkey605eb792014-11-04 13:34:06 -080092import com.android.internal.util.HexDump;
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -070093import com.android.internal.util.Preconditions;
Chenbo Fengf2f1f272019-03-01 15:07:24 -080094import com.android.server.net.NetworkStatsFactory;
Lorenzo Colitti9307ca22019-01-12 01:54:23 +090095
Jeff Sharkeyb24a7852012-05-01 15:19:37 -070096import com.google.android.collect.Maps;
Jeff Sharkey4414cea2011-06-24 17:05:24 -070097
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -070098import java.io.BufferedReader;
99import java.io.DataInputStream;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700100import java.io.FileDescriptor;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700101import java.io.FileInputStream;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700102import java.io.IOException;
Jeff Sharkey9a13f362011-04-26 16:25:36 -0700103import java.io.InputStreamReader;
Jeff Sharkey47eb1022011-08-25 17:48:52 -0700104import java.io.PrintWriter;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700105import java.net.InetAddress;
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700106import java.net.InterfaceAddress;
Jeff Sharkeyeedcb952011-05-17 14:55:15 -0700107import java.util.ArrayList;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400108import java.util.Arrays;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700109import java.util.HashMap;
jiaguo1da35f72014-01-09 16:39:59 +0800110import java.util.List;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700111import java.util.Map;
San Mehat873f2142010-01-14 10:25:07 -0800112
113/**
114 * @hide
115 */
Luke Huang909b31a2019-03-16 21:21:16 +0800116public class NetworkManagementService extends INetworkManagementService.Stub {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900117
118 /**
119 * Helper class that encapsulates NetworkManagementService dependencies and makes them
120 * easier to mock in unit tests.
121 */
122 static class SystemServices {
123 public IBinder getService(String name) {
124 return ServiceManager.getService(name);
125 }
126 public void registerLocalService(NetworkManagementInternal nmi) {
127 LocalServices.addService(NetworkManagementInternal.class, nmi);
128 }
129 public INetd getNetd() {
130 return NetdService.get();
131 }
132 }
133
Amith Yamasani15e472352015-04-24 19:06:07 -0700134 private static final String TAG = "NetworkManagement";
135 private static final boolean DBG = Log.isLoggable(TAG, Log.DEBUG);
Kenny Root305bcbf2010-09-03 07:56:38 -0700136
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400137 private static final int MAX_UID_RANGES_PER_COMMAND = 10;
138
Jeff Sharkey8e9992a2011-08-23 18:37:23 -0700139 /**
140 * Name representing {@link #setGlobalAlert(long)} limit when delivered to
141 * {@link INetworkManagementEventObserver#limitReached(String, String)}.
142 */
143 public static final String LIMIT_GLOBAL_ALERT = "globalAlert";
144
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700145 static final int DAEMON_MSG_MOBILE_CONN_REAL_TIME_INFO = 1;
146
Luke Huang8a462ec2018-08-24 20:33:16 +0800147 static final boolean MODIFY_OPERATION_ADD = true;
148 static final boolean MODIFY_OPERATION_REMOVE = false;
149
San Mehat873f2142010-01-14 10:25:07 -0800150 /**
151 * Binder context for this service
152 */
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700153 private final Context mContext;
San Mehat873f2142010-01-14 10:25:07 -0800154
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700155 private final Handler mDaemonHandler;
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700156
Lorenzo Colittia0868002017-07-11 02:29:28 +0900157 private final SystemServices mServices;
158
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900159 private INetd mNetdService;
160
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000161 private final NetdUnsolicitedEventListener mNetdUnsolicitedEventListener;
Luke Huangd290dd52018-09-04 17:08:18 +0800162
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800163 private IBatteryStats mBatteryStats;
164
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000165 private final RemoteCallbackList<INetworkManagementEventObserver> mObservers =
166 new RemoteCallbackList<>();
167
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700168 private final NetworkStatsFactory mStatsFactory = new NetworkStatsFactory();
169
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900170 @GuardedBy("mTetheringStatsProviders")
171 private final HashMap<ITetheringStatsProvider, String>
172 mTetheringStatsProviders = Maps.newHashMap();
173
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700174 /**
175 * If both locks need to be held, then they should be obtained in the order:
176 * first {@link #mQuotaLock} and then {@link #mRulesLock}.
177 */
Andrew Scull45f533c2017-05-19 15:37:20 +0100178 private final Object mQuotaLock = new Object();
Andrew Scull519291f2017-05-23 13:11:03 +0100179 private final Object mRulesLock = new Object();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800180
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700181 /** Set of interfaces with active quotas. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800182 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700183 private HashMap<String, Long> mActiveQuotas = Maps.newHashMap();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700184 /** Set of interfaces with active alerts. */
Jeff Sharkey605eb792014-11-04 13:34:06 -0800185 @GuardedBy("mQuotaLock")
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700186 private HashMap<String, Long> mActiveAlerts = Maps.newHashMap();
Felipe Leme65be3022016-03-22 14:53:13 -0700187 /** Set of UIDs blacklisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700188 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700189 private SparseBooleanArray mUidRejectOnMetered = new SparseBooleanArray();
190 /** Set of UIDs whitelisted on metered networks. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700191 @GuardedBy("mRulesLock")
Felipe Leme65be3022016-03-22 14:53:13 -0700192 private SparseBooleanArray mUidAllowOnMetered = new SparseBooleanArray();
Jeff Sharkey605eb792014-11-04 13:34:06 -0800193 /** Set of UIDs with cleartext penalties. */
194 @GuardedBy("mQuotaLock")
195 private SparseIntArray mUidCleartextPolicy = new SparseIntArray();
Amith Yamasani15e472352015-04-24 19:06:07 -0700196 /** Set of UIDs that are to be blocked/allowed by firewall controller. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700197 @GuardedBy("mRulesLock")
Amith Yamasani15e472352015-04-24 19:06:07 -0700198 private SparseIntArray mUidFirewallRules = new SparseIntArray();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700199 /**
200 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
201 * to application idles.
202 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700203 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700204 private SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
205 /**
206 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
207 * to device idles.
208 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700209 @GuardedBy("mRulesLock")
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700210 private SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800211 /**
212 * Set of UIDs that are to be blocked/allowed by firewall controller. This set of Ids matches
213 * to device on power-save mode.
214 */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700215 @GuardedBy("mRulesLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800216 private SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700217 /** Set of states for the child firewall chains. True if the chain is active. */
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700218 @GuardedBy("mRulesLock")
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700219 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700220
Felipe Leme65be3022016-03-22 14:53:13 -0700221 @GuardedBy("mQuotaLock")
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700222 private volatile boolean mDataSaverMode;
Felipe Leme65be3022016-03-22 14:53:13 -0700223
Andrew Scull45f533c2017-05-19 15:37:20 +0100224 private final Object mIdleTimerLock = new Object();
Haoyu Bai04124232012-06-28 15:26:19 -0700225 /** Set of interfaces with active idle timers. */
226 private static class IdleTimerParams {
227 public final int timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800228 public final int type;
Haoyu Bai04124232012-06-28 15:26:19 -0700229 public int networkCount;
230
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800231 IdleTimerParams(int timeout, int type) {
Haoyu Bai04124232012-06-28 15:26:19 -0700232 this.timeout = timeout;
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800233 this.type = type;
Haoyu Bai04124232012-06-28 15:26:19 -0700234 this.networkCount = 1;
235 }
236 }
237 private HashMap<String, IdleTimerParams> mActiveIdleTimers = Maps.newHashMap();
238
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700239 private volatile boolean mFirewallEnabled;
Jeff Sharkey605eb792014-11-04 13:34:06 -0800240 private volatile boolean mStrictEnabled;
Jeff Sharkey350083e2011-06-29 10:45:16 -0700241
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700242 private boolean mMobileActivityFromRadio = false;
243 private int mLastPowerStateFromRadio = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Adam Lesinskie08af192015-03-25 16:42:59 -0700244 private int mLastPowerStateFromWifi = DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700245
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800246 private final RemoteCallbackList<INetworkActivityListener> mNetworkActivityListeners =
Christopher Wiley212b95f2016-08-02 11:38:57 -0700247 new RemoteCallbackList<>();
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800248 private boolean mNetworkActive;
249
San Mehat873f2142010-01-14 10:25:07 -0800250 /**
251 * Constructs a new NetworkManagementService instance
252 *
253 * @param context Binder context for this service
254 */
Lorenzo Colittia0868002017-07-11 02:29:28 +0900255 private NetworkManagementService(
Luke Huang909b31a2019-03-16 21:21:16 +0800256 Context context, SystemServices services) {
San Mehat873f2142010-01-14 10:25:07 -0800257 mContext = context;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900258 mServices = services;
San Mehat4d02d002010-01-22 16:07:46 -0800259
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -0700260 mDaemonHandler = new Handler(FgThread.get().getLooper());
Wink Saville67e07892014-06-18 16:43:14 -0700261
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000262 mNetdUnsolicitedEventListener = new NetdUnsolicitedEventListener();
263
Lorenzo Colittia0868002017-07-11 02:29:28 +0900264 mServices.registerLocalService(new LocalService());
Lorenzo Colitti8228eb32017-07-19 06:17:33 +0900265
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900266 synchronized (mTetheringStatsProviders) {
267 mTetheringStatsProviders.put(new NetdTetheringStatsProvider(), "netd");
268 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700269 }
270
271 @VisibleForTesting
272 NetworkManagementService() {
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700273 mContext = null;
274 mDaemonHandler = null;
Lorenzo Colittia0868002017-07-11 02:29:28 +0900275 mServices = null;
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000276 mNetdUnsolicitedEventListener = null;
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700277 }
278
Luke Huang909b31a2019-03-16 21:21:16 +0800279 static NetworkManagementService create(Context context, SystemServices services)
Felipe Leme03e689d2016-03-02 16:17:38 -0800280 throws InterruptedException {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900281 final NetworkManagementService service =
Luke Huang909b31a2019-03-16 21:21:16 +0800282 new NetworkManagementService(context, services);
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700283 if (DBG) Slog.d(TAG, "Creating NetworkManagementService");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900284 if (DBG) Slog.d(TAG, "Connecting native netd service");
bohu07cc3bb2016-05-03 15:58:01 -0700285 service.connectNativeNetdService();
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900286 if (DBG) Slog.d(TAG, "Connected");
Robert Greenwalte5c3afb2010-09-22 14:32:35 -0700287 return service;
San Mehat873f2142010-01-14 10:25:07 -0800288 }
289
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900290 public static NetworkManagementService create(Context context) throws InterruptedException {
Luke Huang909b31a2019-03-16 21:21:16 +0800291 return create(context, new SystemServices());
Lorenzo Colitti7421a012013-08-20 22:51:24 +0900292 }
293
Jeff Sharkey350083e2011-06-29 10:45:16 -0700294 public void systemReady() {
Felipe Leme03e689d2016-03-02 16:17:38 -0800295 if (DBG) {
296 final long start = System.currentTimeMillis();
297 prepareNativeDaemon();
298 final long delta = System.currentTimeMillis() - start;
299 Slog.d(TAG, "Prepared in " + delta + "ms");
300 return;
301 } else {
302 prepareNativeDaemon();
303 }
Jeff Sharkey350083e2011-06-29 10:45:16 -0700304 }
305
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800306 private IBatteryStats getBatteryStats() {
307 synchronized (this) {
308 if (mBatteryStats != null) {
309 return mBatteryStats;
310 }
Lorenzo Colittia0868002017-07-11 02:29:28 +0900311 mBatteryStats =
312 IBatteryStats.Stub.asInterface(mServices.getService(BatteryStats.SERVICE_NAME));
Dianne Hackborne13c4c02014-02-11 17:18:35 -0800313 return mBatteryStats;
314 }
315 }
316
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800317 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800318 public void registerObserver(INetworkManagementEventObserver observer) {
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000319 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
320 mObservers.register(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800321 }
322
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800323 @Override
Jeff Sharkey3df273e2011-12-15 15:47:12 -0800324 public void unregisterObserver(INetworkManagementEventObserver observer) {
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000325 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
326 mObservers.unregister(observer);
San Mehat4d02d002010-01-22 16:07:46 -0800327 }
328
Erik Klineb2cfdfb2017-01-18 20:54:14 +0900329 @FunctionalInterface
330 private interface NetworkManagementEventCallback {
331 public void sendCallback(INetworkManagementEventObserver o) throws RemoteException;
332 }
333
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000334 private void invokeForAllObservers(NetworkManagementEventCallback eventCallback) {
335 final int length = mObservers.beginBroadcast();
336 try {
337 for (int i = 0; i < length; i++) {
338 try {
339 eventCallback.sendCallback(mObservers.getBroadcastItem(i));
340 } catch (RemoteException | RuntimeException e) {
341 }
342 }
343 } finally {
344 mObservers.finishBroadcast();
Lorenzo Colittid8bc8292019-01-24 13:28:50 +0900345 }
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000346 }
Lorenzo Colittid8bc8292019-01-24 13:28:50 +0900347
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000348 /**
349 * Notify our observers of an interface status change
350 */
351 private void notifyInterfaceStatusChanged(String iface, boolean up) {
352 invokeForAllObservers(o -> o.interfaceStatusChanged(iface, up));
353 }
Lorenzo Colittid8bc8292019-01-24 13:28:50 +0900354
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000355 /**
356 * Notify our observers of an interface link state change
357 * (typically, an Ethernet cable has been plugged-in or unplugged).
358 */
359 private void notifyInterfaceLinkStateChanged(String iface, boolean up) {
360 invokeForAllObservers(o -> o.interfaceLinkStateChanged(iface, up));
361 }
362
363 /**
364 * Notify our observers of an interface addition.
365 */
366 private void notifyInterfaceAdded(String iface) {
367 invokeForAllObservers(o -> o.interfaceAdded(iface));
368 }
369
370 /**
371 * Notify our observers of an interface removal.
372 */
373 private void notifyInterfaceRemoved(String iface) {
374 // netd already clears out quota and alerts for removed ifaces; update
375 // our sanity-checking state.
376 mActiveAlerts.remove(iface);
377 mActiveQuotas.remove(iface);
378 invokeForAllObservers(o -> o.interfaceRemoved(iface));
379 }
380
381 /**
382 * Notify our observers of a limit reached.
383 */
384 private void notifyLimitReached(String limitName, String iface) {
385 invokeForAllObservers(o -> o.limitReached(limitName, iface));
386 }
387
388 /**
389 * Notify our observers of a change in the data activity state of the interface
390 */
391 private void notifyInterfaceClassActivity(int type, boolean isActive, long tsNanos,
392 int uid, boolean fromRadio) {
393 final boolean isMobile = ConnectivityManager.isNetworkTypeMobile(type);
394 int powerState = isActive
395 ? DataConnectionRealTimeInfo.DC_POWER_STATE_HIGH
396 : DataConnectionRealTimeInfo.DC_POWER_STATE_LOW;
397 if (isMobile) {
398 if (!fromRadio) {
399 if (mMobileActivityFromRadio) {
400 // If this call is not coming from a report from the radio itself, but we
401 // have previously received reports from the radio, then we will take the
402 // power state to just be whatever the radio last reported.
403 powerState = mLastPowerStateFromRadio;
Lorenzo Colittid8bc8292019-01-24 13:28:50 +0900404 }
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000405 } else {
406 mMobileActivityFromRadio = true;
Mike J. Chen6143f5f2011-06-23 15:17:51 -0700407 }
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000408 if (mLastPowerStateFromRadio != powerState) {
409 mLastPowerStateFromRadio = powerState;
410 try {
411 getBatteryStats().noteMobileRadioPowerState(powerState, tsNanos, uid);
412 } catch (RemoteException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -0700413 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700414 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800415 }
Lorenzo Colittid8bc8292019-01-24 13:28:50 +0900416
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000417 if (ConnectivityManager.isNetworkTypeWifi(type)) {
418 if (mLastPowerStateFromWifi != powerState) {
419 mLastPowerStateFromWifi = powerState;
420 try {
421 getBatteryStats().noteWifiRadioPowerState(powerState, tsNanos, uid);
422 } catch (RemoteException e) {
423 }
424 }
Lorenzo Colittid8bc8292019-01-24 13:28:50 +0900425 }
426
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000427 if (!isMobile || fromRadio || !mMobileActivityFromRadio) {
428 // Report the change in data activity. We don't do this if this is a change
429 // on the mobile network, that is not coming from the radio itself, and we
430 // have previously seen change reports from the radio. In that case only
431 // the radio is the authority for the current state.
432 final boolean active = isActive;
433 invokeForAllObservers(o -> o.interfaceClassDataActivityChanged(
434 Integer.toString(type), active, tsNanos));
435 }
436
437 boolean report = false;
438 synchronized (mIdleTimerLock) {
439 if (mActiveIdleTimers.isEmpty()) {
440 // If there are no idle timers, we are not monitoring activity, so we
441 // are always considered active.
442 isActive = true;
443 }
444 if (mNetworkActive != isActive) {
445 mNetworkActive = isActive;
446 report = isActive;
447 }
448 }
449 if (report) {
450 reportNetworkActive();
Dianne Hackborn77b987f2014-02-26 16:20:52 -0800451 }
Haoyu Baidb3c8672012-06-20 14:29:57 -0700452 }
453
Lorenzo Colitti07f13042017-07-10 19:06:57 +0900454 @Override
455 public void registerTetheringStatsProvider(ITetheringStatsProvider provider, String name) {
456 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
457 Preconditions.checkNotNull(provider);
458 synchronized(mTetheringStatsProviders) {
459 mTetheringStatsProviders.put(provider, name);
460 }
461 }
462
463 @Override
464 public void unregisterTetheringStatsProvider(ITetheringStatsProvider provider) {
465 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
466 synchronized(mTetheringStatsProviders) {
467 mTetheringStatsProviders.remove(provider);
468 }
469 }
470
Lorenzo Colitti9f0baa92017-08-15 19:25:51 +0900471 @Override
472 public void tetherLimitReached(ITetheringStatsProvider provider) {
473 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
474 synchronized(mTetheringStatsProviders) {
475 if (!mTetheringStatsProviders.containsKey(provider)) {
476 return;
477 }
478 // No current code examines the interface parameter in a global alert. Just pass null.
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000479 mDaemonHandler.post(() -> notifyLimitReached(LIMIT_GLOBAL_ALERT, null));
Lorenzo Colitti9f0baa92017-08-15 19:25:51 +0900480 }
481 }
482
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900483 // Sync the state of the given chain with the native daemon.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700484 private void syncFirewallChainLocked(int chain, String name) {
485 SparseIntArray rules;
486 synchronized (mRulesLock) {
487 final SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900488 // Make a copy of the current rules, and then clear them. This is because
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700489 // setFirewallUidRuleInternal only pushes down rules to the native daemon if they
490 // are different from the current rules stored in the mUidFirewall*Rules array for
491 // the specified chain. If we don't clear the rules, setFirewallUidRuleInternal
492 // will do nothing.
493 rules = uidFirewallRules.clone();
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900494 uidFirewallRules.clear();
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700495 }
496 if (rules.size() > 0) {
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900497 // Now push the rules. setFirewallUidRuleInternal will push each of these down to the
498 // native daemon, and also add them to the mUidFirewall*Rules array for the specified
499 // chain.
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700500 if (DBG) Slog.d(TAG, "Pushing " + rules.size() + " active firewall "
501 + name + "UID rules");
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900502 for (int i = 0; i < rules.size(); i++) {
Felipe Lemea701cad2016-05-12 09:58:14 -0700503 setFirewallUidRuleLocked(chain, rules.keyAt(i), rules.valueAt(i));
Lorenzo Colitti9eb844e2016-03-23 23:22:49 +0900504 }
505 }
506 }
507
bohu07cc3bb2016-05-03 15:58:01 -0700508 private void connectNativeNetdService() {
Lorenzo Colittia0868002017-07-11 02:29:28 +0900509 mNetdService = mServices.getNetd();
Luke Huangd290dd52018-09-04 17:08:18 +0800510 try {
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000511 mNetdService.registerUnsolicitedEventListener(mNetdUnsolicitedEventListener);
512 if (DBG) Slog.d(TAG, "Register unsolicited event listener");
Luke Huangd290dd52018-09-04 17:08:18 +0800513 } catch (RemoteException | ServiceSpecificException e) {
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000514 Slog.e(TAG, "Failed to set Netd unsolicited event listener " + e);
Luke Huangd290dd52018-09-04 17:08:18 +0800515 }
bohu07cc3bb2016-05-03 15:58:01 -0700516 }
517
518 /**
519 * Prepare native daemon once connected, enabling modules and pushing any
520 * existing in-memory rules.
521 */
522 private void prepareNativeDaemon() {
Lorenzo Colitti58967ba2016-02-02 17:21:21 +0900523
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700524 // push any existing quota or UID rules
525 synchronized (mQuotaLock) {
Felipe Leme65be3022016-03-22 14:53:13 -0700526
Luke Huang56a03a02018-09-07 12:02:16 +0800527 // Netd unconditionally enable bandwidth control
528 SystemProperties.set(PROP_QTAGUID_ENABLED, "1");
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900529
Luke Huang473eb872018-07-26 17:33:14 +0800530 mStrictEnabled = true;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900531
Felipe Leme65be3022016-03-22 14:53:13 -0700532 setDataSaverModeEnabled(mDataSaverMode);
533
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700534 int size = mActiveQuotas.size();
535 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800536 if (DBG) Slog.d(TAG, "Pushing " + size + " active quota rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700537 final HashMap<String, Long> activeQuotas = mActiveQuotas;
538 mActiveQuotas = Maps.newHashMap();
539 for (Map.Entry<String, Long> entry : activeQuotas.entrySet()) {
540 setInterfaceQuota(entry.getKey(), entry.getValue());
541 }
542 }
543
544 size = mActiveAlerts.size();
545 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800546 if (DBG) Slog.d(TAG, "Pushing " + size + " active alert rules");
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700547 final HashMap<String, Long> activeAlerts = mActiveAlerts;
548 mActiveAlerts = Maps.newHashMap();
549 for (Map.Entry<String, Long> entry : activeAlerts.entrySet()) {
550 setInterfaceAlert(entry.getKey(), entry.getValue());
551 }
552 }
553
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700554 SparseBooleanArray uidRejectOnQuota = null;
555 SparseBooleanArray uidAcceptOnQuota = null;
556 synchronized (mRulesLock) {
557 size = mUidRejectOnMetered.size();
558 if (size > 0) {
559 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered blacklist rules");
560 uidRejectOnQuota = mUidRejectOnMetered;
561 mUidRejectOnMetered = new SparseBooleanArray();
562 }
563
564 size = mUidAllowOnMetered.size();
565 if (size > 0) {
566 if (DBG) Slog.d(TAG, "Pushing " + size + " UIDs to metered whitelist rules");
567 uidAcceptOnQuota = mUidAllowOnMetered;
568 mUidAllowOnMetered = new SparseBooleanArray();
569 }
570 }
571 if (uidRejectOnQuota != null) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700572 for (int i = 0; i < uidRejectOnQuota.size(); i++) {
Felipe Leme65be3022016-03-22 14:53:13 -0700573 setUidMeteredNetworkBlacklist(uidRejectOnQuota.keyAt(i),
574 uidRejectOnQuota.valueAt(i));
575 }
576 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700577 if (uidAcceptOnQuota != null) {
Felipe Leme65be3022016-03-22 14:53:13 -0700578 for (int i = 0; i < uidAcceptOnQuota.size(); i++) {
579 setUidMeteredNetworkWhitelist(uidAcceptOnQuota.keyAt(i),
580 uidAcceptOnQuota.valueAt(i));
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700581 }
582 }
Jeff Sharkey605eb792014-11-04 13:34:06 -0800583
584 size = mUidCleartextPolicy.size();
585 if (size > 0) {
Felipe Leme03e689d2016-03-02 16:17:38 -0800586 if (DBG) Slog.d(TAG, "Pushing " + size + " active UID cleartext policies");
Jeff Sharkey605eb792014-11-04 13:34:06 -0800587 final SparseIntArray local = mUidCleartextPolicy;
588 mUidCleartextPolicy = new SparseIntArray();
589 for (int i = 0; i < local.size(); i++) {
590 setUidCleartextNetworkPolicy(local.keyAt(i), local.valueAt(i));
591 }
592 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -0700593
Robin Leec3736bc2017-03-10 16:19:54 +0000594 setFirewallEnabled(mFirewallEnabled);
Amith Yamasani15e472352015-04-24 19:06:07 -0700595
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700596 syncFirewallChainLocked(FIREWALL_CHAIN_NONE, "");
597 syncFirewallChainLocked(FIREWALL_CHAIN_STANDBY, "standby ");
598 syncFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, "dozable ");
599 syncFirewallChainLocked(FIREWALL_CHAIN_POWERSAVE, "powersave ");
Xiaohui Chenb41c9f72015-06-17 15:55:37 -0700600
Sudheer Shanka62f5c172017-03-17 16:25:55 -0700601 final int[] chains =
602 {FIREWALL_CHAIN_STANDBY, FIREWALL_CHAIN_DOZABLE, FIREWALL_CHAIN_POWERSAVE};
603 for (int chain : chains) {
604 if (getFirewallChainState(chain)) {
605 setFirewallChainEnabled(chain, true);
606 }
Felipe Leme011b98f2016-02-10 17:28:31 -0800607 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700608 }
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900609
Luke Huang56a03a02018-09-07 12:02:16 +0800610
611 try {
612 getBatteryStats().noteNetworkStatsEnabled();
613 } catch (RemoteException e) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +0900614 }
615
Jeff Sharkeyb24a7852012-05-01 15:19:37 -0700616 }
San Mehat4d02d002010-01-22 16:07:46 -0800617
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000618 /**
619 * Notify our observers of a new or updated interface address.
620 */
621 private void notifyAddressUpdated(String iface, LinkAddress address) {
622 invokeForAllObservers(o -> o.addressUpdated(iface, address));
623 }
624
625 /**
626 * Notify our observers of a deleted interface address.
627 */
628 private void notifyAddressRemoved(String iface, LinkAddress address) {
629 invokeForAllObservers(o -> o.addressRemoved(iface, address));
630 }
631
632 /**
633 * Notify our observers of DNS server information received.
634 */
635 private void notifyInterfaceDnsServerInfo(String iface, long lifetime, String[] addresses) {
636 invokeForAllObservers(o -> o.interfaceDnsServerInfo(iface, lifetime, addresses));
637 }
638
639 /**
640 * Notify our observers of a route change.
641 */
642 private void notifyRouteChange(boolean updated, RouteInfo route) {
643 if (updated) {
644 invokeForAllObservers(o -> o.routeUpdated(route));
645 } else {
646 invokeForAllObservers(o -> o.routeRemoved(route));
647 }
648 }
649
650 private class NetdUnsolicitedEventListener extends INetdUnsolicitedEventListener.Stub {
651 @Override
652 public void onInterfaceClassActivityChanged(boolean isActive,
653 int label, long timestamp, int uid) throws RemoteException {
654 final long timestampNanos;
655 if (timestamp <= 0) {
656 timestampNanos = SystemClock.elapsedRealtimeNanos();
657 } else {
658 timestampNanos = timestamp;
659 }
660 mDaemonHandler.post(() ->
661 notifyInterfaceClassActivity(label, isActive, timestampNanos, uid, false));
662 }
663
664 @Override
665 public void onQuotaLimitReached(String alertName, String ifName)
666 throws RemoteException {
667 mDaemonHandler.post(() -> notifyLimitReached(alertName, ifName));
668 }
669
670 @Override
671 public void onInterfaceDnsServerInfo(String ifName,
672 long lifetime, String[] servers) throws RemoteException {
673 mDaemonHandler.post(() -> notifyInterfaceDnsServerInfo(ifName, lifetime, servers));
674 }
675
676 @Override
677 public void onInterfaceAddressUpdated(String addr,
678 String ifName, int flags, int scope) throws RemoteException {
679 final LinkAddress address = new LinkAddress(addr, flags, scope);
680 mDaemonHandler.post(() -> notifyAddressUpdated(ifName, address));
681 }
682
683 @Override
684 public void onInterfaceAddressRemoved(String addr,
685 String ifName, int flags, int scope) throws RemoteException {
686 final LinkAddress address = new LinkAddress(addr, flags, scope);
687 mDaemonHandler.post(() -> notifyAddressRemoved(ifName, address));
688 }
689
690 @Override
691 public void onInterfaceAdded(String ifName) throws RemoteException {
692 mDaemonHandler.post(() -> notifyInterfaceAdded(ifName));
693 }
694
695 @Override
696 public void onInterfaceRemoved(String ifName) throws RemoteException {
697 mDaemonHandler.post(() -> notifyInterfaceRemoved(ifName));
698 }
699
700 @Override
701 public void onInterfaceChanged(String ifName, boolean up)
702 throws RemoteException {
703 mDaemonHandler.post(() -> notifyInterfaceStatusChanged(ifName, up));
704 }
705
706 @Override
707 public void onInterfaceLinkStateChanged(String ifName, boolean up)
708 throws RemoteException {
709 mDaemonHandler.post(() -> notifyInterfaceLinkStateChanged(ifName, up));
710 }
711
712 @Override
713 public void onRouteChanged(boolean updated,
714 String route, String gateway, String ifName) throws RemoteException {
715 final RouteInfo processRoute = new RouteInfo(new IpPrefix(route),
716 ("".equals(gateway)) ? null : InetAddresses.parseNumericAddress(gateway),
717 ifName);
718 mDaemonHandler.post(() -> notifyRouteChange(updated, processRoute));
719 }
720
721 @Override
722 public void onStrictCleartextDetected(int uid, String hex) throws RemoteException {
723 // Don't need to post to mDaemonHandler because the only thing
724 // that notifyCleartextNetwork does is post to a handler
725 ActivityManager.getService().notifyCleartextNetwork(uid,
726 HexDump.hexStringToByteArray(hex));
727 }
Remi NGUYEN VANeec0ed42019-04-09 14:01:51 +0900728
729 @Override
730 public int getInterfaceVersion() {
731 return INetdUnsolicitedEventListener.VERSION;
732 }
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +0000733 }
734
San Mehat873f2142010-01-14 10:25:07 -0800735 //
San Mehat873f2142010-01-14 10:25:07 -0800736 // INetworkManagementService members
737 //
Erik Kline4e37b702016-07-05 11:34:21 +0900738 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800739 public String[] listInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800740 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -0700741 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +0800742 return mNetdService.interfaceGetList();
Luke Huang14f75442018-08-15 19:22:54 +0800743 } catch (RemoteException | ServiceSpecificException e) {
744 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700745 }
San Mehated4fc8a2010-01-22 12:28:36 -0800746 }
747
Lorenzo Colittib90ad242019-03-18 23:50:34 +0900748 /**
749 * Convert InterfaceConfiguration to InterfaceConfigurationParcel with given ifname.
750 */
751 private static InterfaceConfigurationParcel toStableParcel(InterfaceConfiguration cfg,
752 String iface) {
753 InterfaceConfigurationParcel cfgParcel = new InterfaceConfigurationParcel();
754 cfgParcel.ifName = iface;
755 String hwAddr = cfg.getHardwareAddress();
756 if (!TextUtils.isEmpty(hwAddr)) {
757 cfgParcel.hwAddr = hwAddr;
758 } else {
759 cfgParcel.hwAddr = "";
760 }
761 cfgParcel.ipv4Addr = cfg.getLinkAddress().getAddress().getHostAddress();
762 cfgParcel.prefixLength = cfg.getLinkAddress().getPrefixLength();
763 ArrayList<String> flags = new ArrayList<>();
764 for (String flag : cfg.getFlags()) {
765 flags.add(flag);
766 }
767 cfgParcel.flags = flags.toArray(new String[0]);
768
769 return cfgParcel;
770 }
771
772 /**
773 * Construct InterfaceConfiguration from InterfaceConfigurationParcel.
774 */
775 public static InterfaceConfiguration fromStableParcel(InterfaceConfigurationParcel p) {
776 InterfaceConfiguration cfg = new InterfaceConfiguration();
777 cfg.setHardwareAddress(p.hwAddr);
778
779 final InetAddress addr = NetworkUtils.numericToInetAddress(p.ipv4Addr);
780 cfg.setLinkAddress(new LinkAddress(addr, p.prefixLength));
781 for (String flag : p.flags) {
782 cfg.setFlag(flag);
783 }
784
785 return cfg;
786 }
787
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800788 @Override
789 public InterfaceConfiguration getInterfaceConfig(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800790 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang14f75442018-08-15 19:22:54 +0800791 final InterfaceConfigurationParcel result;
Kenny Roota80ce062010-06-01 13:23:53 -0700792 try {
Luke Huang14f75442018-08-15 19:22:54 +0800793 result = mNetdService.interfaceGetCfg(iface);
794 } catch (RemoteException | ServiceSpecificException e) {
795 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700796 }
San Mehated4fc8a2010-01-22 12:28:36 -0800797
San Mehated4fc8a2010-01-22 12:28:36 -0800798 try {
Lorenzo Colittib90ad242019-03-18 23:50:34 +0900799 final InterfaceConfiguration cfg = fromStableParcel(result);
Luke Huang14f75442018-08-15 19:22:54 +0800800 return cfg;
801 } catch (IllegalArgumentException iae) {
802 throw new IllegalStateException("Invalid InterfaceConfigurationParcel", iae);
San Mehated4fc8a2010-01-22 12:28:36 -0800803 }
San Mehated4fc8a2010-01-22 12:28:36 -0800804 }
805
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800806 @Override
807 public void setInterfaceConfig(String iface, InterfaceConfiguration cfg) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800808 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800809 LinkAddress linkAddr = cfg.getLinkAddress();
Robert Greenwalt2d2afd12011-02-01 15:30:46 -0800810 if (linkAddr == null || linkAddr.getAddress() == null) {
811 throw new IllegalStateException("Null LinkAddress given");
Robert Greenwalted126402011-01-28 15:34:55 -0800812 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800813
Lorenzo Colittib90ad242019-03-18 23:50:34 +0900814 final InterfaceConfigurationParcel cfgParcel = toStableParcel(cfg, iface);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800815
Kenny Roota80ce062010-06-01 13:23:53 -0700816 try {
Luke Huang14f75442018-08-15 19:22:54 +0800817 mNetdService.interfaceSetCfg(cfgParcel);
818 } catch (RemoteException | ServiceSpecificException e) {
819 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700820 }
San Mehat873f2142010-01-14 10:25:07 -0800821 }
822
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800823 @Override
824 public void setInterfaceDown(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800825 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800826 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800827 ifcg.setInterfaceDown();
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800828 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -0700829 }
830
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800831 @Override
832 public void setInterfaceUp(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800833 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800834 final InterfaceConfiguration ifcg = getInterfaceConfig(iface);
Jeff Sharkeyddba1062011-11-29 18:37:04 -0800835 ifcg.setInterfaceUp();
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800836 setInterfaceConfig(iface, ifcg);
Irfan Sheriff7244c972011-08-05 20:40:45 -0700837 }
838
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800839 @Override
840 public void setInterfaceIpv6PrivacyExtensions(String iface, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800841 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sheriff73293612011-09-14 12:31:56 -0700842 try {
Luke Huang14f75442018-08-15 19:22:54 +0800843 mNetdService.interfaceSetIPv6PrivacyExtensions(iface, enable);
844 } catch (RemoteException | ServiceSpecificException e) {
845 throw new IllegalStateException(e);
Irfan Sheriff73293612011-09-14 12:31:56 -0700846 }
847 }
848
Irfan Sherifff5600612011-06-16 10:26:28 -0700849 /* TODO: This is right now a IPv4 only function. Works for wifi which loses its
850 IPv6 addresses on interface down, but we need to do full clean up here */
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800851 @Override
852 public void clearInterfaceAddresses(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800853 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Irfan Sherifff5600612011-06-16 10:26:28 -0700854 try {
Luke Huang14f75442018-08-15 19:22:54 +0800855 mNetdService.interfaceClearAddrs(iface);
856 } catch (RemoteException | ServiceSpecificException e) {
857 throw new IllegalStateException(e);
Irfan Sherifff5600612011-06-16 10:26:28 -0700858 }
859 }
860
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800861 @Override
862 public void enableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800863 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -0700864 try {
Luke Huang14f75442018-08-15 19:22:54 +0800865 mNetdService.interfaceSetEnableIPv6(iface, true);
866 } catch (RemoteException | ServiceSpecificException e) {
867 throw new IllegalStateException(e);
repo sync7960d9f2011-09-29 12:40:02 -0700868 }
869 }
870
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800871 @Override
Joel Scherpelz2db10742017-06-07 15:38:38 +0900872 public void setIPv6AddrGenMode(String iface, int mode) throws ServiceSpecificException {
873 try {
874 mNetdService.setIPv6AddrGenMode(iface, mode);
875 } catch (RemoteException e) {
876 throw e.rethrowAsRuntimeException();
877 }
878 }
879
880 @Override
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800881 public void disableIpv6(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800882 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
repo sync7960d9f2011-09-29 12:40:02 -0700883 try {
Luke Huang14f75442018-08-15 19:22:54 +0800884 mNetdService.interfaceSetEnableIPv6(iface, false);
885 } catch (RemoteException | ServiceSpecificException e) {
886 throw new IllegalStateException(e);
repo sync7960d9f2011-09-29 12:40:02 -0700887 }
888 }
889
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800890 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -0700891 public void addRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +0800892 modifyRoute(MODIFY_OPERATION_ADD, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700893 }
894
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800895 @Override
Sreeram Ramachandranb2829fa2014-04-15 19:07:12 -0700896 public void removeRoute(int netId, RouteInfo route) {
Luke Huang8a462ec2018-08-24 20:33:16 +0800897 modifyRoute(MODIFY_OPERATION_REMOVE, netId, route);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700898 }
899
Luke Huang8a462ec2018-08-24 20:33:16 +0800900 private void modifyRoute(boolean add, int netId, RouteInfo route) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800901 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwalt3b28e9a2011-11-02 14:37:19 -0700902
Luke Huang8a462ec2018-08-24 20:33:16 +0800903 final String ifName = route.getInterface();
904 final String dst = route.getDestination().toString();
905 final String nextHop;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +0900906
907 switch (route.getType()) {
908 case RouteInfo.RTN_UNICAST:
909 if (route.hasGateway()) {
Luke Huang8a462ec2018-08-24 20:33:16 +0800910 nextHop = route.getGateway().getHostAddress();
911 } else {
912 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +0900913 }
914 break;
915 case RouteInfo.RTN_UNREACHABLE:
Luke Huang8a462ec2018-08-24 20:33:16 +0800916 nextHop = INetd.NEXTHOP_UNREACHABLE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +0900917 break;
918 case RouteInfo.RTN_THROW:
Luke Huang8a462ec2018-08-24 20:33:16 +0800919 nextHop = INetd.NEXTHOP_THROW;
920 break;
921 default:
922 nextHop = INetd.NEXTHOP_NONE;
Lorenzo Colitti4b0f8e62014-09-19 01:49:05 +0900923 break;
Sreeram Ramachandran1fbcb272014-05-22 16:30:48 -0700924 }
Jeff Sharkeyba2896e2011-11-30 18:13:54 -0800925 try {
Luke Huang8a462ec2018-08-24 20:33:16 +0800926 if (add) {
927 mNetdService.networkAddRoute(netId, ifName, dst, nextHop);
928 } else {
929 mNetdService.networkRemoveRoute(netId, ifName, dst, nextHop);
930 }
931 } catch (RemoteException | ServiceSpecificException e) {
932 throw new IllegalStateException(e);
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700933 }
934 }
935
936 private ArrayList<String> readRouteList(String filename) {
937 FileInputStream fstream = null;
Christopher Wiley212b95f2016-08-02 11:38:57 -0700938 ArrayList<String> list = new ArrayList<>();
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700939
940 try {
941 fstream = new FileInputStream(filename);
942 DataInputStream in = new DataInputStream(fstream);
943 BufferedReader br = new BufferedReader(new InputStreamReader(in));
944 String s;
945
946 // throw away the title line
947
948 while (((s = br.readLine()) != null) && (s.length() != 0)) {
949 list.add(s);
950 }
951 } catch (IOException ex) {
952 // return current list, possibly empty
953 } finally {
954 if (fstream != null) {
955 try {
956 fstream.close();
957 } catch (IOException ex) {}
958 }
959 }
960
961 return list;
962 }
963
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800964 @Override
sy.yun9d9b74a2013-09-02 05:24:09 +0900965 public void setMtu(String iface, int mtu) {
966 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
967
sy.yun9d9b74a2013-09-02 05:24:09 +0900968 try {
Luke Huang14f75442018-08-15 19:22:54 +0800969 mNetdService.interfaceSetMtu(iface, mtu);
970 } catch (RemoteException | ServiceSpecificException e) {
971 throw new IllegalStateException(e);
sy.yun9d9b74a2013-09-02 05:24:09 +0900972 }
973 }
974
975 @Override
San Mehat873f2142010-01-14 10:25:07 -0800976 public void shutdown() {
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800977 // TODO: remove from aidl if nobody calls externally
978 mContext.enforceCallingOrSelfPermission(SHUTDOWN, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800979
Felipe Leme03e689d2016-03-02 16:17:38 -0800980 Slog.i(TAG, "Shutting down");
San Mehat873f2142010-01-14 10:25:07 -0800981 }
982
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800983 @Override
San Mehat873f2142010-01-14 10:25:07 -0800984 public boolean getIpForwardingEnabled() throws IllegalStateException{
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800985 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -0800986
Kenny Roota80ce062010-06-01 13:23:53 -0700987 try {
Luke Huang4db488b2018-08-16 15:37:31 +0800988 final boolean isEnabled = mNetdService.ipfwdEnabled();
989 return isEnabled;
990 } catch (RemoteException | ServiceSpecificException e) {
991 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -0700992 }
San Mehat873f2142010-01-14 10:25:07 -0800993 }
994
Jeff Sharkeyaf75c332011-11-18 12:41:12 -0800995 @Override
996 public void setIpForwardingEnabled(boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -0800997 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey31c6e482011-11-18 17:09:01 -0800998 try {
Luke Huang4db488b2018-08-16 15:37:31 +0800999 if (enable) {
1000 mNetdService.ipfwdEnableForwarding("tethering");
1001 } else {
1002 mNetdService.ipfwdDisableForwarding("tethering");
1003 }
1004 } catch (RemoteException | ServiceSpecificException e) {
1005 throw new IllegalStateException(e);
Jeff Sharkey31c6e482011-11-18 17:09:01 -08001006 }
San Mehat873f2142010-01-14 10:25:07 -08001007 }
1008
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001009 @Override
1010 public void startTethering(String[] dhcpRange) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001011 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Robert Greenwaltbfb7bfa2010-03-24 16:03:21 -07001012 // an odd number of addrs will fail
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001013
Kenny Roota80ce062010-06-01 13:23:53 -07001014 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001015 mNetdService.tetherStart(dhcpRange);
1016 } catch (RemoteException | ServiceSpecificException e) {
1017 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001018 }
San Mehat873f2142010-01-14 10:25:07 -08001019 }
1020
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001021 @Override
1022 public void stopTethering() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001023 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001024 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001025 mNetdService.tetherStop();
1026 } catch (RemoteException | ServiceSpecificException e) {
1027 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001028 }
San Mehat873f2142010-01-14 10:25:07 -08001029 }
1030
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001031 @Override
1032 public boolean isTetheringStarted() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001033 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
San Mehat873f2142010-01-14 10:25:07 -08001034
Kenny Roota80ce062010-06-01 13:23:53 -07001035 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001036 final boolean isEnabled = mNetdService.tetherIsEnabled();
1037 return isEnabled;
1038 } catch (RemoteException | ServiceSpecificException e) {
1039 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001040 }
San Mehat873f2142010-01-14 10:25:07 -08001041 }
Matthew Xiefe19f122012-07-12 16:03:32 -07001042
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001043 @Override
1044 public void tetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001045 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001046 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001047 mNetdService.tetherInterfaceAdd(iface);
1048 } catch (RemoteException | ServiceSpecificException e) {
1049 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001050 }
Christopher Wiley212b95f2016-08-02 11:38:57 -07001051 List<RouteInfo> routes = new ArrayList<>();
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07001052 // The RouteInfo constructor truncates the LinkAddress to a network prefix, thus making it
1053 // suitable to use as a route destination.
1054 routes.add(new RouteInfo(getInterfaceConfig(iface).getLinkAddress(), null, iface));
1055 addInterfaceToLocalNetwork(iface, routes);
San Mehat873f2142010-01-14 10:25:07 -08001056 }
1057
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001058 @Override
San Mehat873f2142010-01-14 10:25:07 -08001059 public void untetherInterface(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001060 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001061 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001062 mNetdService.tetherInterfaceRemove(iface);
1063 } catch (RemoteException | ServiceSpecificException e) {
1064 throw new IllegalStateException(e);
Erik Kline1f4278a2016-08-16 16:46:33 +09001065 } finally {
1066 removeInterfaceFromLocalNetwork(iface);
Kenny Roota80ce062010-06-01 13:23:53 -07001067 }
San Mehat873f2142010-01-14 10:25:07 -08001068 }
1069
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001070 @Override
1071 public String[] listTetheredInterfaces() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001072 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001073 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +08001074 return mNetdService.tetherInterfaceList();
Luke Huang4a32bf42018-08-21 19:09:45 +08001075 } catch (RemoteException | ServiceSpecificException e) {
1076 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001077 }
San Mehat873f2142010-01-14 10:25:07 -08001078 }
1079
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001080 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001081 public void setDnsForwarders(Network network, String[] dns) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001082 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001083
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001084 int netId = (network != null) ? network.netId : ConnectivityManager.NETID_UNSET;
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001085
San Mehat873f2142010-01-14 10:25:07 -08001086 try {
Luke Huang4a32bf42018-08-21 19:09:45 +08001087 mNetdService.tetherDnsSet(netId, dns);
1088 } catch (RemoteException | ServiceSpecificException e) {
1089 throw new IllegalStateException(e);
San Mehat873f2142010-01-14 10:25:07 -08001090 }
1091 }
1092
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001093 @Override
1094 public String[] getDnsForwarders() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001095 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001096 try {
Luke Huang1b4f92f2018-12-12 15:59:31 +08001097 return mNetdService.tetherDnsList();
Luke Huang4a32bf42018-08-21 19:09:45 +08001098 } catch (RemoteException | ServiceSpecificException e) {
1099 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001100 }
San Mehat873f2142010-01-14 10:25:07 -08001101 }
1102
jiaguo1da35f72014-01-09 16:39:59 +08001103 private List<InterfaceAddress> excludeLinkLocal(List<InterfaceAddress> addresses) {
Christopher Wiley212b95f2016-08-02 11:38:57 -07001104 ArrayList<InterfaceAddress> filtered = new ArrayList<>(addresses.size());
jiaguo1da35f72014-01-09 16:39:59 +08001105 for (InterfaceAddress ia : addresses) {
1106 if (!ia.getAddress().isLinkLocalAddress())
1107 filtered.add(ia);
1108 }
1109 return filtered;
1110 }
1111
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001112 private void modifyInterfaceForward(boolean add, String fromIface, String toIface) {
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001113 try {
Luke Huang4db488b2018-08-16 15:37:31 +08001114 if (add) {
1115 mNetdService.ipfwdAddInterfaceForward(fromIface, toIface);
1116 } else {
1117 mNetdService.ipfwdRemoveInterfaceForward(fromIface, toIface);
1118 }
1119 } catch (RemoteException | ServiceSpecificException e) {
1120 throw new IllegalStateException(e);
Lorenzo Colitti35e36db2015-02-26 01:25:36 +09001121 }
1122 }
1123
1124 @Override
1125 public void startInterfaceForwarding(String fromIface, String toIface) {
1126 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1127 modifyInterfaceForward(true, fromIface, toIface);
1128 }
1129
1130 @Override
1131 public void stopInterfaceForwarding(String fromIface, String toIface) {
1132 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1133 modifyInterfaceForward(false, fromIface, toIface);
1134 }
1135
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001136 @Override
1137 public void enableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001138 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001139 try {
Luke Huanga31e0732018-10-22 13:23:10 +09001140 mNetdService.tetherAddForward(internalInterface, externalInterface);
1141 } catch (RemoteException | ServiceSpecificException e) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001142 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001143 }
San Mehat873f2142010-01-14 10:25:07 -08001144 }
1145
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001146 @Override
1147 public void disableNat(String internalInterface, String externalInterface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001148 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Kenny Roota80ce062010-06-01 13:23:53 -07001149 try {
Luke Huanga31e0732018-10-22 13:23:10 +09001150 mNetdService.tetherRemoveForward(internalInterface, externalInterface);
1151 } catch (RemoteException | ServiceSpecificException e) {
Jeff Sharkeyba2896e2011-11-30 18:13:54 -08001152 throw new IllegalStateException(e);
Kenny Roota80ce062010-06-01 13:23:53 -07001153 }
San Mehat873f2142010-01-14 10:25:07 -08001154 }
San Mehat72759df2010-01-19 13:50:37 -08001155
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001156 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001157 public void addIdleTimer(String iface, int timeout, final int type) {
Haoyu Bai04124232012-06-28 15:26:19 -07001158 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1159
1160 if (DBG) Slog.d(TAG, "Adding idletimer");
1161
1162 synchronized (mIdleTimerLock) {
1163 IdleTimerParams params = mActiveIdleTimers.get(iface);
1164 if (params != null) {
1165 // the interface already has idletimer, update network count
1166 params.networkCount++;
1167 return;
1168 }
1169
1170 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001171 mNetdService.idletimerAddInterface(iface, timeout, Integer.toString(type));
1172 } catch (RemoteException | ServiceSpecificException e) {
1173 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001174 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001175 mActiveIdleTimers.put(iface, new IdleTimerParams(timeout, type));
1176
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001177 // Networks start up.
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001178 if (ConnectivityManager.isNetworkTypeMobile(type)) {
1179 mNetworkActive = false;
1180 }
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +00001181 mDaemonHandler.post(() -> notifyInterfaceClassActivity(type, true,
1182 SystemClock.elapsedRealtimeNanos(), -1, false));
Haoyu Bai04124232012-06-28 15:26:19 -07001183 }
1184 }
1185
1186 @Override
1187 public void removeIdleTimer(String iface) {
1188 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1189
1190 if (DBG) Slog.d(TAG, "Removing idletimer");
1191
1192 synchronized (mIdleTimerLock) {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001193 final IdleTimerParams params = mActiveIdleTimers.get(iface);
Haoyu Bai04124232012-06-28 15:26:19 -07001194 if (params == null || --(params.networkCount) > 0) {
1195 return;
1196 }
1197
1198 try {
Luke Huanga62d0492018-07-27 20:08:21 +08001199 mNetdService.idletimerRemoveInterface(iface,
1200 params.timeout, Integer.toString(params.type));
1201 } catch (RemoteException | ServiceSpecificException e) {
1202 throw new IllegalStateException(e);
Haoyu Bai04124232012-06-28 15:26:19 -07001203 }
1204 mActiveIdleTimers.remove(iface);
Remi NGUYEN VANbfd0aa02019-01-29 04:03:38 +00001205 mDaemonHandler.post(() -> notifyInterfaceClassActivity(params.type, false,
1206 SystemClock.elapsedRealtimeNanos(), -1, false));
Haoyu Bai04124232012-06-28 15:26:19 -07001207 }
1208 }
1209
1210 @Override
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001211 public NetworkStats getNetworkStatsSummaryDev() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001212 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001213 try {
1214 return mStatsFactory.readNetworkStatsSummaryDev();
1215 } catch (IOException e) {
1216 throw new IllegalStateException(e);
1217 }
Jeff Sharkeye8914c32012-05-01 16:26:09 -07001218 }
1219
1220 @Override
1221 public NetworkStats getNetworkStatsSummaryXt() {
1222 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001223 try {
1224 return mStatsFactory.readNetworkStatsSummaryXt();
1225 } catch (IOException e) {
1226 throw new IllegalStateException(e);
1227 }
Jeff Sharkeyae2c1812011-10-04 13:11:40 -07001228 }
1229
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001230 @Override
Jeff Sharkey9a13f362011-04-26 16:25:36 -07001231 public NetworkStats getNetworkStatsDetail() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001232 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001233 try {
Dianne Hackbornd0c5b9a2014-02-21 16:19:05 -08001234 return mStatsFactory.readNetworkStatsDetail(UID_ALL, null, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001235 } catch (IOException e) {
1236 throw new IllegalStateException(e);
1237 }
San Mehat91cac642010-03-31 14:31:36 -07001238 }
1239
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001240 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001241 public void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001242 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001243
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001244 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001245 if (mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001246 throw new IllegalStateException("iface " + iface + " already has quota");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001247 }
1248
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001249 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001250 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001251 mNetdService.bandwidthSetInterfaceQuota(iface, quotaBytes);
1252
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001253 mActiveQuotas.put(iface, quotaBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001254 } catch (RemoteException | ServiceSpecificException e) {
1255 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001256 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001257
1258 synchronized (mTetheringStatsProviders) {
1259 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1260 try {
1261 provider.setInterfaceQuota(iface, quotaBytes);
1262 } catch (RemoteException e) {
1263 Log.e(TAG, "Problem setting tethering data limit on provider " +
1264 mTetheringStatsProviders.get(provider) + ": " + e);
1265 }
1266 }
1267 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001268 }
1269 }
1270
1271 @Override
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001272 public void removeInterfaceQuota(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001273 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001274
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001275 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001276 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001277 // TODO: eventually consider throwing
1278 return;
1279 }
1280
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001281 mActiveQuotas.remove(iface);
1282 mActiveAlerts.remove(iface);
Jeff Sharkey38ddeaa2011-11-08 13:04:22 -08001283
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001284 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001285 // TODO: support quota shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001286 mNetdService.bandwidthRemoveInterfaceQuota(iface);
1287 } catch (RemoteException | ServiceSpecificException e) {
1288 throw new IllegalStateException(e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001289 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001290
1291 synchronized (mTetheringStatsProviders) {
1292 for (ITetheringStatsProvider provider : mTetheringStatsProviders.keySet()) {
1293 try {
1294 provider.setInterfaceQuota(iface, ITetheringStatsProvider.QUOTA_UNLIMITED);
1295 } catch (RemoteException e) {
1296 Log.e(TAG, "Problem removing tethering data limit on provider " +
1297 mTetheringStatsProviders.get(provider) + ": " + e);
1298 }
1299 }
1300 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001301 }
1302 }
1303
1304 @Override
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001305 public void setInterfaceAlert(String iface, long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001306 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001307
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001308 // quick sanity check
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001309 if (!mActiveQuotas.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001310 throw new IllegalStateException("setting alert requires existing quota on iface");
1311 }
1312
1313 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001314 if (mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001315 throw new IllegalStateException("iface " + iface + " already has alert");
1316 }
1317
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001318 try {
1319 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001320 mNetdService.bandwidthSetInterfaceAlert(iface, alertBytes);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001321 mActiveAlerts.put(iface, alertBytes);
Luke Huangc7bea8662018-08-07 16:04:26 +08001322 } catch (RemoteException | ServiceSpecificException e) {
1323 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001324 }
1325 }
1326 }
1327
1328 @Override
1329 public void removeInterfaceAlert(String iface) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001330 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001331
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001332 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001333 if (!mActiveAlerts.containsKey(iface)) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001334 // TODO: eventually consider throwing
1335 return;
1336 }
1337
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001338 try {
1339 // TODO: support alert shared across interfaces
Luke Huangc7bea8662018-08-07 16:04:26 +08001340 mNetdService.bandwidthRemoveInterfaceAlert(iface);
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001341 mActiveAlerts.remove(iface);
Luke Huangc7bea8662018-08-07 16:04:26 +08001342 } catch (RemoteException | ServiceSpecificException e) {
1343 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001344 }
1345 }
1346 }
1347
1348 @Override
1349 public void setGlobalAlert(long alertBytes) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001350 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001351
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001352 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001353 mNetdService.bandwidthSetGlobalAlert(alertBytes);
1354 } catch (RemoteException | ServiceSpecificException e) {
1355 throw new IllegalStateException(e);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001356 }
1357 }
1358
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001359 private void setUidOnMeteredNetworkList(int uid, boolean blacklist, boolean enable) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001360 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001361
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001362 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001363 boolean oldEnable;
1364 SparseBooleanArray quotaList;
1365 synchronized (mRulesLock) {
1366 quotaList = blacklist ? mUidRejectOnMetered : mUidAllowOnMetered;
1367 oldEnable = quotaList.get(uid, false);
1368 }
Felipe Leme65be3022016-03-22 14:53:13 -07001369 if (oldEnable == enable) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001370 // TODO: eventually consider throwing
1371 return;
1372 }
1373
Felipe Leme29e72ea2016-09-08 13:26:55 -07001374 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "inetd bandwidth");
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001375 try {
Luke Huangc7bea8662018-08-07 16:04:26 +08001376 if (blacklist) {
1377 if (enable) {
1378 mNetdService.bandwidthAddNaughtyApp(uid);
1379 } else {
1380 mNetdService.bandwidthRemoveNaughtyApp(uid);
1381 }
1382 } else {
1383 if (enable) {
1384 mNetdService.bandwidthAddNiceApp(uid);
1385 } else {
1386 mNetdService.bandwidthRemoveNiceApp(uid);
1387 }
1388 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001389 synchronized (mRulesLock) {
1390 if (enable) {
1391 quotaList.put(uid, true);
1392 } else {
1393 quotaList.delete(uid);
1394 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001395 }
Luke Huangc7bea8662018-08-07 16:04:26 +08001396 } catch (RemoteException | ServiceSpecificException e) {
1397 throw new IllegalStateException(e);
Felipe Leme29e72ea2016-09-08 13:26:55 -07001398 } finally {
1399 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001400 }
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001401 }
1402 }
1403
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001404 @Override
Felipe Leme65be3022016-03-22 14:53:13 -07001405 public void setUidMeteredNetworkBlacklist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001406 setUidOnMeteredNetworkList(uid, true, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001407 }
1408
1409 @Override
1410 public void setUidMeteredNetworkWhitelist(int uid, boolean enable) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001411 setUidOnMeteredNetworkList(uid, false, enable);
Felipe Leme65be3022016-03-22 14:53:13 -07001412 }
1413
1414 @Override
1415 public boolean setDataSaverModeEnabled(boolean enable) {
Sehee Parka9139bc2017-12-22 13:54:05 +09001416 mContext.enforceCallingOrSelfPermission(NETWORK_SETTINGS, TAG);
1417
Felipe Leme65be3022016-03-22 14:53:13 -07001418 if (DBG) Log.d(TAG, "setDataSaverMode: " + enable);
1419 synchronized (mQuotaLock) {
1420 if (mDataSaverMode == enable) {
1421 Log.w(TAG, "setDataSaverMode(): already " + mDataSaverMode);
1422 return true;
1423 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07001424 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "bandwidthEnableDataSaver");
Felipe Leme65be3022016-03-22 14:53:13 -07001425 try {
1426 final boolean changed = mNetdService.bandwidthEnableDataSaver(enable);
1427 if (changed) {
1428 mDataSaverMode = enable;
1429 } else {
1430 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command silently failed");
1431 }
1432 return changed;
1433 } catch (RemoteException e) {
1434 Log.w(TAG, "setDataSaverMode(" + enable + "): netd command failed", e);
1435 return false;
Felipe Leme29e72ea2016-09-08 13:26:55 -07001436 } finally {
1437 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme65be3022016-03-22 14:53:13 -07001438 }
1439 }
1440 }
1441
Lorenzo Colittib90ad242019-03-18 23:50:34 +09001442 private static UidRangeParcel makeUidRangeParcel(int start, int stop) {
1443 UidRangeParcel range = new UidRangeParcel();
1444 range.start = start;
1445 range.stop = stop;
1446 return range;
1447 }
1448
1449 private static UidRangeParcel[] toStableParcels(UidRange[] ranges) {
1450 UidRangeParcel[] stableRanges = new UidRangeParcel[ranges.length];
1451 for (int i = 0; i < ranges.length; i++) {
1452 stableRanges[i] = makeUidRangeParcel(ranges[i].start, ranges[i].stop);
1453 }
1454 return stableRanges;
1455 }
1456
Felipe Leme65be3022016-03-22 14:53:13 -07001457 @Override
Robin Lee17e61832016-05-09 13:46:28 +01001458 public void setAllowOnlyVpnForUids(boolean add, UidRange[] uidRanges)
1459 throws ServiceSpecificException {
Rubin Xu2ea6c552018-01-11 10:59:19 +00001460 mContext.enforceCallingOrSelfPermission(NETWORK_STACK, TAG);
Robin Lee17e61832016-05-09 13:46:28 +01001461 try {
Lorenzo Colittib90ad242019-03-18 23:50:34 +09001462 mNetdService.networkRejectNonSecureVpn(add, toStableParcels(uidRanges));
Robin Lee17e61832016-05-09 13:46:28 +01001463 } catch (ServiceSpecificException e) {
1464 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1465 + ": netd command failed", e);
1466 throw e;
1467 } catch (RemoteException e) {
1468 Log.w(TAG, "setAllowOnlyVpnForUids(" + add + ", " + Arrays.toString(uidRanges) + ")"
1469 + ": netd command failed", e);
1470 throw e.rethrowAsRuntimeException();
1471 }
1472 }
1473
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001474 private void applyUidCleartextNetworkPolicy(int uid, int policy) {
Luke Huang473eb872018-07-26 17:33:14 +08001475 final int policyValue;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001476 switch (policy) {
1477 case StrictMode.NETWORK_POLICY_ACCEPT:
Luke Huang473eb872018-07-26 17:33:14 +08001478 policyValue = INetd.PENALTY_POLICY_ACCEPT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001479 break;
1480 case StrictMode.NETWORK_POLICY_LOG:
Luke Huang473eb872018-07-26 17:33:14 +08001481 policyValue = INetd.PENALTY_POLICY_LOG;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001482 break;
1483 case StrictMode.NETWORK_POLICY_REJECT:
Luke Huang473eb872018-07-26 17:33:14 +08001484 policyValue = INetd.PENALTY_POLICY_REJECT;
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001485 break;
1486 default:
1487 throw new IllegalArgumentException("Unknown policy " + policy);
1488 }
1489
1490 try {
Luke Huang473eb872018-07-26 17:33:14 +08001491 mNetdService.strictUidCleartextPenalty(uid, policyValue);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001492 mUidCleartextPolicy.put(uid, policy);
Luke Huang473eb872018-07-26 17:33:14 +08001493 } catch (RemoteException | ServiceSpecificException e) {
1494 throw new IllegalStateException(e);
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001495 }
1496 }
1497
Robin Lee17e61832016-05-09 13:46:28 +01001498 @Override
Jeff Sharkey605eb792014-11-04 13:34:06 -08001499 public void setUidCleartextNetworkPolicy(int uid, int policy) {
1500 if (Binder.getCallingUid() != uid) {
1501 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1502 }
1503
1504 synchronized (mQuotaLock) {
1505 final int oldPolicy = mUidCleartextPolicy.get(uid, StrictMode.NETWORK_POLICY_ACCEPT);
1506 if (oldPolicy == policy) {
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001507 // This also ensures we won't needlessly apply an ACCEPT policy if we've just
1508 // enabled strict and the underlying iptables rules are empty.
Jeff Sharkey605eb792014-11-04 13:34:06 -08001509 return;
1510 }
1511
Luke Huang473eb872018-07-26 17:33:14 +08001512 // TODO: remove this code after removing prepareNativeDaemon()
Jeff Sharkey605eb792014-11-04 13:34:06 -08001513 if (!mStrictEnabled) {
1514 // Module isn't enabled yet; stash the requested policy away to
1515 // apply later once the daemon is connected.
1516 mUidCleartextPolicy.put(uid, policy);
1517 return;
1518 }
1519
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001520 // netd does not keep state on strict mode policies, and cannot replace a non-accept
1521 // policy without deleting it first. Rather than add state to netd, just always send
1522 // it an accept policy when switching between two non-accept policies.
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001523 // TODO: consider keeping state in netd so we can simplify this code.
Lorenzo Colitti8c253ad2017-07-19 00:23:44 +09001524 if (oldPolicy != StrictMode.NETWORK_POLICY_ACCEPT &&
1525 policy != StrictMode.NETWORK_POLICY_ACCEPT) {
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001526 applyUidCleartextNetworkPolicy(uid, StrictMode.NETWORK_POLICY_ACCEPT);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001527 }
Lorenzo Colitti26364f12017-08-20 11:54:57 +09001528
1529 applyUidCleartextNetworkPolicy(uid, policy);
Jeff Sharkey605eb792014-11-04 13:34:06 -08001530 }
1531 }
1532
1533 @Override
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001534 public boolean isBandwidthControlEnabled() {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001535 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang56a03a02018-09-07 12:02:16 +08001536 return true;
Jeff Sharkey63d27a92011-08-03 17:04:22 -07001537 }
1538
1539 @Override
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001540 public NetworkStats getNetworkStatsUidDetail(int uid, String[] ifaces) {
Jeff Sharkey4529bb62011-12-14 10:31:54 -08001541 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001542 try {
Remi NGUYEN VAN088ff682018-03-06 12:36:54 +09001543 return mStatsFactory.readNetworkStatsDetail(uid, ifaces, TAG_ALL, null);
Jeff Sharkey9a2c2a62013-01-14 16:48:51 -08001544 } catch (IOException e) {
1545 throw new IllegalStateException(e);
1546 }
Jeff Sharkeyeedcb952011-05-17 14:55:15 -07001547 }
1548
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001549 private class NetdTetheringStatsProvider extends ITetheringStatsProvider.Stub {
1550 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001551 public NetworkStats getTetherStats(int how) {
1552 // We only need to return per-UID stats. Per-device stats are already counted by
1553 // interface counters.
1554 if (how != STATS_PER_UID) {
1555 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
1556 }
1557
Luke Huang13b79e82018-09-26 14:53:42 +08001558 final TetherStatsParcel[] tetherStatsVec;
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001559 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001560 tetherStatsVec = mNetdService.tetherGetStats();
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001561 } catch (RemoteException | ServiceSpecificException e) {
1562 throw new IllegalStateException("problem parsing tethering stats: ", e);
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001563 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001564
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001565 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(),
Luke Huang13b79e82018-09-26 14:53:42 +08001566 tetherStatsVec.length);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001567 final NetworkStats.Entry entry = new NetworkStats.Entry();
1568
Luke Huang13b79e82018-09-26 14:53:42 +08001569 for (TetherStatsParcel tetherStats : tetherStatsVec) {
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001570 try {
Luke Huang13b79e82018-09-26 14:53:42 +08001571 entry.iface = tetherStats.iface;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001572 entry.uid = UID_TETHERING;
1573 entry.set = SET_DEFAULT;
1574 entry.tag = TAG_NONE;
Luke Huang13b79e82018-09-26 14:53:42 +08001575 entry.rxBytes = tetherStats.rxBytes;
1576 entry.rxPackets = tetherStats.rxPackets;
1577 entry.txBytes = tetherStats.txBytes;
1578 entry.txPackets = tetherStats.txPackets;
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001579 stats.combineValues(entry);
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001580 } catch (ArrayIndexOutOfBoundsException e) {
Luke Huang13b79e82018-09-26 14:53:42 +08001581 throw new IllegalStateException("invalid tethering stats " + e);
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001582 }
1583 }
Lorenzo Colitti563dc452017-09-01 17:12:34 +09001584
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001585 return stats;
1586 }
Lorenzo Colitti50b60fc2017-08-11 13:47:49 +09001587
1588 @Override
1589 public void setInterfaceQuota(String iface, long quotaBytes) {
1590 // Do nothing. netd is already informed of quota changes in setInterfaceQuota.
1591 }
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001592 }
1593
1594 @Override
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001595 public NetworkStats getNetworkStatsTethering(int how) {
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001596 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1597
1598 final NetworkStats stats = new NetworkStats(SystemClock.elapsedRealtime(), 1);
1599 synchronized (mTetheringStatsProviders) {
1600 for (ITetheringStatsProvider provider: mTetheringStatsProviders.keySet()) {
1601 try {
Lorenzo Colittif1912ca2017-08-17 19:23:08 +09001602 stats.combineAllValues(provider.getTetherStats(how));
Lorenzo Colitti07f13042017-07-10 19:06:57 +09001603 } catch (RemoteException e) {
1604 Log.e(TAG, "Problem reading tethering stats from " +
1605 mTetheringStatsProviders.get(provider) + ": " + e);
1606 }
1607 }
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001608 }
Jeff Sharkeye4984be2013-09-10 21:03:27 -07001609 return stats;
Jeff Sharkeycdd02c5d2011-09-16 01:52:49 -07001610 }
1611
Jeff Sharkeyaf75c332011-11-18 12:41:12 -08001612 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001613 public void addVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001614 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001615
1616 try {
Lorenzo Colittib90ad242019-03-18 23:50:34 +09001617 mNetdService.networkAddUidRanges(netId, toStableParcels(ranges));
Luke Huang8a462ec2018-08-24 20:33:16 +08001618 } catch (RemoteException | ServiceSpecificException e) {
1619 throw new IllegalStateException(e);
Chad Brubaker3277620a2013-06-12 13:37:30 -07001620 }
1621 }
1622
1623 @Override
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001624 public void removeVpnUidRanges(int netId, UidRange[] ranges) {
Chad Brubaker3277620a2013-06-12 13:37:30 -07001625 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Luke Huang8a462ec2018-08-24 20:33:16 +08001626 try {
Lorenzo Colittib90ad242019-03-18 23:50:34 +09001627 mNetdService.networkRemoveUidRanges(netId, toStableParcels(ranges));
Luke Huang8a462ec2018-08-24 20:33:16 +08001628 } catch (RemoteException | ServiceSpecificException e) {
1629 throw new IllegalStateException(e);
Chad Brubakercca54c42013-06-27 17:41:38 -07001630 }
1631 }
1632
1633 @Override
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001634 public void setFirewallEnabled(boolean enabled) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001635 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001636 try {
Luke Huanga241db92018-07-31 20:15:24 +08001637 mNetdService.firewallSetFirewallType(
1638 enabled ? INetd.FIREWALL_WHITELIST : INetd.FIREWALL_BLACKLIST);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001639 mFirewallEnabled = enabled;
Luke Huanga241db92018-07-31 20:15:24 +08001640 } catch (RemoteException | ServiceSpecificException e) {
1641 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001642 }
1643 }
1644
1645 @Override
1646 public boolean isFirewallEnabled() {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001647 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001648 return mFirewallEnabled;
1649 }
1650
1651 @Override
Jeff Sharkey2c092982012-08-24 11:44:40 -07001652 public void setFirewallInterfaceRule(String iface, boolean allow) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001653 enforceSystemUid();
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001654 Preconditions.checkState(mFirewallEnabled);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001655 try {
Luke Huanga241db92018-07-31 20:15:24 +08001656 mNetdService.firewallSetInterfaceRule(iface,
1657 allow ? INetd.FIREWALL_RULE_ALLOW : INetd.FIREWALL_RULE_DENY);
1658 } catch (RemoteException | ServiceSpecificException e) {
1659 throw new IllegalStateException(e);
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001660 }
1661 }
1662
Lorenzo Colitti3fef7232016-04-29 18:00:03 +09001663 private void closeSocketsForFirewallChainLocked(int chain, String chainName) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001664 // UID ranges to close sockets on.
Lorenzo Colittib90ad242019-03-18 23:50:34 +09001665 UidRangeParcel[] ranges;
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001666 // UID ranges whose sockets we won't touch.
1667 int[] exemptUids;
1668
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001669 int numUids = 0;
Luke Huanga241db92018-07-31 20:15:24 +08001670 if (DBG) Slog.d(TAG, "Closing sockets after enabling chain " + chainName);
Remi NGUYEN VANdacee142019-02-13 18:28:35 +09001671 if (getFirewallType(chain) == FIREWALL_WHITELIST) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001672 // Close all sockets on all non-system UIDs...
Lorenzo Colittib90ad242019-03-18 23:50:34 +09001673 ranges = new UidRangeParcel[] {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001674 // TODO: is there a better way of finding all existing users? If so, we could
1675 // specify their ranges here.
Lorenzo Colittib90ad242019-03-18 23:50:34 +09001676 makeUidRangeParcel(Process.FIRST_APPLICATION_UID, Integer.MAX_VALUE),
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001677 };
1678 // ... except for the UIDs that have allow rules.
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001679 synchronized (mRulesLock) {
1680 final SparseIntArray rules = getUidFirewallRulesLR(chain);
1681 exemptUids = new int[rules.size()];
1682 for (int i = 0; i < exemptUids.length; i++) {
Remi NGUYEN VANdacee142019-02-13 18:28:35 +09001683 if (rules.valueAt(i) == FIREWALL_RULE_ALLOW) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001684 exemptUids[numUids] = rules.keyAt(i);
1685 numUids++;
1686 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001687 }
1688 }
1689 // Normally, whitelist chains only contain deny rules, so numUids == exemptUids.length.
1690 // But the code does not guarantee this in any way, and at least in one case - if we add
1691 // a UID rule to the firewall, and then disable the firewall - the chains can contain
1692 // the wrong type of rule. In this case, don't close connections that we shouldn't.
1693 //
1694 // TODO: tighten up this code by ensuring we never set the wrong type of rule, and
1695 // fix setFirewallEnabled to grab mQuotaLock and clear rules.
1696 if (numUids != exemptUids.length) {
1697 exemptUids = Arrays.copyOf(exemptUids, numUids);
1698 }
1699 } else {
1700 // Close sockets for every UID that has a deny rule...
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001701 synchronized (mRulesLock) {
1702 final SparseIntArray rules = getUidFirewallRulesLR(chain);
Lorenzo Colittib90ad242019-03-18 23:50:34 +09001703 ranges = new UidRangeParcel[rules.size()];
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001704 for (int i = 0; i < ranges.length; i++) {
Remi NGUYEN VANdacee142019-02-13 18:28:35 +09001705 if (rules.valueAt(i) == FIREWALL_RULE_DENY) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001706 int uid = rules.keyAt(i);
Lorenzo Colittib90ad242019-03-18 23:50:34 +09001707 ranges[numUids] = makeUidRangeParcel(uid, uid);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001708 numUids++;
1709 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001710 }
1711 }
1712 // As above; usually numUids == ranges.length, but not always.
1713 if (numUids != ranges.length) {
1714 ranges = Arrays.copyOf(ranges, numUids);
1715 }
1716 // ... with no exceptions.
1717 exemptUids = new int[0];
1718 }
1719
1720 try {
1721 mNetdService.socketDestroy(ranges, exemptUids);
1722 } catch(RemoteException | ServiceSpecificException e) {
1723 Slog.e(TAG, "Error closing sockets after enabling chain " + chainName + ": " + e);
1724 }
1725 }
1726
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001727 @Override
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001728 public void setFirewallChainEnabled(int chain, boolean enable) {
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001729 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001730 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001731 synchronized (mRulesLock) {
1732 if (getFirewallChainState(chain) == enable) {
1733 // All is the same, nothing to do. This relies on the fact that netd has child
1734 // chains default detached.
1735 return;
1736 }
1737 setFirewallChainState(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001738 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001739
Luke Huang615e1022018-10-25 11:54:05 +09001740 final String chainName = getFirewallChainName(chain);
Luke Huanga241db92018-07-31 20:15:24 +08001741 if (chain == FIREWALL_CHAIN_NONE) {
Luke Huang615e1022018-10-25 11:54:05 +09001742 throw new IllegalArgumentException("Bad child chain: " + chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001743 }
1744
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001745 try {
Luke Huanga241db92018-07-31 20:15:24 +08001746 mNetdService.firewallEnableChildChain(chain, enable);
1747 } catch (RemoteException | ServiceSpecificException e) {
1748 throw new IllegalStateException(e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001749 }
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001750
1751 // Close any sockets that were opened by the affected UIDs. This has to be done after
1752 // disabling network connectivity, in case they react to the socket close by reopening
1753 // the connection and race with the iptables commands that enable the firewall. All
1754 // whitelist and blacklist chains allow RSTs through.
1755 if (enable) {
Luke Huang615e1022018-10-25 11:54:05 +09001756 closeSocketsForFirewallChainLocked(chain, chainName);
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09001757 }
Amith Yamasani15e472352015-04-24 19:06:07 -07001758 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001759 }
1760
Luke Huanga241db92018-07-31 20:15:24 +08001761 private String getFirewallChainName(int chain) {
1762 switch (chain) {
1763 case FIREWALL_CHAIN_STANDBY:
1764 return FIREWALL_CHAIN_NAME_STANDBY;
1765 case FIREWALL_CHAIN_DOZABLE:
1766 return FIREWALL_CHAIN_NAME_DOZABLE;
1767 case FIREWALL_CHAIN_POWERSAVE:
1768 return FIREWALL_CHAIN_NAME_POWERSAVE;
1769 default:
1770 throw new IllegalArgumentException("Bad child chain: " + chain);
1771 }
1772 }
1773
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001774 private int getFirewallType(int chain) {
1775 switch (chain) {
1776 case FIREWALL_CHAIN_STANDBY:
Remi NGUYEN VANdacee142019-02-13 18:28:35 +09001777 return FIREWALL_BLACKLIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001778 case FIREWALL_CHAIN_DOZABLE:
Remi NGUYEN VANdacee142019-02-13 18:28:35 +09001779 return FIREWALL_WHITELIST;
Felipe Leme011b98f2016-02-10 17:28:31 -08001780 case FIREWALL_CHAIN_POWERSAVE:
Remi NGUYEN VANdacee142019-02-13 18:28:35 +09001781 return FIREWALL_WHITELIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001782 default:
Remi NGUYEN VANdacee142019-02-13 18:28:35 +09001783 return isFirewallEnabled() ? FIREWALL_WHITELIST : FIREWALL_BLACKLIST;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001784 }
1785 }
1786
1787 @Override
1788 public void setFirewallUidRules(int chain, int[] uids, int[] rules) {
1789 enforceSystemUid();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001790 synchronized (mQuotaLock) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001791 synchronized (mRulesLock) {
1792 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
1793 SparseIntArray newRules = new SparseIntArray();
1794 // apply new set of rules
1795 for (int index = uids.length - 1; index >= 0; --index) {
1796 int uid = uids[index];
1797 int rule = rules[index];
1798 updateFirewallUidRuleLocked(chain, uid, rule);
1799 newRules.put(uid, rule);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001800 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001801 // collect the rules to remove.
1802 SparseIntArray rulesToRemove = new SparseIntArray();
1803 for (int index = uidFirewallRules.size() - 1; index >= 0; --index) {
1804 int uid = uidFirewallRules.keyAt(index);
1805 if (newRules.indexOfKey(uid) < 0) {
1806 rulesToRemove.put(uid, FIREWALL_RULE_DEFAULT);
1807 }
1808 }
1809 // remove dead rules
1810 for (int index = rulesToRemove.size() - 1; index >= 0; --index) {
1811 int uid = rulesToRemove.keyAt(index);
1812 updateFirewallUidRuleLocked(chain, uid, FIREWALL_RULE_DEFAULT);
1813 }
Felipe Lemea701cad2016-05-12 09:58:14 -07001814 }
1815 try {
1816 switch (chain) {
1817 case FIREWALL_CHAIN_DOZABLE:
1818 mNetdService.firewallReplaceUidChain("fw_dozable", true, uids);
1819 break;
1820 case FIREWALL_CHAIN_STANDBY:
1821 mNetdService.firewallReplaceUidChain("fw_standby", false, uids);
1822 break;
1823 case FIREWALL_CHAIN_POWERSAVE:
1824 mNetdService.firewallReplaceUidChain("fw_powersave", true, uids);
1825 break;
1826 case FIREWALL_CHAIN_NONE:
1827 default:
1828 Slog.d(TAG, "setFirewallUidRules() called on invalid chain: " + chain);
1829 }
1830 } catch (RemoteException e) {
1831 Slog.w(TAG, "Error flushing firewall chain " + chain, e);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001832 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001833 }
1834 }
1835
1836 @Override
1837 public void setFirewallUidRule(int chain, int uid, int rule) {
1838 enforceSystemUid();
Felipe Lemea701cad2016-05-12 09:58:14 -07001839 synchronized (mQuotaLock) {
1840 setFirewallUidRuleLocked(chain, uid, rule);
1841 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001842 }
1843
Felipe Lemea701cad2016-05-12 09:58:14 -07001844 private void setFirewallUidRuleLocked(int chain, int uid, int rule) {
1845 if (updateFirewallUidRuleLocked(chain, uid, rule)) {
Luke Huanga241db92018-07-31 20:15:24 +08001846 final int ruleType = getFirewallRuleType(chain, rule);
Amith Yamasani15e472352015-04-24 19:06:07 -07001847 try {
Luke Huanga241db92018-07-31 20:15:24 +08001848 mNetdService.firewallSetUidRule(chain, uid, ruleType);
1849 } catch (RemoteException | ServiceSpecificException e) {
1850 throw new IllegalStateException(e);
Amith Yamasani15e472352015-04-24 19:06:07 -07001851 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001852 }
1853 }
1854
Felipe Lemea701cad2016-05-12 09:58:14 -07001855 // TODO: now that netd supports batching, NMS should not keep these data structures anymore...
1856 private boolean updateFirewallUidRuleLocked(int chain, int uid, int rule) {
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001857 synchronized (mRulesLock) {
1858 SparseIntArray uidFirewallRules = getUidFirewallRulesLR(chain);
Felipe Lemea701cad2016-05-12 09:58:14 -07001859
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001860 final int oldUidFirewallRule = uidFirewallRules.get(uid, FIREWALL_RULE_DEFAULT);
1861 if (DBG) {
1862 Slog.d(TAG, "oldRule = " + oldUidFirewallRule
1863 + ", newRule=" + rule + " for uid=" + uid + " on chain " + chain);
1864 }
1865 if (oldUidFirewallRule == rule) {
1866 if (DBG) Slog.d(TAG, "!!!!! Skipping change");
1867 // TODO: eventually consider throwing
1868 return false;
1869 }
Felipe Lemea701cad2016-05-12 09:58:14 -07001870
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001871 String ruleName = getFirewallRuleName(chain, rule);
1872 String oldRuleName = getFirewallRuleName(chain, oldUidFirewallRule);
Felipe Lemea701cad2016-05-12 09:58:14 -07001873
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001874 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
1875 uidFirewallRules.delete(uid);
1876 } else {
1877 uidFirewallRules.put(uid, rule);
1878 }
1879 return !ruleName.equals(oldRuleName);
Felipe Lemea701cad2016-05-12 09:58:14 -07001880 }
Felipe Lemea701cad2016-05-12 09:58:14 -07001881 }
1882
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001883 private @NonNull String getFirewallRuleName(int chain, int rule) {
1884 String ruleName;
Remi NGUYEN VANdacee142019-02-13 18:28:35 +09001885 if (getFirewallType(chain) == FIREWALL_WHITELIST) {
1886 if (rule == FIREWALL_RULE_ALLOW) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001887 ruleName = "allow";
1888 } else {
1889 ruleName = "deny";
1890 }
1891 } else { // Blacklist mode
Remi NGUYEN VANdacee142019-02-13 18:28:35 +09001892 if (rule == FIREWALL_RULE_DENY) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07001893 ruleName = "deny";
1894 } else {
1895 ruleName = "allow";
1896 }
1897 }
1898 return ruleName;
1899 }
1900
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001901 private @NonNull SparseIntArray getUidFirewallRulesLR(int chain) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001902 switch (chain) {
1903 case FIREWALL_CHAIN_STANDBY:
1904 return mUidFirewallStandbyRules;
1905 case FIREWALL_CHAIN_DOZABLE:
1906 return mUidFirewallDozableRules;
Felipe Leme011b98f2016-02-10 17:28:31 -08001907 case FIREWALL_CHAIN_POWERSAVE:
1908 return mUidFirewallPowerSaveRules;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001909 case FIREWALL_CHAIN_NONE:
1910 return mUidFirewallRules;
1911 default:
1912 throw new IllegalArgumentException("Unknown chain:" + chain);
1913 }
1914 }
1915
Luke Huanga241db92018-07-31 20:15:24 +08001916 private int getFirewallRuleType(int chain, int rule) {
Luke Huang615e1022018-10-25 11:54:05 +09001917 if (rule == NetworkPolicyManager.FIREWALL_RULE_DEFAULT) {
Remi NGUYEN VANdacee142019-02-13 18:28:35 +09001918 return getFirewallType(chain) == FIREWALL_WHITELIST
Luke Huang615e1022018-10-25 11:54:05 +09001919 ? INetd.FIREWALL_RULE_DENY : INetd.FIREWALL_RULE_ALLOW;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001920 }
Luke Huang615e1022018-10-25 11:54:05 +09001921 return rule;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001922 }
1923
Jeff Sharkeyf56e2432012-09-06 17:54:29 -07001924 private static void enforceSystemUid() {
1925 final int uid = Binder.getCallingUid();
1926 if (uid != Process.SYSTEM_UID) {
1927 throw new SecurityException("Only available to AID_SYSTEM");
1928 }
1929 }
1930
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001931 @Override
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001932 public void registerNetworkActivityListener(INetworkActivityListener listener) {
1933 mNetworkActivityListeners.register(listener);
1934 }
1935
1936 @Override
1937 public void unregisterNetworkActivityListener(INetworkActivityListener listener) {
1938 mNetworkActivityListeners.unregister(listener);
1939 }
1940
1941 @Override
1942 public boolean isNetworkActive() {
1943 synchronized (mNetworkActivityListeners) {
1944 return mNetworkActive || mActiveIdleTimers.isEmpty();
1945 }
1946 }
1947
1948 private void reportNetworkActive() {
1949 final int length = mNetworkActivityListeners.beginBroadcast();
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07001950 try {
1951 for (int i = 0; i < length; i++) {
1952 try {
1953 mNetworkActivityListeners.getBroadcastItem(i).onNetworkActive();
Felipe Leme03e689d2016-03-02 16:17:38 -08001954 } catch (RemoteException | RuntimeException e) {
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07001955 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001956 }
Robert Greenwalt2c9f5472014-04-21 14:50:28 -07001957 } finally {
1958 mNetworkActivityListeners.finishBroadcast();
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001959 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001960 }
1961
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001962 @Override
1963 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001964 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001965
Dianne Hackborn2ffa11e2014-04-21 15:56:18 -07001966 pw.print("mMobileActivityFromRadio="); pw.print(mMobileActivityFromRadio);
1967 pw.print(" mLastPowerStateFromRadio="); pw.println(mLastPowerStateFromRadio);
1968 pw.print("mNetworkActive="); pw.println(mNetworkActive);
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001969
1970 synchronized (mQuotaLock) {
Jeff Sharkeyb24a7852012-05-01 15:19:37 -07001971 pw.print("Active quota ifaces: "); pw.println(mActiveQuotas.toString());
1972 pw.print("Active alert ifaces: "); pw.println(mActiveAlerts.toString());
Felipe Leme65be3022016-03-22 14:53:13 -07001973 pw.print("Data saver mode: "); pw.println(mDataSaverMode);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001974 synchronized (mRulesLock) {
1975 dumpUidRuleOnQuotaLocked(pw, "blacklist", mUidRejectOnMetered);
1976 dumpUidRuleOnQuotaLocked(pw, "whitelist", mUidAllowOnMetered);
1977 }
Jeff Sharkey47eb1022011-08-25 17:48:52 -07001978 }
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07001979
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001980 synchronized (mRulesLock) {
Felipe Leme011b98f2016-02-10 17:28:31 -08001981 dumpUidFirewallRule(pw, "", mUidFirewallRules);
Amith Yamasani15e472352015-04-24 19:06:07 -07001982
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001983 pw.print("UID firewall standby chain enabled: "); pw.println(
1984 getFirewallChainState(FIREWALL_CHAIN_STANDBY));
Felipe Leme011b98f2016-02-10 17:28:31 -08001985 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_STANDBY, mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001986
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001987 pw.print("UID firewall dozable chain enabled: "); pw.println(
1988 getFirewallChainState(FIREWALL_CHAIN_DOZABLE));
Felipe Leme011b98f2016-02-10 17:28:31 -08001989 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_DOZABLE, mUidFirewallDozableRules);
Felipe Leme011b98f2016-02-10 17:28:31 -08001990
Sudheer Shanka62f5c172017-03-17 16:25:55 -07001991 pw.println("UID firewall powersave chain enabled: " +
1992 getFirewallChainState(FIREWALL_CHAIN_POWERSAVE));
Felipe Leme011b98f2016-02-10 17:28:31 -08001993 dumpUidFirewallRule(pw, FIREWALL_CHAIN_NAME_POWERSAVE, mUidFirewallPowerSaveRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001994 }
1995
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001996 synchronized (mIdleTimerLock) {
1997 pw.println("Idle timers:");
1998 for (HashMap.Entry<String, IdleTimerParams> ent : mActiveIdleTimers.entrySet()) {
1999 pw.print(" "); pw.print(ent.getKey()); pw.println(":");
2000 IdleTimerParams params = ent.getValue();
2001 pw.print(" timeout="); pw.print(params.timeout);
2002 pw.print(" type="); pw.print(params.type);
2003 pw.print(" networkCount="); pw.println(params.networkCount);
2004 }
2005 }
2006
Jeff Sharkeyc268f0b2012-08-24 10:25:31 -07002007 pw.print("Firewall enabled: "); pw.println(mFirewallEnabled);
Felipe Leme65be3022016-03-22 14:53:13 -07002008 pw.print("Netd service status: " );
2009 if (mNetdService == null) {
2010 pw.println("disconnected");
2011 } else {
2012 try {
2013 final boolean alive = mNetdService.isAlive();
2014 pw.println(alive ? "alive": "dead");
2015 } catch (RemoteException e) {
2016 pw.println("unreachable");
2017 }
2018 }
2019 }
2020
2021 private void dumpUidRuleOnQuotaLocked(PrintWriter pw, String name, SparseBooleanArray list) {
2022 pw.print("UID bandwith control ");
2023 pw.print(name);
2024 pw.print(" rule: [");
2025 final int size = list.size();
2026 for (int i = 0; i < size; i++) {
2027 pw.print(list.keyAt(i));
2028 if (i < size - 1) pw.print(",");
2029 }
2030 pw.println("]");
Jeff Sharkey47eb1022011-08-25 17:48:52 -07002031 }
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002032
Felipe Leme011b98f2016-02-10 17:28:31 -08002033 private void dumpUidFirewallRule(PrintWriter pw, String name, SparseIntArray rules) {
Lorenzo Colitti4cb42402016-04-24 12:52:00 +09002034 pw.print("UID firewall ");
Felipe Leme011b98f2016-02-10 17:28:31 -08002035 pw.print(name);
2036 pw.print(" rule: [");
2037 final int size = rules.size();
2038 for (int i = 0; i < size; i++) {
2039 pw.print(rules.keyAt(i));
2040 pw.print(":");
2041 pw.print(rules.valueAt(i));
2042 if (i < size - 1) pw.print(",");
2043 }
2044 pw.println("]");
2045 }
2046
Robert Greenwalt568891d2014-04-04 13:38:00 -07002047 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002048 public void createPhysicalNetwork(int netId, int permission) {
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002049 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2050
2051 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002052 mNetdService.networkCreatePhysical(netId, permission);
2053 } catch (RemoteException | ServiceSpecificException e) {
2054 throw new IllegalStateException(e);
Robert Greenwalt9ba9c582014-03-19 17:56:12 -07002055 }
2056 }
2057
Robert Greenwalt568891d2014-04-04 13:38:00 -07002058 @Override
ckenbed368e2018-12-05 20:32:30 +09002059 public void createVirtualNetwork(int netId, boolean secure) {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002060 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2061
2062 try {
ckenbed368e2018-12-05 20:32:30 +09002063 mNetdService.networkCreateVpn(netId, secure);
Luke Huang8a462ec2018-08-24 20:33:16 +08002064 } catch (RemoteException | ServiceSpecificException e) {
2065 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002066 }
2067 }
2068
2069 @Override
Paul Jensen992f2522014-04-28 10:33:11 -04002070 public void addInterfaceToNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002071 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, netId, iface);
Paul Jensen992f2522014-04-28 10:33:11 -04002072 }
2073
2074 @Override
2075 public void removeInterfaceFromNetwork(String iface, int netId) {
Luke Huang8a462ec2018-08-24 20:33:16 +08002076 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, netId, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002077 }
Paul Jensen992f2522014-04-28 10:33:11 -04002078
Luke Huang8a462ec2018-08-24 20:33:16 +08002079 private void modifyInterfaceInNetwork(boolean add, int netId, String iface) {
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002080 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Paul Jensen992f2522014-04-28 10:33:11 -04002081 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002082 if (add) {
2083 mNetdService.networkAddInterface(netId, iface);
2084 } else {
2085 mNetdService.networkRemoveInterface(netId, iface);
2086 }
2087 } catch (RemoteException | ServiceSpecificException e) {
2088 throw new IllegalStateException(e);
Paul Jensen992f2522014-04-28 10:33:11 -04002089 }
2090 }
2091
2092 @Override
Robert Greenwalt913c8952014-04-07 17:36:35 -07002093 public void addLegacyRouteForNetId(int netId, RouteInfo routeInfo, int uid) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002094 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2095
Sreeram Ramachandrancc91c7b2014-06-03 18:41:43 -07002096 final LinkAddress la = routeInfo.getDestinationLinkAddress();
Luke Huang8a462ec2018-08-24 20:33:16 +08002097 final String ifName = routeInfo.getInterface();
2098 final String dst = la.toString();
2099 final String nextHop;
Robert Greenwalt568891d2014-04-04 13:38:00 -07002100
Luke Huang8a462ec2018-08-24 20:33:16 +08002101 if (routeInfo.hasGateway()) {
2102 nextHop = routeInfo.getGateway().getHostAddress();
2103 } else {
2104 nextHop = "";
2105 }
Robert Greenwalt568891d2014-04-04 13:38:00 -07002106 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002107 mNetdService.networkAddLegacyRoute(netId, ifName, dst, nextHop, uid);
2108 } catch (RemoteException | ServiceSpecificException e) {
2109 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002110 }
2111 }
2112
2113 @Override
Sreeram Ramachandranf047f2a2014-04-15 16:04:26 -07002114 public void setDefaultNetId(int netId) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002115 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2116
2117 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002118 mNetdService.networkSetDefault(netId);
2119 } catch (RemoteException | ServiceSpecificException e) {
2120 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002121 }
2122 }
2123
2124 @Override
2125 public void clearDefaultNetId() {
2126 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2127
2128 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002129 mNetdService.networkClearDefault();
2130 } catch (RemoteException | ServiceSpecificException e) {
2131 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002132 }
2133 }
2134
2135 @Override
Luke Huang8a462ec2018-08-24 20:33:16 +08002136 public void setNetworkPermission(int netId, int permission) {
Paul Jensen487ffe72015-07-24 15:57:11 -04002137 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2138
2139 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002140 mNetdService.networkSetPermissionForNetwork(netId, permission);
2141 } catch (RemoteException | ServiceSpecificException e) {
2142 throw new IllegalStateException(e);
Paul Jensen487ffe72015-07-24 15:57:11 -04002143 }
2144 }
2145
Luke Huang8a462ec2018-08-24 20:33:16 +08002146 private int parsePermission(String permission) {
2147 if (permission.equals("NETWORK")) {
2148 return INetd.PERMISSION_NETWORK;
2149 }
2150 if (permission.equals("SYSTEM")) {
2151 return INetd.PERMISSION_SYSTEM;
2152 }
2153 return INetd.PERMISSION_NONE;
2154 }
Paul Jensen487ffe72015-07-24 15:57:11 -04002155
2156 @Override
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07002157 public void setPermission(String permission, int[] uids) {
Robert Greenwalt568891d2014-04-04 13:38:00 -07002158 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2159
Luke Huang8a462ec2018-08-24 20:33:16 +08002160 try {
2161 mNetdService.networkSetPermissionForUser(parsePermission(permission), uids);
2162 } catch (RemoteException | ServiceSpecificException e) {
2163 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002164 }
2165 }
2166
2167 @Override
2168 public void clearPermission(int[] uids) {
2169 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2170
Luke Huang8a462ec2018-08-24 20:33:16 +08002171 try {
2172 mNetdService.networkClearPermissionForUser(uids);
2173 } catch (RemoteException | ServiceSpecificException e) {
2174 throw new IllegalStateException(e);
Robert Greenwalt568891d2014-04-04 13:38:00 -07002175 }
2176 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002177
2178 @Override
2179 public void allowProtect(int uid) {
2180 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2181
2182 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002183 mNetdService.networkSetProtectAllow(uid);
2184 } catch (RemoteException | ServiceSpecificException e) {
2185 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002186 }
2187 }
2188
2189 @Override
2190 public void denyProtect(int uid) {
2191 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2192
2193 try {
Luke Huang8a462ec2018-08-24 20:33:16 +08002194 mNetdService.networkSetProtectDeny(uid);
2195 } catch (RemoteException | ServiceSpecificException e) {
2196 throw new IllegalStateException(e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002197 }
2198 }
2199
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002200 @Override
2201 public void addInterfaceToLocalNetwork(String iface, List<RouteInfo> routes) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002202 modifyInterfaceInNetwork(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002203
2204 for (RouteInfo route : routes) {
2205 if (!route.isDefaultRoute()) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002206 modifyRoute(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID, route);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002207 }
2208 }
Jimmy Chen086779d2019-03-07 14:15:36 +08002209
2210 // IPv6 link local should be activated always.
2211 modifyRoute(MODIFY_OPERATION_ADD, INetd.LOCAL_NET_ID,
2212 new RouteInfo(new IpPrefix("fe80::/64"), null, iface));
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002213 }
2214
2215 @Override
2216 public void removeInterfaceFromLocalNetwork(String iface) {
Luke Huang706d7ab2018-10-16 15:42:15 +08002217 modifyInterfaceInNetwork(MODIFY_OPERATION_REMOVE, INetd.LOCAL_NET_ID, iface);
Sreeram Ramachandrana77760d2014-07-17 17:09:07 -07002218 }
Erik Kline6599ee82016-07-17 21:28:39 +09002219
2220 @Override
2221 public int removeRoutesFromLocalNetwork(List<RouteInfo> routes) {
2222 int failures = 0;
2223
2224 for (RouteInfo route : routes) {
2225 try {
Luke Huang706d7ab2018-10-16 15:42:15 +08002226 modifyRoute(MODIFY_OPERATION_REMOVE, INetd.LOCAL_NET_ID, route);
Erik Kline6599ee82016-07-17 21:28:39 +09002227 } catch (IllegalStateException e) {
2228 failures++;
2229 }
2230 }
2231
2232 return failures;
2233 }
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002234
Sudheer Shankab8f23162017-08-04 13:30:10 -07002235 @Override
2236 public boolean isNetworkRestricted(int uid) {
2237 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2238 return isNetworkRestrictedInternal(uid);
2239 }
2240
2241 private boolean isNetworkRestrictedInternal(int uid) {
2242 synchronized (mRulesLock) {
2243 if (getFirewallChainState(FIREWALL_CHAIN_STANDBY)
2244 && mUidFirewallStandbyRules.get(uid) == FIREWALL_RULE_DENY) {
2245 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of app standby mode");
2246 return true;
2247 }
2248 if (getFirewallChainState(FIREWALL_CHAIN_DOZABLE)
2249 && mUidFirewallDozableRules.get(uid) != FIREWALL_RULE_ALLOW) {
2250 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of device idle mode");
2251 return true;
2252 }
2253 if (getFirewallChainState(FIREWALL_CHAIN_POWERSAVE)
2254 && mUidFirewallPowerSaveRules.get(uid) != FIREWALL_RULE_ALLOW) {
2255 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of power saver mode");
2256 return true;
2257 }
2258 if (mUidRejectOnMetered.get(uid)) {
2259 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of no metered data"
2260 + " in the background");
2261 return true;
2262 }
2263 if (mDataSaverMode && !mUidAllowOnMetered.get(uid)) {
2264 if (DBG) Slog.d(TAG, "Uid " + uid + " restricted because of data saver mode");
2265 return true;
2266 }
2267 return false;
2268 }
2269 }
2270
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002271 private void setFirewallChainState(int chain, boolean state) {
2272 synchronized (mRulesLock) {
2273 mFirewallChainStates.put(chain, state);
2274 }
2275 }
2276
2277 private boolean getFirewallChainState(int chain) {
2278 synchronized (mRulesLock) {
2279 return mFirewallChainStates.get(chain);
2280 }
2281 }
2282
2283 @VisibleForTesting
2284 class LocalService extends NetworkManagementInternal {
2285 @Override
2286 public boolean isNetworkRestrictedForUid(int uid) {
Sudheer Shankab8f23162017-08-04 13:30:10 -07002287 return isNetworkRestrictedInternal(uid);
Sudheer Shanka62f5c172017-03-17 16:25:55 -07002288 }
2289 }
2290
2291 @VisibleForTesting
2292 Injector getInjector() {
2293 return new Injector();
2294 }
2295
2296 @VisibleForTesting
2297 class Injector {
2298 void setDataSaverMode(boolean dataSaverMode) {
2299 mDataSaverMode = dataSaverMode;
2300 }
2301
2302 void setFirewallChainState(int chain, boolean state) {
2303 NetworkManagementService.this.setFirewallChainState(chain, state);
2304 }
2305
2306 void setFirewallRule(int chain, int uid, int rule) {
2307 synchronized (mRulesLock) {
2308 getUidFirewallRulesLR(chain).put(uid, rule);
2309 }
2310 }
2311
2312 void setUidOnMeteredNetworkList(boolean blacklist, int uid, boolean enable) {
2313 synchronized (mRulesLock) {
2314 if (blacklist) {
2315 mUidRejectOnMetered.put(uid, enable);
2316 } else {
2317 mUidAllowOnMetered.put(uid, enable);
2318 }
2319 }
2320 }
2321
2322 void reset() {
2323 synchronized (mRulesLock) {
2324 setDataSaverMode(false);
2325 final int[] chains = {
2326 FIREWALL_CHAIN_DOZABLE,
2327 FIREWALL_CHAIN_STANDBY,
2328 FIREWALL_CHAIN_POWERSAVE
2329 };
2330 for (int chain : chains) {
2331 setFirewallChainState(chain, false);
2332 getUidFirewallRulesLR(chain).clear();
2333 }
2334 mUidAllowOnMetered.clear();
2335 mUidRejectOnMetered.clear();
2336 }
2337 }
2338 }
San Mehat873f2142010-01-14 10:25:07 -08002339}