blob: 8a93e4de73381765c3b52937a2b7015c459d2c40 [file] [log] [blame]
markchien74a4fa92019-09-09 20:50:49 +08001/*
2 * Copyright (C) 2016 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 android.net.ip;
18
markchien6cf0e552019-12-06 15:24:53 +080019import static android.net.RouteInfo.RTN_UNICAST;
Mark49649c92023-03-15 06:45:04 +000020import static android.net.TetheringManager.CONNECTIVITY_SCOPE_GLOBAL;
21import static android.net.TetheringManager.CONNECTIVITY_SCOPE_LOCAL;
Mark74461fc2022-12-14 08:49:40 +000022import static android.net.TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
23import static android.net.TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
24import static android.net.TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
25import static android.net.TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
26import static android.net.TetheringManager.TETHER_ERROR_NO_ERROR;
27import static android.net.TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
28import static android.net.TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien245352e2020-02-27 20:27:18 +080029import static android.net.TetheringManager.TetheringRequest.checkStaticAddressConfiguration;
markchien74a4fa92019-09-09 20:50:49 +080030import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
markchien74a4fa92019-09-09 20:50:49 +080031import static android.net.util.NetworkConstants.asByte;
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +090032import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080033
Chalard Jean78701642020-07-31 20:00:30 +090034import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH;
Xiao Ma1f993302023-08-09 18:55:49 +090035import static com.android.net.module.util.NetworkStackConstants.RFC7421_PREFIX_LENGTH;
markchien7dc1b4d2021-07-13 17:12:56 +080036import static com.android.networkstack.tethering.UpstreamNetworkState.isVcnInterface;
markchiend02f9af2021-11-04 11:26:03 +080037import static com.android.networkstack.tethering.util.PrefixUtils.asIpPrefix;
38import static com.android.networkstack.tethering.util.TetheringMessageBase.BASE_IPSERVER;
Chalard Jean78701642020-07-31 20:00:30 +090039
markchien74a4fa92019-09-09 20:50:49 +080040import android.net.INetd;
41import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080042import android.net.IpPrefix;
43import android.net.LinkAddress;
44import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090045import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080046import android.net.RouteInfo;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090047import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080048import android.net.TetheringManager;
markchienf053e4b2020-03-16 21:49:48 +080049import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090050import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080051import android.net.dhcp.DhcpServerCallbacks;
52import android.net.dhcp.DhcpServingParamsParcel;
53import android.net.dhcp.DhcpServingParamsParcelExt;
Xiao Ma49889dd2020-04-03 17:01:33 +090054import android.net.dhcp.IDhcpEventCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080055import android.net.dhcp.IDhcpServer;
56import android.net.ip.RouterAdvertisementDaemon.RaParams;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090057import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080058import android.os.Looper;
59import android.os.Message;
60import android.os.RemoteException;
61import android.os.ServiceSpecificException;
62import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080063import android.util.SparseArray;
64
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090065import androidx.annotation.NonNull;
Xiao Ma4455d6b2020-04-09 10:13:44 +090066import androidx.annotation.Nullable;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090067
KH Shi3f738fc2023-05-23 22:37:17 +080068import com.android.internal.annotations.VisibleForTesting;
markchien74a4fa92019-09-09 20:50:49 +080069import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080070import com.android.internal.util.State;
71import com.android.internal.util.StateMachine;
markchien932df542021-08-12 13:56:43 +080072import com.android.modules.utils.build.SdkLevel;
Patrick Rohr9f371f02022-03-04 15:14:27 +010073import com.android.net.module.util.InterfaceParams;
Chalard Jeanadcec9e2021-10-29 15:57:22 +090074import com.android.net.module.util.NetdUtils;
Patrick Rohrb873e252022-06-16 16:38:43 -070075import com.android.net.module.util.SharedLog;
Xiao Mac81c0662022-06-17 14:58:03 +090076import com.android.net.module.util.ip.InterfaceController;
77import com.android.net.module.util.ip.IpNeighborMonitor;
78import com.android.net.module.util.ip.IpNeighborMonitor.NeighborEvent;
Hungming Chen68f1c2a2020-03-12 21:24:01 +080079import com.android.networkstack.tethering.BpfCoordinator;
Hungming Chend71c06e2020-12-21 19:39:49 +080080import com.android.networkstack.tethering.BpfCoordinator.ClientInfo;
KH Shi59ad35e2023-08-15 07:13:00 +000081import com.android.networkstack.tethering.BpfCoordinator.Ipv6DownstreamRule;
markchienc9daba32020-02-12 00:19:21 +080082import com.android.networkstack.tethering.PrivateAddressCoordinator;
markchienb961d3d2022-02-26 00:39:06 +080083import com.android.networkstack.tethering.TetheringConfiguration;
Wayne Ma6cd440f2022-03-14 18:04:33 +080084import com.android.networkstack.tethering.metrics.TetheringMetrics;
markchiend02f9af2021-11-04 11:26:03 +080085import com.android.networkstack.tethering.util.InterfaceSet;
86import com.android.networkstack.tethering.util.PrefixUtils;
markchien74a4fa92019-09-09 20:50:49 +080087
88import java.net.Inet4Address;
89import java.net.Inet6Address;
markchien74a4fa92019-09-09 20:50:49 +080090import java.net.UnknownHostException;
91import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090092import java.util.Arrays;
KH Shi3f738fc2023-05-23 22:37:17 +080093import java.util.Collection;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090094import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080095import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090096import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080097import java.util.Objects;
98import java.util.Random;
99import java.util.Set;
100
101/**
102 * Provides the interface to IP-layer serving functionality for a given network
103 * interface, e.g. for tethering or "local-only hotspot" mode.
104 *
105 * @hide
106 */
107public class IpServer extends StateMachine {
108 public static final int STATE_UNAVAILABLE = 0;
109 public static final int STATE_AVAILABLE = 1;
110 public static final int STATE_TETHERED = 2;
111 public static final int STATE_LOCAL_ONLY = 3;
112
113 /** Get string name of |state|.*/
114 public static String getStateString(int state) {
115 switch (state) {
116 case STATE_UNAVAILABLE: return "UNAVAILABLE";
117 case STATE_AVAILABLE: return "AVAILABLE";
118 case STATE_TETHERED: return "TETHERED";
119 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
120 }
121 return "UNKNOWN: " + state;
122 }
123
124 private static final byte DOUG_ADAMS = (byte) 42;
125
markchien74a4fa92019-09-09 20:50:49 +0800126 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800127 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800128
129 // TODO: have this configurable
130 private static final int DHCP_LEASE_TIME_SECS = 3600;
131
KH Shi701c3ca2023-08-16 13:19:33 +0000132 private static final int NO_UPSTREAM = 0;
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900133 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
134
markchien74a4fa92019-09-09 20:50:49 +0800135 private static final String TAG = "IpServer";
136 private static final boolean DBG = false;
137 private static final boolean VDBG = false;
138 private static final Class[] sMessageClasses = {
139 IpServer.class
140 };
141 private static final SparseArray<String> sMagicDecoderRing =
142 MessageUtils.findMessageNames(sMessageClasses);
143
144 /** IpServer callback. */
145 public static class Callback {
146 /**
147 * Notify that |who| has changed its tethering state.
148 *
149 * @param who the calling instance of IpServer
150 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800151 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800152 */
markchien9d353822019-12-16 20:15:20 +0800153 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800154
155 /**
156 * Notify that |who| has new LinkProperties.
157 *
158 * @param who the calling instance of IpServer
159 * @param newLp the new LinkProperties to report
160 */
markchien9d353822019-12-16 20:15:20 +0800161 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900162
163 /**
164 * Notify that the DHCP leases changed in one of the IpServers.
165 */
166 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800167
168 /**
169 * Request Tethering change.
170 *
171 * @param tetheringType the downstream type of this IpServer.
172 * @param enabled enable or disable tethering.
173 */
174 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800175 }
176
177 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800178 public abstract static class Dependencies {
Tyler Wear90e40632020-03-13 11:38:38 -0700179 /**
180 * Create a DadProxy instance to be used by IpServer.
181 * To support multiple tethered interfaces concurrently DAD Proxy
182 * needs to be supported per IpServer instead of per upstream.
183 */
184 public DadProxy getDadProxy(Handler handler, InterfaceParams ifParams) {
185 return new DadProxy(handler, ifParams);
186 }
187
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900188 /** Create an IpNeighborMonitor to be used by this IpServer */
189 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
190 IpNeighborMonitor.NeighborEventConsumer consumer) {
191 return new IpNeighborMonitor(handler, log, consumer);
192 }
193
markchien74a4fa92019-09-09 20:50:49 +0800194 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
195 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
196 return new RouterAdvertisementDaemon(ifParams);
197 }
198
199 /** Get |ifName|'s interface information.*/
200 public InterfaceParams getInterfaceParams(String ifName) {
201 return InterfaceParams.getByName(ifName);
202 }
203
markchien9d353822019-12-16 20:15:20 +0800204 /** Create a DhcpServer instance to be used by IpServer. */
205 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
206 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800207 }
208
markchien74a4fa92019-09-09 20:50:49 +0800209 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800210 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800211 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800212 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800213 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800214 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800215 // notification from the {@link Tethering.TetherMainSM} that it had trouble enabling IP
216 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800217 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800218 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble disabling IP
219 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800220 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800221 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble starting
222 // tethering
markchien6cf0e552019-12-06 15:24:53 +0800223 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800224 // notification from the {@link Tethering.TetherMainSM} that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800225 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800226 // notification from the {@link Tethering.TetherMainSM} that it had trouble setting the DNS
227 // forwarders
markchien6cf0e552019-12-06 15:24:53 +0800228 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800229 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800230 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800231 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800232 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900233 // new neighbor cache entry on our interface
234 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900235 // request from DHCP server that it wants to have a new prefix
236 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800237 // request from PrivateAddressCoordinator to restart tethering.
238 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
markchien74a4fa92019-09-09 20:50:49 +0800239
240 private final State mInitialState;
241 private final State mLocalHotspotState;
242 private final State mTetheredState;
243 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800244 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800245
246 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800247 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800248 @NonNull
249 private final BpfCoordinator mBpfCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800250 private final Callback mCallback;
251 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800252 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800253
254 private final String mIfaceName;
255 private final int mInterfaceType;
256 private final LinkProperties mLinkProperties;
257 private final boolean mUsingLegacyDhcp;
markchienfb65dfe2022-02-25 23:14:58 +0800258 private final int mP2pLeasesSubnetPrefixLength;
markchien74a4fa92019-09-09 20:50:49 +0800259
260 private final Dependencies mDeps;
261
262 private int mLastError;
263 private int mServingMode;
264 private InterfaceSet mUpstreamIfaceSet; // may change over time
KH Shi701c3ca2023-08-16 13:19:33 +0000265 // mInterfaceParams can't be final now because IpServer will be created when receives
266 // WIFI_AP_STATE_CHANGED broadcasts or when it detects that the wifi interface has come up.
267 // In the latter case, the interface is not fully initialized and the MAC address might not
268 // be correct (it will be set with a randomized MAC address later).
269 // TODO: Consider create the IpServer only when tethering want to enable it, then we can
270 // make mInterfaceParams final.
markchien74a4fa92019-09-09 20:50:49 +0800271 private InterfaceParams mInterfaceParams;
272 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
273 // properties are those selected by the IPv6TetheringCoordinator and relayed
274 // to us. By comparison, mLinkProperties contains the addresses and directly
275 // connected routes that have been formed from these properties iff. we have
276 // succeeded in configuring them and are able to announce them within Router
277 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
278 private LinkProperties mLastIPv6LinkProperties;
279 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700280 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800281
282 // To be accessed only on the handler thread
283 private int mDhcpServerStartIndex = 0;
284 private IDhcpServer mDhcpServer;
285 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800286
287 private LinkAddress mStaticIpv4ServerAddr;
288 private LinkAddress mStaticIpv4ClientAddr;
289
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900290 @NonNull
291 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800292
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900293 private int mLastIPv6UpstreamIfindex = 0;
KH Shi68770342023-08-17 14:34:31 +0000294 private boolean mUpstreamSupportsBpf = false;
KH Shi3f738fc2023-05-23 22:37:17 +0800295 @NonNull
296 private Set<IpPrefix> mLastIPv6UpstreamPrefixes = Collections.emptySet();
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900297
298 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
299 public void accept(NeighborEvent e) {
300 sendMessage(CMD_NEIGHBOR_EVENT, e);
301 }
302 }
303
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900304 private final IpNeighborMonitor mIpNeighborMonitor;
305
markchienc9daba32020-02-12 00:19:21 +0800306 private LinkAddress mIpv4Address;
307
Wayne Ma6cd440f2022-03-14 18:04:33 +0800308 private final TetheringMetrics mTetheringMetrics;
309
Hungming Chen5bc3af92020-05-12 19:15:24 +0800310 // TODO: Add a dependency object to pass the data members or variables from the tethering
311 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800312 public IpServer(
313 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800314 INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
markchienb961d3d2022-02-26 00:39:06 +0800315 TetheringConfiguration config, PrivateAddressCoordinator addressCoordinator,
Wayne Ma6cd440f2022-03-14 18:04:33 +0800316 TetheringMetrics tetheringMetrics, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800317 super(ifaceName, looper);
318 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800319 mNetd = netd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800320 mBpfCoordinator = coordinator;
markchien74a4fa92019-09-09 20:50:49 +0800321 mCallback = callback;
322 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
323 mIfaceName = ifaceName;
324 mInterfaceType = interfaceType;
325 mLinkProperties = new LinkProperties();
markchienb961d3d2022-02-26 00:39:06 +0800326 mUsingLegacyDhcp = config.useLegacyDhcpServer();
markchienfb65dfe2022-02-25 23:14:58 +0800327 mP2pLeasesSubnetPrefixLength = config.getP2pLeasesSubnetPrefixLength();
markchienc9daba32020-02-12 00:19:21 +0800328 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800329 mDeps = deps;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800330 mTetheringMetrics = tetheringMetrics;
markchien74a4fa92019-09-09 20:50:49 +0800331 resetLinkProperties();
Mark74461fc2022-12-14 08:49:40 +0000332 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800333 mServingMode = STATE_AVAILABLE;
334
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900335 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
336 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800337
KH Shie4d549a2023-08-28 09:57:34 +0000338 // IP neighbor monitor monitors the neighbor events for adding/removing IPv6 downstream rule
339 // per client. If BPF offload is not supported, don't start listening for neighbor events.
340 if (mBpfCoordinator.isUsingBpfOffload() && !mIpNeighborMonitor.start()) {
Hungming Chen5bc3af92020-05-12 19:15:24 +0800341 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900342 }
343
markchien74a4fa92019-09-09 20:50:49 +0800344 mInitialState = new InitialState();
345 mLocalHotspotState = new LocalHotspotState();
346 mTetheredState = new TetheredState();
347 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800348 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800349 addState(mInitialState);
350 addState(mLocalHotspotState);
351 addState(mTetheredState);
markchienc9daba32020-02-12 00:19:21 +0800352 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800353 addState(mUnavailableState);
354
355 setInitialState(mInitialState);
356 }
357
358 /** Interface name which IpServer served.*/
359 public String interfaceName() {
360 return mIfaceName;
361 }
362
363 /**
markchien9b4d7572019-12-25 19:40:32 +0800364 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800365 */
366 public int interfaceType() {
367 return mInterfaceType;
368 }
369
370 /** Last error from this IpServer. */
371 public int lastError() {
372 return mLastError;
373 }
374
375 /** Serving mode is the current state of IpServer state machine. */
376 public int servingMode() {
377 return mServingMode;
378 }
379
380 /** The properties of the network link which IpServer is serving. */
381 public LinkProperties linkProperties() {
382 return new LinkProperties(mLinkProperties);
383 }
384
markchienc9daba32020-02-12 00:19:21 +0800385 /** The address which IpServer is using. */
386 public LinkAddress getAddress() {
387 return mIpv4Address;
388 }
389
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900390 /**
391 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
392 * thread.
393 */
394 public List<TetheredClient> getAllLeases() {
395 return Collections.unmodifiableList(mDhcpLeases);
396 }
397
Marka5424582022-12-01 13:46:32 +0000398 /** Enable this IpServer. IpServer state machine will be tethered or localHotspot state. */
399 public void enable(final int requestedState, final TetheringRequestParcel request) {
400 sendMessage(CMD_TETHER_REQUESTED, requestedState, 0, request);
401 }
402
markchien74a4fa92019-09-09 20:50:49 +0800403 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
404 public void stop() {
405 sendMessage(CMD_INTERFACE_DOWN);
406 }
407
408 /**
409 * Tethering is canceled. IpServer state machine will be available and wait for
410 * next tethering request.
411 */
412 public void unwanted() {
413 sendMessage(CMD_TETHER_UNREQUESTED);
414 }
415
416 /** Internals. */
417
Mark49649c92023-03-15 06:45:04 +0000418 private boolean startIPv4(int scope) {
419 return configureIPv4(true, scope);
markchien74a4fa92019-09-09 20:50:49 +0800420 }
421
422 /**
423 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
424 * handler.
425 *
426 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
427 * with different implementations of the callback, to differentiate handling of success/error in
428 * each call.
429 */
430 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
431 @Override
432 public void onStatusAvailable(int statusCode) {
433 getHandler().post(() -> callback(statusCode));
434 }
435
436 public abstract void callback(int statusCode);
437
438 @Override
439 public int getInterfaceVersion() {
440 return this.VERSION;
441 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900442
443 @Override
444 public String getInterfaceHash() {
445 return this.HASH;
446 }
markchien74a4fa92019-09-09 20:50:49 +0800447 }
448
449 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
450 private final int mStartIndex;
451
452 private DhcpServerCallbacksImpl(int startIndex) {
453 mStartIndex = startIndex;
454 }
455
456 @Override
457 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
458 getHandler().post(() -> {
459 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
460 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800461 // This start request is obsolete. Explicitly stop the DHCP server to shut
462 // down its thread. When the |server| binder token goes out of scope, the
463 // garbage collector will finalize it, which causes the network stack process
464 // garbage collector to collect the server itself.
465 try {
466 server.stop(null);
467 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800468 return;
469 }
470
471 if (statusCode != STATUS_SUCCESS) {
472 mLog.e("Error obtaining DHCP server: " + statusCode);
473 handleError();
474 return;
475 }
476
477 mDhcpServer = server;
478 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900479 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800480 @Override
481 public void callback(int startStatusCode) {
482 if (startStatusCode != STATUS_SUCCESS) {
483 mLog.e("Error starting DHCP server: " + startStatusCode);
484 handleError();
485 }
486 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900487 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800488 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800489 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800490 }
491 });
492 }
493
494 private void handleError() {
Mark74461fc2022-12-14 08:49:40 +0000495 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800496 transitionTo(mInitialState);
497 }
498 }
499
Xiao Ma4455d6b2020-04-09 10:13:44 +0900500 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900501 @Override
502 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
503 final ArrayList<TetheredClient> leases = new ArrayList<>();
504 for (DhcpLeaseParcelable lease : leaseParcelables) {
505 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900506 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
507 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
508 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900509
510 final MacAddress macAddress;
511 try {
512 macAddress = MacAddress.fromBytes(lease.hwAddr);
513 } catch (IllegalArgumentException e) {
514 Log.wtf(TAG, "Invalid address received from DhcpServer: "
515 + Arrays.toString(lease.hwAddr));
516 return;
517 }
518
519 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900520 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900521 leases.add(new TetheredClient(
522 macAddress,
523 Collections.singletonList(addressInfo),
524 mInterfaceType));
525 }
526
527 getHandler().post(() -> {
528 mDhcpLeases = leases;
529 mCallback.dhcpLeasesChanged();
530 });
531 }
532
533 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900534 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
535 Objects.requireNonNull(currentPrefix);
536 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900537 }
538
539 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900540 public int getInterfaceVersion() {
541 return this.VERSION;
542 }
543
544 @Override
545 public String getInterfaceHash() throws RemoteException {
546 return this.HASH;
547 }
548 }
549
Xiao Ma4455d6b2020-04-09 10:13:44 +0900550 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
551 Objects.requireNonNull(ipv4Address);
552 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
553 }
554
555 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
556 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
557 @Nullable Inet4Address clientAddr) {
558 final boolean changePrefixOnDecline =
559 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
markchienfb65dfe2022-02-25 23:14:58 +0800560 final int subnetPrefixLength = mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
561 ? mP2pLeasesSubnetPrefixLength : 0 /* default value */;
562
Xiao Ma4455d6b2020-04-09 10:13:44 +0900563 return new DhcpServingParamsParcelExt()
564 .setDefaultRouters(defaultRouter)
565 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
566 .setDnsServers(dnsServer)
567 .setServerAddr(serverAddr)
568 .setMetered(true)
569 .setSingleClientAddr(clientAddr)
markchienfb65dfe2022-02-25 23:14:58 +0800570 .setChangePrefixOnDecline(changePrefixOnDecline)
571 .setLeasesSubnetPrefixLength(subnetPrefixLength);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900572 // TODO: also advertise link MTU
573 }
574
markchien245352e2020-02-27 20:27:18 +0800575 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800576 if (mUsingLegacyDhcp) {
577 return true;
578 }
markchien245352e2020-02-27 20:27:18 +0800579
580 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800581 final Inet4Address clientAddr = clientLinkAddr == null ? null :
582 (Inet4Address) clientLinkAddr.getAddress();
583
Xiao Ma4455d6b2020-04-09 10:13:44 +0900584 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
585 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800586 mDhcpServerStartIndex++;
587 mDeps.makeDhcpServer(
588 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
589 return true;
590 }
591
592 private void stopDhcp() {
593 // Make all previous start requests obsolete so servers are not started later
594 mDhcpServerStartIndex++;
595
596 if (mDhcpServer != null) {
597 try {
598 mDhcpServer.stop(new OnHandlerStatusCallback() {
599 @Override
600 public void callback(int statusCode) {
601 if (statusCode != STATUS_SUCCESS) {
602 mLog.e("Error stopping DHCP server: " + statusCode);
Mark74461fc2022-12-14 08:49:40 +0000603 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800604 // Not much more we can do here
605 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900606 mDhcpLeases.clear();
607 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800608 }
609 });
610 mDhcpServer = null;
611 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900612 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800613 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800614 }
615 }
616 }
617
markchien245352e2020-02-27 20:27:18 +0800618 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
619 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800620 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800621 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800622 } else {
623 stopDhcp();
624 return true;
625 }
626 }
627
628 private void stopIPv4() {
Mark49649c92023-03-15 06:45:04 +0000629 configureIPv4(false /* enabled */, CONNECTIVITY_SCOPE_GLOBAL /* not used */);
markchien74a4fa92019-09-09 20:50:49 +0800630 // NOTE: All of configureIPv4() will be refactored out of existence
631 // into calls to InterfaceController, shared with startIPv4().
632 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800633 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800634 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800635 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800636 mStaticIpv4ServerAddr = null;
637 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800638 }
639
Mark49649c92023-03-15 06:45:04 +0000640 private boolean configureIPv4(boolean enabled, int scope) {
markchien74a4fa92019-09-09 20:50:49 +0800641 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
642
markchienc9daba32020-02-12 00:19:21 +0800643 if (enabled) {
Mark49649c92023-03-15 06:45:04 +0000644 mIpv4Address = requestIpv4Address(scope, true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800645 }
646
647 if (mIpv4Address == null) {
648 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800649 return false;
markchien74a4fa92019-09-09 20:50:49 +0800650 }
651
markchien69681d62021-11-15 23:58:05 +0800652 if (shouldNotConfigureBluetoothInterface()) {
653 // Interface was already configured elsewhere, only start DHCP.
markchienc9daba32020-02-12 00:19:21 +0800654 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
655 }
656
657 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
658
markchien12c5bb82020-01-07 14:43:17 +0800659 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800660 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900661 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200662 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
663 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900664 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800665 // It is unclear whether the Bluetooth or USB stacks will manage their own
666 // state.
667 setIfaceUp = null;
668 } else {
669 setIfaceUp = enabled;
670 }
671 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
672 mLog.e("Error configuring interface");
673 if (!enabled) stopDhcp();
674 return false;
675 }
markchien74a4fa92019-09-09 20:50:49 +0800676
markchien74a4fa92019-09-09 20:50:49 +0800677 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800678 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900679 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800680 } else {
markchien12c5bb82020-01-07 14:43:17 +0800681 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900682 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800683 }
markchien245352e2020-02-27 20:27:18 +0800684 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800685 }
686
markchien69681d62021-11-15 23:58:05 +0800687 private boolean shouldNotConfigureBluetoothInterface() {
688 // Before T, bluetooth tethering configures the interface elsewhere.
689 return (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) && !SdkLevel.isAtLeastT();
690 }
691
Mark49649c92023-03-15 06:45:04 +0000692 private LinkAddress requestIpv4Address(final int scope, final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800693 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800694
markchien69681d62021-11-15 23:58:05 +0800695 if (shouldNotConfigureBluetoothInterface()) return new LinkAddress(BLUETOOTH_IFACE_ADDR);
markchienc9daba32020-02-12 00:19:21 +0800696
Mark49649c92023-03-15 06:45:04 +0000697 return mPrivateAddressCoordinator.requestDownstreamAddress(this, scope, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900698 }
699
markchien74a4fa92019-09-09 20:50:49 +0800700 private boolean startIPv6() {
701 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
702 if (mInterfaceParams == null) {
703 mLog.e("Failed to find InterfaceParams");
704 stopIPv6();
705 return false;
706 }
707
708 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
709 if (!mRaDaemon.start()) {
710 stopIPv6();
711 return false;
712 }
713
markchien932df542021-08-12 13:56:43 +0800714 if (SdkLevel.isAtLeastS()) {
Tyler Wear90e40632020-03-13 11:38:38 -0700715 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
716 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
717 }
718
markchien74a4fa92019-09-09 20:50:49 +0800719 return true;
720 }
721
722 private void stopIPv6() {
723 mInterfaceParams = null;
724 setRaParams(null);
725
726 if (mRaDaemon != null) {
727 mRaDaemon.stop();
728 mRaDaemon = null;
729 }
Tyler Wear90e40632020-03-13 11:38:38 -0700730
731 if (mDadProxy != null) {
732 mDadProxy.stop();
733 mDadProxy = null;
734 }
markchien74a4fa92019-09-09 20:50:49 +0800735 }
736
737 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
738 // LinkProperties. These have extraneous data filtered out and only the
739 // necessary prefixes included (per its prefix distribution policy).
740 //
741 // TODO: Evaluate using a data structure than is more directly suited to
742 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800743 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800744 if (mRaDaemon == null) return;
745
746 // Avoid unnecessary work on spurious updates.
747 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
748 return;
749 }
750
751 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700752 String upstreamIface = null;
753 InterfaceParams upstreamIfaceParams = null;
KH Shi701c3ca2023-08-16 13:19:33 +0000754 int upstreamIfIndex = NO_UPSTREAM;
markchien74a4fa92019-09-09 20:50:49 +0800755
756 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700757 upstreamIface = v6only.getInterfaceName();
758 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
759 if (upstreamIfaceParams != null) {
760 upstreamIfIndex = upstreamIfaceParams.index;
761 }
markchien74a4fa92019-09-09 20:50:49 +0800762 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700763 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800764 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
765
markchiend63c4f32020-05-21 17:38:28 +0800766 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800767
KH Shi3f738fc2023-05-23 22:37:17 +0800768 params.prefixes = getTetherableIpv6Prefixes(v6only);
769 for (IpPrefix prefix : params.prefixes) {
markchien74a4fa92019-09-09 20:50:49 +0800770 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
771 if (dnsServer != null) {
772 params.dnses.add(dnsServer);
773 }
774 }
775 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900776
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900777 // Add upstream index to name mapping. See the comment of the interface mapping update in
778 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
779 // timing issue. It prevents that the IPv6 capability is updated later than
780 // CMD_TETHER_CONNECTION_CHANGED.
KH Shi701c3ca2023-08-16 13:19:33 +0000781 mBpfCoordinator.maybeAddUpstreamToLookupTable(upstreamIfIndex, upstreamIface);
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900782
markchien74a4fa92019-09-09 20:50:49 +0800783 // If v6only is null, we pass in null to setRaParams(), which handles
784 // deprecation of any existing RA data.
markchien74a4fa92019-09-09 20:50:49 +0800785 setRaParams(params);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900786
KH Shi68770342023-08-17 14:34:31 +0000787 // Not support BPF on virtual upstream interface
788 final boolean upstreamSupportsBpf = upstreamIface != null && !isVcnInterface(upstreamIface);
KH Shi3f738fc2023-05-23 22:37:17 +0800789 final Set<IpPrefix> upstreamPrefixes = params != null ? params.prefixes : Set.of();
790 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamPrefixes,
791 upstreamIfIndex, upstreamPrefixes, upstreamSupportsBpf);
KH Shi68770342023-08-17 14:34:31 +0000792 mLastIPv6LinkProperties = v6only;
Tyler Wear90e40632020-03-13 11:38:38 -0700793 mLastIPv6UpstreamIfindex = upstreamIfIndex;
KH Shi3f738fc2023-05-23 22:37:17 +0800794 mLastIPv6UpstreamPrefixes = upstreamPrefixes;
KH Shi68770342023-08-17 14:34:31 +0000795 mUpstreamSupportsBpf = upstreamSupportsBpf;
Tyler Wear90e40632020-03-13 11:38:38 -0700796 if (mDadProxy != null) {
797 mDadProxy.setUpstreamIface(upstreamIfaceParams);
798 }
markchien74a4fa92019-09-09 20:50:49 +0800799 }
800
Xiao Ma4455d6b2020-04-09 10:13:44 +0900801 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900802 final int removalFailures = NetdUtils.removeRoutesFromLocalNetwork(
Xiao Ma4455d6b2020-04-09 10:13:44 +0900803 mNetd, toBeRemoved);
804 if (removalFailures > 0) {
805 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
806 removalFailures));
807 }
808
809 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
810 }
811
812 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
813 try {
814 // It's safe to call networkAddInterface() even if
815 // the interface is already in the local_network.
816 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
817 try {
818 // Add routes from local network. Note that adding routes that
819 // already exist does not cause an error (EEXIST is silently ignored).
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900820 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900821 } catch (IllegalStateException e) {
822 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
823 return;
824 }
825 } catch (ServiceSpecificException | RemoteException e) {
826 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
827 return;
828 }
829
830 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
831 }
832
markchien74a4fa92019-09-09 20:50:49 +0800833 private void configureLocalIPv6Routes(
834 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
835 // [1] Remove the routes that are deprecated.
836 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900837 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800838 }
839
840 // [2] Add only the routes that have not previously been added.
841 if (newPrefixes != null && !newPrefixes.isEmpty()) {
842 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
843 if (mLastRaParams != null) {
844 addedPrefixes.removeAll(mLastRaParams.prefixes);
845 }
846
847 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900848 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800849 }
850 }
851 }
852
853 private void configureLocalIPv6Dns(
854 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
855 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
856 if (mNetd == null) {
857 if (newDnses != null) newDnses.clear();
858 mLog.e("No netd service instance available; not setting local IPv6 addresses");
859 return;
860 }
861
862 // [1] Remove deprecated local DNS IP addresses.
863 if (!deprecatedDnses.isEmpty()) {
864 for (Inet6Address dns : deprecatedDnses) {
865 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
866 mLog.e("Failed to remove local dns IP " + dns);
867 }
868
869 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
870 }
871 }
872
873 // [2] Add only the local DNS IP addresses that have not previously been added.
874 if (newDnses != null && !newDnses.isEmpty()) {
875 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
876 if (mLastRaParams != null) {
877 addedDnses.removeAll(mLastRaParams.dnses);
878 }
879
880 for (Inet6Address dns : addedDnses) {
881 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
882 mLog.e("Failed to add local dns IP " + dns);
883 newDnses.remove(dns);
884 }
885
886 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
887 }
888 }
889
890 try {
891 mNetd.tetherApplyDnsInterfaces();
892 } catch (ServiceSpecificException | RemoteException e) {
893 mLog.e("Failed to update local DNS caching server");
894 if (newDnses != null) newDnses.clear();
895 }
896 }
897
KH Shi701c3ca2023-08-16 13:19:33 +0000898 private int getInterfaceIndexForRule(int ifindex, boolean supportsBpf) {
899 return supportsBpf ? ifindex : NO_UPSTREAM;
900 }
901
KH Shi3f738fc2023-05-23 22:37:17 +0800902 // Handles updates to IPv6 forwarding rules if the upstream or its prefixes change.
903 private void updateIpv6ForwardingRules(int prevUpstreamIfindex,
904 @NonNull Set<IpPrefix> prevUpstreamPrefixes, int upstreamIfindex,
905 @NonNull Set<IpPrefix> upstreamPrefixes, boolean upstreamSupportsBpf) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900906 // If the upstream interface has changed, remove all rules and re-add them with the new
KH Shi701c3ca2023-08-16 13:19:33 +0000907 // upstream interface. If upstream is a virtual network, treated as no upstream.
KH Shi3f738fc2023-05-23 22:37:17 +0800908 if (prevUpstreamIfindex != upstreamIfindex
909 || !prevUpstreamPrefixes.equals(upstreamPrefixes)) {
KH Shi701c3ca2023-08-16 13:19:33 +0000910 mBpfCoordinator.updateAllIpv6Rules(this, this.mInterfaceParams,
KH Shi3f738fc2023-05-23 22:37:17 +0800911 getInterfaceIndexForRule(upstreamIfindex, upstreamSupportsBpf),
912 upstreamPrefixes);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900913 }
KH Shi701c3ca2023-08-16 13:19:33 +0000914 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900915
KH Shi701c3ca2023-08-16 13:19:33 +0000916 // Handles updates to IPv6 downstream rules if a neighbor event is received.
917 private void addOrRemoveIpv6Downstream(NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900918 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900919 if (e == null) return;
920 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
921 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
922 return;
923 }
924
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900925 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
KH Shi59ad35e2023-08-15 07:13:00 +0000926 // Do this here instead of in the Ipv6DownstreamRule constructor to ensure that we
927 // never add rules with a null MAC, only delete them.
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900928 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
KH Shi701c3ca2023-08-16 13:19:33 +0000929 Ipv6DownstreamRule rule = new Ipv6DownstreamRule(
930 getInterfaceIndexForRule(mLastIPv6UpstreamIfindex, mUpstreamSupportsBpf),
931 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900932 if (e.isValid()) {
KH Shie4d549a2023-08-28 09:57:34 +0000933 mBpfCoordinator.addIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900934 } else {
KH Shie4d549a2023-08-28 09:57:34 +0000935 mBpfCoordinator.removeIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900936 }
937 }
938
Hungming Chend71c06e2020-12-21 19:39:49 +0800939 // TODO: consider moving into BpfCoordinator.
940 private void updateClientInfoIpv4(NeighborEvent e) {
Hungming Chend71c06e2020-12-21 19:39:49 +0800941 if (e == null) return;
942 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
943 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
944 return;
945 }
946
947 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
948 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
949 // IpServer never add clients with a null MAC, only delete them.
950 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
951 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
952 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
953 if (e.isValid()) {
954 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
955 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +0800956 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
957 }
958 }
959
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900960 private void handleNeighborEvent(NeighborEvent e) {
961 if (mInterfaceParams != null
962 && mInterfaceParams.index == e.ifindex
963 && mInterfaceParams.hasMacAddress) {
KH Shi701c3ca2023-08-16 13:19:33 +0000964 addOrRemoveIpv6Downstream(e);
Hungming Chend71c06e2020-12-21 19:39:49 +0800965 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900966 }
967 }
968
markchiend63c4f32020-05-21 17:38:28 +0800969 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +0800970 try {
971 int upstreamHopLimit = Integer.parseUnsignedInt(
972 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +0800973 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +0800974 // Cap the hop limit to 255.
975 return (byte) Integer.min(upstreamHopLimit, 255);
976 } catch (Exception e) {
977 mLog.e("Failed to find upstream interface hop limit", e);
978 }
979 return RaParams.DEFAULT_HOPLIMIT;
980 }
981
982 private void setRaParams(RaParams newParams) {
983 if (mRaDaemon != null) {
984 final RaParams deprecatedParams =
985 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
986
987 configureLocalIPv6Routes(deprecatedParams.prefixes,
988 (newParams != null) ? newParams.prefixes : null);
989
990 configureLocalIPv6Dns(deprecatedParams.dnses,
991 (newParams != null) ? newParams.dnses : null);
992
993 mRaDaemon.buildNewRa(deprecatedParams, newParams);
994 }
995
996 mLastRaParams = newParams;
997 }
998
markchien21021ef2021-06-01 10:58:04 +0800999 private void maybeLogMessage(State state, int what) {
1000 switch (what) {
1001 // Suppress some CMD_* to avoid log flooding.
1002 case CMD_IPV6_TETHER_UPDATE:
1003 case CMD_NEIGHBOR_EVENT:
1004 break;
1005 default:
1006 mLog.log(state.getName() + " got "
1007 + sMagicDecoderRing.get(what, Integer.toString(what)));
1008 }
markchien74a4fa92019-09-09 20:50:49 +08001009 }
1010
1011 private void sendInterfaceState(int newInterfaceState) {
1012 mServingMode = newInterfaceState;
1013 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1014 sendLinkProperties();
1015 }
1016
1017 private void sendLinkProperties() {
1018 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1019 }
1020
1021 private void resetLinkProperties() {
1022 mLinkProperties.clear();
1023 mLinkProperties.setInterfaceName(mIfaceName);
1024 }
1025
markchienf053e4b2020-03-16 21:49:48 +08001026 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001027 // Ignore static address configuration if they are invalid or null. In theory, static
1028 // addresses should not be invalid here because TetheringManager do not allow caller to
1029 // specify invalid static address configuration.
1030 if (request == null || request.localIPv4Address == null
1031 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1032 request.localIPv4Address, request.staticClientAddress)) {
1033 return;
1034 }
markchienf053e4b2020-03-16 21:49:48 +08001035
1036 mStaticIpv4ServerAddr = request.localIPv4Address;
1037 mStaticIpv4ClientAddr = request.staticClientAddress;
1038 }
1039
markchien74a4fa92019-09-09 20:50:49 +08001040 class InitialState extends State {
1041 @Override
1042 public void enter() {
1043 sendInterfaceState(STATE_AVAILABLE);
1044 }
1045
1046 @Override
1047 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001048 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001049 switch (message.what) {
1050 case CMD_TETHER_REQUESTED:
Mark74461fc2022-12-14 08:49:40 +00001051 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001052 switch (message.arg1) {
1053 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001054 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001055 transitionTo(mLocalHotspotState);
1056 break;
1057 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001058 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001059 transitionTo(mTetheredState);
1060 break;
1061 default:
1062 mLog.e("Invalid tethering interface serving state specified.");
1063 }
1064 break;
1065 case CMD_INTERFACE_DOWN:
1066 transitionTo(mUnavailableState);
1067 break;
markchien74a4fa92019-09-09 20:50:49 +08001068 default:
1069 return NOT_HANDLED;
1070 }
1071 return HANDLED;
1072 }
1073 }
1074
Hungming Chen46c30b12020-10-15 17:25:36 +08001075 private void startConntrackMonitoring() {
1076 mBpfCoordinator.startMonitoring(this);
1077 }
1078
1079 private void stopConntrackMonitoring() {
1080 mBpfCoordinator.stopMonitoring(this);
1081 }
1082
Mark3ec851e2023-05-19 08:50:38 +00001083 abstract class BaseServingState extends State {
1084 private final int mDesiredInterfaceState;
1085
1086 BaseServingState(int interfaceState) {
1087 mDesiredInterfaceState = interfaceState;
1088 }
1089
markchien74a4fa92019-09-09 20:50:49 +08001090 @Override
1091 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001092 startConntrackMonitoring();
1093
Mark3ec851e2023-05-19 08:50:38 +00001094 startServingInterface();
1095
1096 if (mLastError != TETHER_ERROR_NO_ERROR) {
1097 transitionTo(mInitialState);
1098 }
1099
1100 if (DBG) Log.d(TAG, getStateString(mDesiredInterfaceState) + " serve " + mIfaceName);
1101 sendInterfaceState(mDesiredInterfaceState);
1102 }
1103
Mark49649c92023-03-15 06:45:04 +00001104 private int getScope() {
1105 if (mDesiredInterfaceState == STATE_TETHERED) {
1106 return CONNECTIVITY_SCOPE_GLOBAL;
1107 }
1108
1109 return CONNECTIVITY_SCOPE_LOCAL;
1110 }
1111
Mark3ec851e2023-05-19 08:50:38 +00001112 private void startServingInterface() {
Mark49649c92023-03-15 06:45:04 +00001113 if (!startIPv4(getScope())) {
Mark74461fc2022-12-14 08:49:40 +00001114 mLastError = TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001115 return;
1116 }
1117
1118 try {
markchienc9daba32020-02-12 00:19:21 +08001119 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001120 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001121 mLog.e("Error Tethering", e);
Mark74461fc2022-12-14 08:49:40 +00001122 mLastError = TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001123 return;
1124 }
1125
1126 if (!startIPv6()) {
1127 mLog.e("Failed to startIPv6");
1128 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1129 return;
1130 }
1131 }
1132
1133 @Override
1134 public void exit() {
1135 // Note that at this point, we're leaving the tethered state. We can fail any
1136 // of these operations, but it doesn't really change that we have to try them
1137 // all in sequence.
1138 stopIPv6();
1139
1140 try {
markchien12c5bb82020-01-07 14:43:17 +08001141 NetdUtils.untetherInterface(mNetd, mIfaceName);
1142 } catch (RemoteException | ServiceSpecificException e) {
Mark74461fc2022-12-14 08:49:40 +00001143 mLastError = TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001144 mLog.e("Failed to untether interface: " + e);
1145 }
1146
1147 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001148 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001149
1150 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001151
1152 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1153 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001154 }
1155
1156 @Override
1157 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001158 switch (message.what) {
1159 case CMD_TETHER_UNREQUESTED:
1160 transitionTo(mInitialState);
1161 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1162 break;
1163 case CMD_INTERFACE_DOWN:
1164 transitionTo(mUnavailableState);
1165 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1166 break;
1167 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001168 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001169 sendLinkProperties();
1170 break;
1171 case CMD_IP_FORWARDING_ENABLE_ERROR:
1172 case CMD_IP_FORWARDING_DISABLE_ERROR:
1173 case CMD_START_TETHERING_ERROR:
1174 case CMD_STOP_TETHERING_ERROR:
1175 case CMD_SET_DNS_FORWARDERS_ERROR:
Mark74461fc2022-12-14 08:49:40 +00001176 mLastError = TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001177 transitionTo(mInitialState);
1178 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001179 case CMD_NEW_PREFIX_REQUEST:
1180 handleNewPrefixRequest((IpPrefix) message.obj);
1181 break;
markchienc9daba32020-02-12 00:19:21 +08001182 case CMD_NOTIFY_PREFIX_CONFLICT:
1183 mLog.i("restart tethering: " + mInterfaceType);
1184 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1185 transitionTo(mWaitingForRestartState);
1186 break;
markchien74a4fa92019-09-09 20:50:49 +08001187 default:
1188 return false;
1189 }
1190 return true;
1191 }
Mark3ec851e2023-05-19 08:50:38 +00001192
1193 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
1194 if (!currentPrefix.contains(mIpv4Address.getAddress())
1195 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
1196 Log.e(TAG, "Invalid prefix: " + currentPrefix);
1197 return;
1198 }
1199
1200 final LinkAddress deprecatedLinkAddress = mIpv4Address;
Mark49649c92023-03-15 06:45:04 +00001201 mIpv4Address = requestIpv4Address(getScope(), false);
Mark3ec851e2023-05-19 08:50:38 +00001202 if (mIpv4Address == null) {
1203 mLog.e("Fail to request a new downstream prefix");
1204 return;
1205 }
1206 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
1207
1208 // Add new IPv4 address on the interface.
1209 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1210 mLog.e("Failed to add new IP " + srvAddr);
1211 return;
1212 }
1213
1214 // Remove deprecated routes from local network.
1215 removeRoutesFromLocalNetwork(
1216 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1217 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1218
1219 // Add new routes to local network.
1220 addRoutesToLocalNetwork(
1221 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1222 mLinkProperties.addLinkAddress(mIpv4Address);
1223
1224 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1225 // listen on the interface configured with new IPv4 address, that results DNS validation
1226 // failure of downstream client even if appropriate routes have been configured.
1227 try {
1228 mNetd.tetherApplyDnsInterfaces();
1229 } catch (ServiceSpecificException | RemoteException e) {
1230 mLog.e("Failed to update local DNS caching server");
1231 return;
1232 }
1233 sendLinkProperties();
1234
1235 // Notify DHCP server that new prefix/route has been applied on IpServer.
1236 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1237 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1238 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1239 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1240 try {
1241 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1242 @Override
1243 public void callback(int statusCode) {
1244 if (statusCode != STATUS_SUCCESS) {
1245 mLog.e("Error updating DHCP serving params: " + statusCode);
1246 }
1247 }
1248 });
1249 } catch (RemoteException e) {
1250 mLog.e("Error updating DHCP serving params", e);
1251 }
1252 }
markchien74a4fa92019-09-09 20:50:49 +08001253 }
1254
1255 // Handling errors in BaseServingState.enter() by transitioning is
1256 // problematic because transitioning during a multi-state jump yields
1257 // a Log.wtf(). Ultimately, there should be only one ServingState,
1258 // and forwarding and NAT rules should be handled by a coordinating
1259 // functional element outside of IpServer.
1260 class LocalHotspotState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001261 LocalHotspotState() {
1262 super(STATE_LOCAL_ONLY);
markchien74a4fa92019-09-09 20:50:49 +08001263 }
1264
1265 @Override
1266 public boolean processMessage(Message message) {
1267 if (super.processMessage(message)) return true;
1268
markchien21021ef2021-06-01 10:58:04 +08001269 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001270 switch (message.what) {
1271 case CMD_TETHER_REQUESTED:
1272 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1273 break;
1274 case CMD_TETHER_CONNECTION_CHANGED:
1275 // Ignored in local hotspot state.
1276 break;
1277 default:
1278 return false;
1279 }
1280 return true;
1281 }
1282 }
1283
1284 // Handling errors in BaseServingState.enter() by transitioning is
1285 // problematic because transitioning during a multi-state jump yields
1286 // a Log.wtf(). Ultimately, there should be only one ServingState,
1287 // and forwarding and NAT rules should be handled by a coordinating
1288 // functional element outside of IpServer.
1289 class TetheredState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001290 TetheredState() {
1291 super(STATE_TETHERED);
markchien74a4fa92019-09-09 20:50:49 +08001292 }
1293
1294 @Override
1295 public void exit() {
1296 cleanupUpstream();
KH Shi701c3ca2023-08-16 13:19:33 +00001297 mBpfCoordinator.clearAllIpv6Rules(IpServer.this);
markchien74a4fa92019-09-09 20:50:49 +08001298 super.exit();
1299 }
1300
Hungming Chena6e78692021-02-08 17:15:35 +08001301 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1302 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1303 // and behaviour. While upstream is switching from offload supported interface to
1304 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1305 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1306 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1307 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1308 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1309 // in the state machine. Once there is any case out whish is not covered by previous cases,
1310 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001311 private void cleanupUpstream() {
1312 if (mUpstreamIfaceSet == null) return;
1313
1314 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1315 mUpstreamIfaceSet = null;
KH Shi701c3ca2023-08-16 13:19:33 +00001316 mBpfCoordinator.updateAllIpv6Rules(
KH Shi3f738fc2023-05-23 22:37:17 +08001317 IpServer.this, IpServer.this.mInterfaceParams, NO_UPSTREAM, Set.of());
markchien74a4fa92019-09-09 20:50:49 +08001318 }
1319
1320 private void cleanupUpstreamInterface(String upstreamIface) {
1321 // Note that we don't care about errors here.
1322 // Sometimes interfaces are gone before we get
1323 // to remove their rules, which generates errors.
1324 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001325 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001326 try {
markchien12c5bb82020-01-07 14:43:17 +08001327 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1328 } catch (RemoteException | ServiceSpecificException e) {
1329 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001330 }
1331 try {
markchien12c5bb82020-01-07 14:43:17 +08001332 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1333 } catch (RemoteException | ServiceSpecificException e) {
1334 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001335 }
1336 }
1337
1338 @Override
1339 public boolean processMessage(Message message) {
1340 if (super.processMessage(message)) return true;
1341
markchien21021ef2021-06-01 10:58:04 +08001342 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001343 switch (message.what) {
1344 case CMD_TETHER_REQUESTED:
1345 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1346 break;
1347 case CMD_TETHER_CONNECTION_CHANGED:
1348 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1349 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1350 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1351 break;
1352 }
1353
1354 if (newUpstreamIfaceSet == null) {
1355 cleanupUpstream();
1356 break;
1357 }
1358
1359 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1360 cleanupUpstreamInterface(removed);
1361 }
1362
1363 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1364 // This makes the call to cleanupUpstream() in the error
1365 // path for any interface neatly cleanup all the interfaces.
1366 mUpstreamIfaceSet = newUpstreamIfaceSet;
1367
1368 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001369 // Add upstream index to name mapping for the tether stats usage in the
1370 // coordinator. Although this mapping could be added by both class
1371 // Tethering and IpServer, adding mapping from IpServer guarantees that
1372 // the mapping is added before adding forwarding rules. That is because
1373 // there are different state machines in both classes. It is hard to
1374 // guarantee the link property update order between multiple state machines.
1375 // Note that both IPv4 and IPv6 interface may be added because
1376 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1377 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1378 // capability may be updated later. In that case, IPv6 interface mapping is
1379 // updated in updateUpstreamIPv6LinkProperties.
1380 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1381 final InterfaceParams upstreamIfaceParams =
1382 mDeps.getInterfaceParams(ifname);
1383 if (upstreamIfaceParams != null) {
KH Shi701c3ca2023-08-16 13:19:33 +00001384 mBpfCoordinator.maybeAddUpstreamToLookupTable(
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001385 upstreamIfaceParams.index, ifname);
1386 }
1387 }
1388
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001389 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001390 try {
markchien12c5bb82020-01-07 14:43:17 +08001391 mNetd.tetherAddForward(mIfaceName, ifname);
1392 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1393 } catch (RemoteException | ServiceSpecificException e) {
1394 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001395 cleanupUpstream();
Mark74461fc2022-12-14 08:49:40 +00001396 mLastError = TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001397 transitionTo(mInitialState);
1398 return true;
1399 }
1400 }
1401 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001402 case CMD_NEIGHBOR_EVENT:
1403 handleNeighborEvent((NeighborEvent) message.obj);
1404 break;
markchien74a4fa92019-09-09 20:50:49 +08001405 default:
1406 return false;
1407 }
1408 return true;
1409 }
1410
1411 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1412 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1413 if (mUpstreamIfaceSet != null && newIfaces != null) {
1414 return mUpstreamIfaceSet.equals(newIfaces);
1415 }
1416 return false;
1417 }
1418
1419 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1420 if (mUpstreamIfaceSet == null) return new HashSet<>();
1421
1422 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1423 removed.removeAll(newIfaces.ifnames);
1424 return removed;
1425 }
1426
1427 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1428 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1429 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1430 return added;
1431 }
1432 }
1433
1434 /**
1435 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001436 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001437 * specific state machine from its list of possible recipients of
1438 * tethering requests. The state machine itself will hang around until
1439 * the garbage collector finds it.
1440 */
1441 class UnavailableState extends State {
1442 @Override
1443 public void enter() {
KH Shi701c3ca2023-08-16 13:19:33 +00001444 // TODO: move mIpNeighborMonitor.stop() to TetheredState#exit, and trigger a neighbours
1445 // dump after starting mIpNeighborMonitor.
h.zhangd244bd02020-06-14 14:46:54 +08001446 mIpNeighborMonitor.stop();
Mark74461fc2022-12-14 08:49:40 +00001447 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001448 sendInterfaceState(STATE_UNAVAILABLE);
1449 }
1450 }
1451
markchienc9daba32020-02-12 00:19:21 +08001452 class WaitingForRestartState extends State {
1453 @Override
1454 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001455 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001456 switch (message.what) {
1457 case CMD_TETHER_UNREQUESTED:
1458 transitionTo(mInitialState);
1459 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1460 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1461 break;
1462 case CMD_INTERFACE_DOWN:
1463 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001464 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001465 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1466 break;
1467 default:
1468 return false;
1469 }
1470 return true;
1471 }
1472 }
1473
markchien74a4fa92019-09-09 20:50:49 +08001474 // Accumulate routes representing "prefixes to be assigned to the local
1475 // interface", for subsequent modification of local_network routing.
1476 private static ArrayList<RouteInfo> getLocalRoutesFor(
1477 String ifname, HashSet<IpPrefix> prefixes) {
1478 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1479 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001480 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001481 }
1482 return localRoutes;
1483 }
1484
1485 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1486 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1487 final byte[] dnsBytes = localPrefix.getRawAddress();
1488 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1489 try {
1490 return Inet6Address.getByAddress(null, dnsBytes, 0);
1491 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001492 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001493 return null;
1494 }
1495 }
1496
1497 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1498 final byte random = (byte) (new Random()).nextInt();
1499 for (int value : excluded) {
1500 if (random == value) return dflt;
1501 }
1502 return random;
1503 }
KH Shi3f738fc2023-05-23 22:37:17 +08001504
1505 /** Get IPv6 prefixes from LinkProperties */
1506 @NonNull
1507 @VisibleForTesting
1508 static HashSet<IpPrefix> getTetherableIpv6Prefixes(@NonNull Collection<LinkAddress> addrs) {
1509 final HashSet<IpPrefix> prefixes = new HashSet<>();
1510 for (LinkAddress linkAddr : addrs) {
1511 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
1512 prefixes.add(new IpPrefix(linkAddr.getAddress(), RFC7421_PREFIX_LENGTH));
1513 }
1514 return prefixes;
1515 }
1516
1517 @NonNull
1518 private HashSet<IpPrefix> getTetherableIpv6Prefixes(@NonNull LinkProperties lp) {
1519 return getTetherableIpv6Prefixes(lp.getLinkAddresses());
1520 }
markchien74a4fa92019-09-09 20:50:49 +08001521}