blob: a8c840803b50e30257a6472b7971b7a70204b83e [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;
Chalard Jean2fb66f12023-08-25 12:50:37 +090047import android.net.RoutingCoordinatorManager;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090048import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080049import android.net.TetheringManager;
markchienf053e4b2020-03-16 21:49:48 +080050import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090051import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080052import android.net.dhcp.DhcpServerCallbacks;
53import android.net.dhcp.DhcpServingParamsParcel;
54import android.net.dhcp.DhcpServingParamsParcelExt;
Xiao Ma49889dd2020-04-03 17:01:33 +090055import android.net.dhcp.IDhcpEventCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080056import android.net.dhcp.IDhcpServer;
57import android.net.ip.RouterAdvertisementDaemon.RaParams;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090058import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080059import 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;
markchien932df542021-08-12 13:56:43 +080071import com.android.modules.utils.build.SdkLevel;
Patrick Rohr9f371f02022-03-04 15:14:27 +010072import com.android.net.module.util.InterfaceParams;
Chalard Jeanadcec9e2021-10-29 15:57:22 +090073import com.android.net.module.util.NetdUtils;
Chalard Jean2fb66f12023-08-25 12:50:37 +090074import com.android.net.module.util.SdkUtil.LateSdk;
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;
Mark21502962022-12-21 06:58:23 +000087import com.android.networkstack.tethering.util.StateMachineShim;
88import com.android.networkstack.tethering.util.SyncStateMachine.StateInfo;
markchien74a4fa92019-09-09 20:50:49 +080089
90import java.net.Inet4Address;
91import java.net.Inet6Address;
markchien74a4fa92019-09-09 20:50:49 +080092import java.net.UnknownHostException;
93import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090094import java.util.Arrays;
KH Shi3f738fc2023-05-23 22:37:17 +080095import java.util.Collection;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090096import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080097import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090098import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080099import java.util.Objects;
100import java.util.Random;
101import java.util.Set;
102
103/**
104 * Provides the interface to IP-layer serving functionality for a given network
105 * interface, e.g. for tethering or "local-only hotspot" mode.
106 *
107 * @hide
108 */
Mark21502962022-12-21 06:58:23 +0000109public class IpServer extends StateMachineShim {
markchien74a4fa92019-09-09 20:50:49 +0800110 public static final int STATE_UNAVAILABLE = 0;
111 public static final int STATE_AVAILABLE = 1;
112 public static final int STATE_TETHERED = 2;
113 public static final int STATE_LOCAL_ONLY = 3;
114
115 /** Get string name of |state|.*/
116 public static String getStateString(int state) {
117 switch (state) {
118 case STATE_UNAVAILABLE: return "UNAVAILABLE";
119 case STATE_AVAILABLE: return "AVAILABLE";
120 case STATE_TETHERED: return "TETHERED";
121 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
122 }
123 return "UNKNOWN: " + state;
124 }
125
126 private static final byte DOUG_ADAMS = (byte) 42;
127
markchien74a4fa92019-09-09 20:50:49 +0800128 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800129 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800130
131 // TODO: have this configurable
132 private static final int DHCP_LEASE_TIME_SECS = 3600;
133
KH Shi701c3ca2023-08-16 13:19:33 +0000134 private static final int NO_UPSTREAM = 0;
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900135 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
136
markchien74a4fa92019-09-09 20:50:49 +0800137 private static final String TAG = "IpServer";
138 private static final boolean DBG = false;
139 private static final boolean VDBG = false;
140 private static final Class[] sMessageClasses = {
141 IpServer.class
142 };
143 private static final SparseArray<String> sMagicDecoderRing =
144 MessageUtils.findMessageNames(sMessageClasses);
145
146 /** IpServer callback. */
147 public static class Callback {
148 /**
149 * Notify that |who| has changed its tethering state.
150 *
151 * @param who the calling instance of IpServer
152 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800153 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800154 */
markchien9d353822019-12-16 20:15:20 +0800155 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800156
157 /**
158 * Notify that |who| has new LinkProperties.
159 *
160 * @param who the calling instance of IpServer
161 * @param newLp the new LinkProperties to report
162 */
markchien9d353822019-12-16 20:15:20 +0800163 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900164
165 /**
166 * Notify that the DHCP leases changed in one of the IpServers.
167 */
168 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800169
170 /**
171 * Request Tethering change.
172 *
173 * @param tetheringType the downstream type of this IpServer.
174 * @param enabled enable or disable tethering.
175 */
176 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800177 }
178
179 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800180 public abstract static class Dependencies {
Tyler Wear90e40632020-03-13 11:38:38 -0700181 /**
182 * Create a DadProxy instance to be used by IpServer.
183 * To support multiple tethered interfaces concurrently DAD Proxy
184 * needs to be supported per IpServer instead of per upstream.
185 */
186 public DadProxy getDadProxy(Handler handler, InterfaceParams ifParams) {
187 return new DadProxy(handler, ifParams);
188 }
189
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900190 /** Create an IpNeighborMonitor to be used by this IpServer */
191 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
192 IpNeighborMonitor.NeighborEventConsumer consumer) {
193 return new IpNeighborMonitor(handler, log, consumer);
194 }
195
markchien74a4fa92019-09-09 20:50:49 +0800196 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
197 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
198 return new RouterAdvertisementDaemon(ifParams);
199 }
200
201 /** Get |ifName|'s interface information.*/
202 public InterfaceParams getInterfaceParams(String ifName) {
203 return InterfaceParams.getByName(ifName);
204 }
205
markchien9d353822019-12-16 20:15:20 +0800206 /** Create a DhcpServer instance to be used by IpServer. */
207 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
208 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800209 }
210
markchien74a4fa92019-09-09 20:50:49 +0800211 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800212 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800213 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800214 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800215 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800216 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800217 // notification from the {@link Tethering.TetherMainSM} that it had trouble enabling IP
218 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800219 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800220 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble disabling IP
221 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800222 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800223 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble starting
224 // tethering
markchien6cf0e552019-12-06 15:24:53 +0800225 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800226 // notification from the {@link Tethering.TetherMainSM} that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800227 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800228 // notification from the {@link Tethering.TetherMainSM} that it had trouble setting the DNS
229 // forwarders
markchien6cf0e552019-12-06 15:24:53 +0800230 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800231 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800232 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800233 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800234 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900235 // new neighbor cache entry on our interface
236 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900237 // request from DHCP server that it wants to have a new prefix
238 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800239 // request from PrivateAddressCoordinator to restart tethering.
240 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
Mark50eef832023-09-19 06:56:14 +0000241 public static final int CMD_SERVICE_FAILED_TO_START = BASE_IPSERVER + 14;
markchien74a4fa92019-09-09 20:50:49 +0800242
243 private final State mInitialState;
244 private final State mLocalHotspotState;
245 private final State mTetheredState;
246 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800247 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800248
249 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800250 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800251 @NonNull
252 private final BpfCoordinator mBpfCoordinator;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900253 // Contains null if the connectivity module is unsupported, as the routing coordinator is not
254 // available. Must use LateSdk because MessageUtils enumerates fields in this class, so it
255 // must be able to find all classes at runtime.
256 @NonNull
257 private final LateSdk<RoutingCoordinatorManager> mRoutingCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800258 private final Callback mCallback;
259 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800260 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800261
262 private final String mIfaceName;
263 private final int mInterfaceType;
264 private final LinkProperties mLinkProperties;
265 private final boolean mUsingLegacyDhcp;
markchienfb65dfe2022-02-25 23:14:58 +0800266 private final int mP2pLeasesSubnetPrefixLength;
markchien74a4fa92019-09-09 20:50:49 +0800267
268 private final Dependencies mDeps;
269
270 private int mLastError;
271 private int mServingMode;
272 private InterfaceSet mUpstreamIfaceSet; // may change over time
KH Shi701c3ca2023-08-16 13:19:33 +0000273 // mInterfaceParams can't be final now because IpServer will be created when receives
274 // WIFI_AP_STATE_CHANGED broadcasts or when it detects that the wifi interface has come up.
275 // In the latter case, the interface is not fully initialized and the MAC address might not
276 // be correct (it will be set with a randomized MAC address later).
277 // TODO: Consider create the IpServer only when tethering want to enable it, then we can
278 // make mInterfaceParams final.
markchien74a4fa92019-09-09 20:50:49 +0800279 private InterfaceParams mInterfaceParams;
280 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
281 // properties are those selected by the IPv6TetheringCoordinator and relayed
282 // to us. By comparison, mLinkProperties contains the addresses and directly
283 // connected routes that have been formed from these properties iff. we have
284 // succeeded in configuring them and are able to announce them within Router
285 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
286 private LinkProperties mLastIPv6LinkProperties;
287 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700288 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800289
290 // To be accessed only on the handler thread
291 private int mDhcpServerStartIndex = 0;
292 private IDhcpServer mDhcpServer;
293 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800294
295 private LinkAddress mStaticIpv4ServerAddr;
296 private LinkAddress mStaticIpv4ClientAddr;
297
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900298 @NonNull
299 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800300
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900301 private int mLastIPv6UpstreamIfindex = 0;
KH Shi68770342023-08-17 14:34:31 +0000302 private boolean mUpstreamSupportsBpf = false;
KH Shi3f738fc2023-05-23 22:37:17 +0800303 @NonNull
304 private Set<IpPrefix> mLastIPv6UpstreamPrefixes = Collections.emptySet();
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900305
306 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
307 public void accept(NeighborEvent e) {
308 sendMessage(CMD_NEIGHBOR_EVENT, e);
309 }
310 }
311
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900312 private final IpNeighborMonitor mIpNeighborMonitor;
313
markchienc9daba32020-02-12 00:19:21 +0800314 private LinkAddress mIpv4Address;
315
Wayne Ma6cd440f2022-03-14 18:04:33 +0800316 private final TetheringMetrics mTetheringMetrics;
Mark21502962022-12-21 06:58:23 +0000317 private final Handler mHandler;
Markcf11be92023-12-05 08:19:15 +0000318 private final boolean mIsSyncSM;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800319
Hungming Chen5bc3af92020-05-12 19:15:24 +0800320 // TODO: Add a dependency object to pass the data members or variables from the tethering
321 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800322 public IpServer(
Mark21502962022-12-21 06:58:23 +0000323 String ifaceName, Handler handler, int interfaceType, SharedLog log,
Chalard Jean2fb66f12023-08-25 12:50:37 +0900324 INetd netd, @NonNull BpfCoordinator bpfCoordinator,
325 @Nullable LateSdk<RoutingCoordinatorManager> routingCoordinator, Callback callback,
markchienb961d3d2022-02-26 00:39:06 +0800326 TetheringConfiguration config, PrivateAddressCoordinator addressCoordinator,
Wayne Ma6cd440f2022-03-14 18:04:33 +0800327 TetheringMetrics tetheringMetrics, Dependencies deps) {
Markcf11be92023-12-05 08:19:15 +0000328 super(ifaceName, config.isSyncSM() ? null : handler.getLooper());
Mark21502962022-12-21 06:58:23 +0000329 mHandler = handler;
markchien74a4fa92019-09-09 20:50:49 +0800330 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800331 mNetd = netd;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900332 mBpfCoordinator = bpfCoordinator;
333 mRoutingCoordinator = routingCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800334 mCallback = callback;
335 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
336 mIfaceName = ifaceName;
337 mInterfaceType = interfaceType;
338 mLinkProperties = new LinkProperties();
markchienb961d3d2022-02-26 00:39:06 +0800339 mUsingLegacyDhcp = config.useLegacyDhcpServer();
markchienfb65dfe2022-02-25 23:14:58 +0800340 mP2pLeasesSubnetPrefixLength = config.getP2pLeasesSubnetPrefixLength();
Markcf11be92023-12-05 08:19:15 +0000341 mIsSyncSM = config.isSyncSM();
markchienc9daba32020-02-12 00:19:21 +0800342 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800343 mDeps = deps;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800344 mTetheringMetrics = tetheringMetrics;
markchien74a4fa92019-09-09 20:50:49 +0800345 resetLinkProperties();
Mark74461fc2022-12-14 08:49:40 +0000346 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800347 mServingMode = STATE_AVAILABLE;
348
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900349 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
350 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800351
KH Shie4d549a2023-08-28 09:57:34 +0000352 // IP neighbor monitor monitors the neighbor events for adding/removing IPv6 downstream rule
353 // per client. If BPF offload is not supported, don't start listening for neighbor events.
354 if (mBpfCoordinator.isUsingBpfOffload() && !mIpNeighborMonitor.start()) {
Hungming Chen5bc3af92020-05-12 19:15:24 +0800355 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900356 }
357
markchien74a4fa92019-09-09 20:50:49 +0800358 mInitialState = new InitialState();
359 mLocalHotspotState = new LocalHotspotState();
360 mTetheredState = new TetheredState();
361 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800362 mWaitingForRestartState = new WaitingForRestartState();
Mark21502962022-12-21 06:58:23 +0000363 final ArrayList allStates = new ArrayList<StateInfo>();
364 allStates.add(new StateInfo(mInitialState, null));
365 allStates.add(new StateInfo(mLocalHotspotState, null));
366 allStates.add(new StateInfo(mTetheredState, null));
367 allStates.add(new StateInfo(mWaitingForRestartState, mTetheredState));
368 allStates.add(new StateInfo(mUnavailableState, null));
369 addAllStates(allStates);
370 }
markchien74a4fa92019-09-09 20:50:49 +0800371
Mark21502962022-12-21 06:58:23 +0000372 private Handler getHandler() {
373 return mHandler;
374 }
375
376 /** Start IpServer state machine. */
377 public void start() {
378 start(mInitialState);
markchien74a4fa92019-09-09 20:50:49 +0800379 }
380
381 /** Interface name which IpServer served.*/
382 public String interfaceName() {
383 return mIfaceName;
384 }
385
386 /**
markchien9b4d7572019-12-25 19:40:32 +0800387 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800388 */
389 public int interfaceType() {
390 return mInterfaceType;
391 }
392
393 /** Last error from this IpServer. */
394 public int lastError() {
395 return mLastError;
396 }
397
398 /** Serving mode is the current state of IpServer state machine. */
399 public int servingMode() {
400 return mServingMode;
401 }
402
403 /** The properties of the network link which IpServer is serving. */
404 public LinkProperties linkProperties() {
405 return new LinkProperties(mLinkProperties);
406 }
407
markchienc9daba32020-02-12 00:19:21 +0800408 /** The address which IpServer is using. */
409 public LinkAddress getAddress() {
410 return mIpv4Address;
411 }
412
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900413 /**
414 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
415 * thread.
416 */
417 public List<TetheredClient> getAllLeases() {
418 return Collections.unmodifiableList(mDhcpLeases);
419 }
420
Marka5424582022-12-01 13:46:32 +0000421 /** Enable this IpServer. IpServer state machine will be tethered or localHotspot state. */
422 public void enable(final int requestedState, final TetheringRequestParcel request) {
423 sendMessage(CMD_TETHER_REQUESTED, requestedState, 0, request);
424 }
425
markchien74a4fa92019-09-09 20:50:49 +0800426 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
427 public void stop() {
428 sendMessage(CMD_INTERFACE_DOWN);
429 }
430
431 /**
432 * Tethering is canceled. IpServer state machine will be available and wait for
433 * next tethering request.
434 */
435 public void unwanted() {
436 sendMessage(CMD_TETHER_UNREQUESTED);
437 }
438
439 /** Internals. */
440
Mark49649c92023-03-15 06:45:04 +0000441 private boolean startIPv4(int scope) {
442 return configureIPv4(true, scope);
markchien74a4fa92019-09-09 20:50:49 +0800443 }
444
445 /**
446 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
447 * handler.
448 *
449 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
450 * with different implementations of the callback, to differentiate handling of success/error in
451 * each call.
452 */
453 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
454 @Override
455 public void onStatusAvailable(int statusCode) {
456 getHandler().post(() -> callback(statusCode));
457 }
458
459 public abstract void callback(int statusCode);
460
461 @Override
462 public int getInterfaceVersion() {
463 return this.VERSION;
464 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900465
466 @Override
467 public String getInterfaceHash() {
468 return this.HASH;
469 }
markchien74a4fa92019-09-09 20:50:49 +0800470 }
471
472 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
473 private final int mStartIndex;
474
475 private DhcpServerCallbacksImpl(int startIndex) {
476 mStartIndex = startIndex;
477 }
478
479 @Override
480 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
481 getHandler().post(() -> {
482 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
483 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800484 // This start request is obsolete. Explicitly stop the DHCP server to shut
485 // down its thread. When the |server| binder token goes out of scope, the
486 // garbage collector will finalize it, which causes the network stack process
487 // garbage collector to collect the server itself.
488 try {
489 server.stop(null);
490 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800491 return;
492 }
493
494 if (statusCode != STATUS_SUCCESS) {
495 mLog.e("Error obtaining DHCP server: " + statusCode);
496 handleError();
497 return;
498 }
499
500 mDhcpServer = server;
501 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900502 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800503 @Override
504 public void callback(int startStatusCode) {
505 if (startStatusCode != STATUS_SUCCESS) {
506 mLog.e("Error starting DHCP server: " + startStatusCode);
507 handleError();
508 }
509 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900510 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800511 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800512 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800513 }
514 });
515 }
516
517 private void handleError() {
Mark74461fc2022-12-14 08:49:40 +0000518 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
Markcf11be92023-12-05 08:19:15 +0000519 if (mIsSyncSM) {
Markbe99f862022-12-21 16:39:23 +0000520 sendMessage(CMD_SERVICE_FAILED_TO_START, TETHER_ERROR_DHCPSERVER_ERROR);
521 } else {
522 sendMessageAtFrontOfQueueToAsyncSM(CMD_SERVICE_FAILED_TO_START,
523 TETHER_ERROR_DHCPSERVER_ERROR);
524 }
markchien74a4fa92019-09-09 20:50:49 +0800525 }
526 }
527
Xiao Ma4455d6b2020-04-09 10:13:44 +0900528 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900529 @Override
530 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
531 final ArrayList<TetheredClient> leases = new ArrayList<>();
532 for (DhcpLeaseParcelable lease : leaseParcelables) {
533 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900534 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
535 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
536 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900537
538 final MacAddress macAddress;
539 try {
540 macAddress = MacAddress.fromBytes(lease.hwAddr);
541 } catch (IllegalArgumentException e) {
542 Log.wtf(TAG, "Invalid address received from DhcpServer: "
543 + Arrays.toString(lease.hwAddr));
544 return;
545 }
546
547 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900548 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900549 leases.add(new TetheredClient(
550 macAddress,
551 Collections.singletonList(addressInfo),
552 mInterfaceType));
553 }
554
555 getHandler().post(() -> {
556 mDhcpLeases = leases;
557 mCallback.dhcpLeasesChanged();
558 });
559 }
560
561 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900562 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
563 Objects.requireNonNull(currentPrefix);
564 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900565 }
566
567 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900568 public int getInterfaceVersion() {
569 return this.VERSION;
570 }
571
572 @Override
573 public String getInterfaceHash() throws RemoteException {
574 return this.HASH;
575 }
576 }
577
Xiao Ma4455d6b2020-04-09 10:13:44 +0900578 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
579 Objects.requireNonNull(ipv4Address);
580 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
581 }
582
583 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
584 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
585 @Nullable Inet4Address clientAddr) {
586 final boolean changePrefixOnDecline =
587 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
markchienfb65dfe2022-02-25 23:14:58 +0800588 final int subnetPrefixLength = mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
589 ? mP2pLeasesSubnetPrefixLength : 0 /* default value */;
590
Xiao Ma4455d6b2020-04-09 10:13:44 +0900591 return new DhcpServingParamsParcelExt()
592 .setDefaultRouters(defaultRouter)
593 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
594 .setDnsServers(dnsServer)
595 .setServerAddr(serverAddr)
596 .setMetered(true)
597 .setSingleClientAddr(clientAddr)
markchienfb65dfe2022-02-25 23:14:58 +0800598 .setChangePrefixOnDecline(changePrefixOnDecline)
599 .setLeasesSubnetPrefixLength(subnetPrefixLength);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900600 // TODO: also advertise link MTU
601 }
602
markchien245352e2020-02-27 20:27:18 +0800603 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800604 if (mUsingLegacyDhcp) {
605 return true;
606 }
markchien245352e2020-02-27 20:27:18 +0800607
608 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800609 final Inet4Address clientAddr = clientLinkAddr == null ? null :
610 (Inet4Address) clientLinkAddr.getAddress();
611
Xiao Ma4455d6b2020-04-09 10:13:44 +0900612 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
613 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800614 mDhcpServerStartIndex++;
615 mDeps.makeDhcpServer(
616 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
617 return true;
618 }
619
620 private void stopDhcp() {
621 // Make all previous start requests obsolete so servers are not started later
622 mDhcpServerStartIndex++;
623
624 if (mDhcpServer != null) {
625 try {
626 mDhcpServer.stop(new OnHandlerStatusCallback() {
627 @Override
628 public void callback(int statusCode) {
629 if (statusCode != STATUS_SUCCESS) {
630 mLog.e("Error stopping DHCP server: " + statusCode);
Mark74461fc2022-12-14 08:49:40 +0000631 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800632 // Not much more we can do here
633 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900634 mDhcpLeases.clear();
635 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800636 }
637 });
638 mDhcpServer = null;
639 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900640 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800641 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800642 }
643 }
644 }
645
markchien245352e2020-02-27 20:27:18 +0800646 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
647 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800648 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800649 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800650 } else {
651 stopDhcp();
652 return true;
653 }
654 }
655
656 private void stopIPv4() {
Mark49649c92023-03-15 06:45:04 +0000657 configureIPv4(false /* enabled */, CONNECTIVITY_SCOPE_GLOBAL /* not used */);
markchien74a4fa92019-09-09 20:50:49 +0800658 // NOTE: All of configureIPv4() will be refactored out of existence
659 // into calls to InterfaceController, shared with startIPv4().
660 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800661 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800662 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800663 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800664 mStaticIpv4ServerAddr = null;
665 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800666 }
667
Mark49649c92023-03-15 06:45:04 +0000668 private boolean configureIPv4(boolean enabled, int scope) {
markchien74a4fa92019-09-09 20:50:49 +0800669 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
670
markchienc9daba32020-02-12 00:19:21 +0800671 if (enabled) {
Mark49649c92023-03-15 06:45:04 +0000672 mIpv4Address = requestIpv4Address(scope, true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800673 }
674
675 if (mIpv4Address == null) {
676 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800677 return false;
markchien74a4fa92019-09-09 20:50:49 +0800678 }
679
markchien69681d62021-11-15 23:58:05 +0800680 if (shouldNotConfigureBluetoothInterface()) {
681 // Interface was already configured elsewhere, only start DHCP.
markchienc9daba32020-02-12 00:19:21 +0800682 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
683 }
684
685 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
686
markchien12c5bb82020-01-07 14:43:17 +0800687 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800688 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900689 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200690 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
691 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900692 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800693 // It is unclear whether the Bluetooth or USB stacks will manage their own
694 // state.
695 setIfaceUp = null;
696 } else {
697 setIfaceUp = enabled;
698 }
699 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
700 mLog.e("Error configuring interface");
701 if (!enabled) stopDhcp();
702 return false;
703 }
markchien74a4fa92019-09-09 20:50:49 +0800704
markchien74a4fa92019-09-09 20:50:49 +0800705 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800706 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900707 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800708 } else {
markchien12c5bb82020-01-07 14:43:17 +0800709 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900710 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800711 }
markchien245352e2020-02-27 20:27:18 +0800712 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800713 }
714
markchien69681d62021-11-15 23:58:05 +0800715 private boolean shouldNotConfigureBluetoothInterface() {
716 // Before T, bluetooth tethering configures the interface elsewhere.
717 return (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) && !SdkLevel.isAtLeastT();
718 }
719
Mark49649c92023-03-15 06:45:04 +0000720 private LinkAddress requestIpv4Address(final int scope, final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800721 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800722
markchien69681d62021-11-15 23:58:05 +0800723 if (shouldNotConfigureBluetoothInterface()) return new LinkAddress(BLUETOOTH_IFACE_ADDR);
markchienc9daba32020-02-12 00:19:21 +0800724
Mark49649c92023-03-15 06:45:04 +0000725 return mPrivateAddressCoordinator.requestDownstreamAddress(this, scope, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900726 }
727
markchien74a4fa92019-09-09 20:50:49 +0800728 private boolean startIPv6() {
729 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
730 if (mInterfaceParams == null) {
731 mLog.e("Failed to find InterfaceParams");
732 stopIPv6();
733 return false;
734 }
735
736 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
737 if (!mRaDaemon.start()) {
738 stopIPv6();
739 return false;
740 }
741
markchien932df542021-08-12 13:56:43 +0800742 if (SdkLevel.isAtLeastS()) {
Tyler Wear90e40632020-03-13 11:38:38 -0700743 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
744 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
745 }
746
markchien74a4fa92019-09-09 20:50:49 +0800747 return true;
748 }
749
750 private void stopIPv6() {
751 mInterfaceParams = null;
752 setRaParams(null);
753
754 if (mRaDaemon != null) {
755 mRaDaemon.stop();
756 mRaDaemon = null;
757 }
Tyler Wear90e40632020-03-13 11:38:38 -0700758
759 if (mDadProxy != null) {
760 mDadProxy.stop();
761 mDadProxy = null;
762 }
markchien74a4fa92019-09-09 20:50:49 +0800763 }
764
765 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
766 // LinkProperties. These have extraneous data filtered out and only the
767 // necessary prefixes included (per its prefix distribution policy).
768 //
769 // TODO: Evaluate using a data structure than is more directly suited to
770 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800771 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800772 if (mRaDaemon == null) return;
773
774 // Avoid unnecessary work on spurious updates.
775 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
776 return;
777 }
778
779 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700780 String upstreamIface = null;
781 InterfaceParams upstreamIfaceParams = null;
KH Shi701c3ca2023-08-16 13:19:33 +0000782 int upstreamIfIndex = NO_UPSTREAM;
markchien74a4fa92019-09-09 20:50:49 +0800783
784 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700785 upstreamIface = v6only.getInterfaceName();
786 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
787 if (upstreamIfaceParams != null) {
788 upstreamIfIndex = upstreamIfaceParams.index;
789 }
markchien74a4fa92019-09-09 20:50:49 +0800790 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700791 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800792 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
793
markchiend63c4f32020-05-21 17:38:28 +0800794 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800795
KH Shi3f738fc2023-05-23 22:37:17 +0800796 params.prefixes = getTetherableIpv6Prefixes(v6only);
797 for (IpPrefix prefix : params.prefixes) {
markchien74a4fa92019-09-09 20:50:49 +0800798 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
799 if (dnsServer != null) {
800 params.dnses.add(dnsServer);
801 }
802 }
803 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900804
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900805 // Add upstream index to name mapping. See the comment of the interface mapping update in
806 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
807 // timing issue. It prevents that the IPv6 capability is updated later than
808 // CMD_TETHER_CONNECTION_CHANGED.
KH Shi701c3ca2023-08-16 13:19:33 +0000809 mBpfCoordinator.maybeAddUpstreamToLookupTable(upstreamIfIndex, upstreamIface);
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900810
markchien74a4fa92019-09-09 20:50:49 +0800811 // If v6only is null, we pass in null to setRaParams(), which handles
812 // deprecation of any existing RA data.
markchien74a4fa92019-09-09 20:50:49 +0800813 setRaParams(params);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900814
KH Shi68770342023-08-17 14:34:31 +0000815 // Not support BPF on virtual upstream interface
816 final boolean upstreamSupportsBpf = upstreamIface != null && !isVcnInterface(upstreamIface);
KH Shi3f738fc2023-05-23 22:37:17 +0800817 final Set<IpPrefix> upstreamPrefixes = params != null ? params.prefixes : Set.of();
818 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamPrefixes,
819 upstreamIfIndex, upstreamPrefixes, upstreamSupportsBpf);
KH Shi68770342023-08-17 14:34:31 +0000820 mLastIPv6LinkProperties = v6only;
Tyler Wear90e40632020-03-13 11:38:38 -0700821 mLastIPv6UpstreamIfindex = upstreamIfIndex;
KH Shi3f738fc2023-05-23 22:37:17 +0800822 mLastIPv6UpstreamPrefixes = upstreamPrefixes;
KH Shi68770342023-08-17 14:34:31 +0000823 mUpstreamSupportsBpf = upstreamSupportsBpf;
Tyler Wear90e40632020-03-13 11:38:38 -0700824 if (mDadProxy != null) {
825 mDadProxy.setUpstreamIface(upstreamIfaceParams);
826 }
markchien74a4fa92019-09-09 20:50:49 +0800827 }
828
Xiao Ma4455d6b2020-04-09 10:13:44 +0900829 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900830 final int removalFailures = NetdUtils.removeRoutesFromLocalNetwork(
Xiao Ma4455d6b2020-04-09 10:13:44 +0900831 mNetd, toBeRemoved);
832 if (removalFailures > 0) {
833 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
834 removalFailures));
835 }
836
837 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
838 }
839
Chalard Jean2fb66f12023-08-25 12:50:37 +0900840 private void addInterfaceToNetwork(final int netId, @NonNull final String ifaceName) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900841 try {
Motomu Utsumiac7c5722023-11-15 11:51:42 +0900842 if (SdkLevel.isAtLeastS() && null != mRoutingCoordinator.value) {
Chalard Jean2fb66f12023-08-25 12:50:37 +0900843 // TODO : remove this call in favor of using the LocalNetworkConfiguration
844 // correctly, which will let ConnectivityService do it automatically.
845 mRoutingCoordinator.value.addInterfaceToNetwork(netId, ifaceName);
846 } else {
847 mNetd.networkAddInterface(netId, ifaceName);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900848 }
849 } catch (ServiceSpecificException | RemoteException e) {
850 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
Chalard Jean820ce9d2023-10-06 18:31:08 +0900851 }
852 }
853
854 private void addInterfaceForward(@NonNull final String fromIface,
855 @NonNull final String toIface) throws ServiceSpecificException, RemoteException {
Motomu Utsumiac7c5722023-11-15 11:51:42 +0900856 if (SdkLevel.isAtLeastS() && null != mRoutingCoordinator.value) {
Chalard Jean820ce9d2023-10-06 18:31:08 +0900857 mRoutingCoordinator.value.addInterfaceForward(fromIface, toIface);
858 } else {
859 mNetd.tetherAddForward(fromIface, toIface);
860 mNetd.ipfwdAddInterfaceForward(fromIface, toIface);
861 }
862 }
863
864 private void removeInterfaceForward(@NonNull final String fromIface,
865 @NonNull final String toIface) {
Motomu Utsumiac7c5722023-11-15 11:51:42 +0900866 if (SdkLevel.isAtLeastS() && null != mRoutingCoordinator.value) {
Chalard Jean820ce9d2023-10-06 18:31:08 +0900867 try {
868 mRoutingCoordinator.value.removeInterfaceForward(fromIface, toIface);
869 } catch (ServiceSpecificException e) {
870 mLog.e("Exception in removeInterfaceForward", e);
871 }
872 } else {
873 try {
874 mNetd.ipfwdRemoveInterfaceForward(fromIface, toIface);
875 } catch (RemoteException | ServiceSpecificException e) {
876 mLog.e("Exception in ipfwdRemoveInterfaceForward", e);
877 }
878 try {
879 mNetd.tetherRemoveForward(fromIface, toIface);
880 } catch (RemoteException | ServiceSpecificException e) {
881 mLog.e("Exception in disableNat", e);
882 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900883 }
Chalard Jean2fb66f12023-08-25 12:50:37 +0900884 }
885
886 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
887 // It's safe to call addInterfaceToNetwork() even if
888 // the interface is already in the local_network.
889 addInterfaceToNetwork(INetd.LOCAL_NET_ID, mIfaceName);
890 try {
891 // Add routes from local network. Note that adding routes that
892 // already exist does not cause an error (EEXIST is silently ignored).
893 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
894 } catch (IllegalStateException e) {
895 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
896 return;
897 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900898
899 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
900 }
901
markchien74a4fa92019-09-09 20:50:49 +0800902 private void configureLocalIPv6Routes(
903 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
904 // [1] Remove the routes that are deprecated.
905 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900906 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800907 }
908
909 // [2] Add only the routes that have not previously been added.
910 if (newPrefixes != null && !newPrefixes.isEmpty()) {
911 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
912 if (mLastRaParams != null) {
913 addedPrefixes.removeAll(mLastRaParams.prefixes);
914 }
915
916 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900917 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800918 }
919 }
920 }
921
922 private void configureLocalIPv6Dns(
923 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
924 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
925 if (mNetd == null) {
926 if (newDnses != null) newDnses.clear();
927 mLog.e("No netd service instance available; not setting local IPv6 addresses");
928 return;
929 }
930
931 // [1] Remove deprecated local DNS IP addresses.
932 if (!deprecatedDnses.isEmpty()) {
933 for (Inet6Address dns : deprecatedDnses) {
934 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
935 mLog.e("Failed to remove local dns IP " + dns);
936 }
937
938 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
939 }
940 }
941
942 // [2] Add only the local DNS IP addresses that have not previously been added.
943 if (newDnses != null && !newDnses.isEmpty()) {
944 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
945 if (mLastRaParams != null) {
946 addedDnses.removeAll(mLastRaParams.dnses);
947 }
948
949 for (Inet6Address dns : addedDnses) {
950 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
951 mLog.e("Failed to add local dns IP " + dns);
952 newDnses.remove(dns);
953 }
954
955 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
956 }
957 }
958
959 try {
960 mNetd.tetherApplyDnsInterfaces();
961 } catch (ServiceSpecificException | RemoteException e) {
962 mLog.e("Failed to update local DNS caching server");
963 if (newDnses != null) newDnses.clear();
964 }
965 }
966
KH Shi701c3ca2023-08-16 13:19:33 +0000967 private int getInterfaceIndexForRule(int ifindex, boolean supportsBpf) {
968 return supportsBpf ? ifindex : NO_UPSTREAM;
969 }
970
KH Shi3f738fc2023-05-23 22:37:17 +0800971 // Handles updates to IPv6 forwarding rules if the upstream or its prefixes change.
972 private void updateIpv6ForwardingRules(int prevUpstreamIfindex,
973 @NonNull Set<IpPrefix> prevUpstreamPrefixes, int upstreamIfindex,
974 @NonNull Set<IpPrefix> upstreamPrefixes, boolean upstreamSupportsBpf) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900975 // If the upstream interface has changed, remove all rules and re-add them with the new
KH Shi701c3ca2023-08-16 13:19:33 +0000976 // upstream interface. If upstream is a virtual network, treated as no upstream.
KH Shi3f738fc2023-05-23 22:37:17 +0800977 if (prevUpstreamIfindex != upstreamIfindex
978 || !prevUpstreamPrefixes.equals(upstreamPrefixes)) {
KH Shi701c3ca2023-08-16 13:19:33 +0000979 mBpfCoordinator.updateAllIpv6Rules(this, this.mInterfaceParams,
KH Shi3f738fc2023-05-23 22:37:17 +0800980 getInterfaceIndexForRule(upstreamIfindex, upstreamSupportsBpf),
981 upstreamPrefixes);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900982 }
KH Shi701c3ca2023-08-16 13:19:33 +0000983 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900984
KH Shi701c3ca2023-08-16 13:19:33 +0000985 // Handles updates to IPv6 downstream rules if a neighbor event is received.
986 private void addOrRemoveIpv6Downstream(NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900987 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900988 if (e == null) return;
989 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
990 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
991 return;
992 }
993
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900994 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
KH Shi59ad35e2023-08-15 07:13:00 +0000995 // Do this here instead of in the Ipv6DownstreamRule constructor to ensure that we
996 // never add rules with a null MAC, only delete them.
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900997 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
KH Shi701c3ca2023-08-16 13:19:33 +0000998 Ipv6DownstreamRule rule = new Ipv6DownstreamRule(
999 getInterfaceIndexForRule(mLastIPv6UpstreamIfindex, mUpstreamSupportsBpf),
1000 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001001 if (e.isValid()) {
KH Shie4d549a2023-08-28 09:57:34 +00001002 mBpfCoordinator.addIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001003 } else {
KH Shie4d549a2023-08-28 09:57:34 +00001004 mBpfCoordinator.removeIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001005 }
1006 }
1007
Hungming Chend71c06e2020-12-21 19:39:49 +08001008 // TODO: consider moving into BpfCoordinator.
1009 private void updateClientInfoIpv4(NeighborEvent e) {
Hungming Chend71c06e2020-12-21 19:39:49 +08001010 if (e == null) return;
1011 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
1012 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
1013 return;
1014 }
1015
1016 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
1017 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
1018 // IpServer never add clients with a null MAC, only delete them.
1019 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
1020 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
1021 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
1022 if (e.isValid()) {
1023 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
1024 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +08001025 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
1026 }
1027 }
1028
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001029 private void handleNeighborEvent(NeighborEvent e) {
1030 if (mInterfaceParams != null
1031 && mInterfaceParams.index == e.ifindex
1032 && mInterfaceParams.hasMacAddress) {
KH Shi701c3ca2023-08-16 13:19:33 +00001033 addOrRemoveIpv6Downstream(e);
Hungming Chend71c06e2020-12-21 19:39:49 +08001034 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001035 }
1036 }
1037
markchiend63c4f32020-05-21 17:38:28 +08001038 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001039 try {
1040 int upstreamHopLimit = Integer.parseUnsignedInt(
1041 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001042 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001043 // Cap the hop limit to 255.
1044 return (byte) Integer.min(upstreamHopLimit, 255);
1045 } catch (Exception e) {
1046 mLog.e("Failed to find upstream interface hop limit", e);
1047 }
1048 return RaParams.DEFAULT_HOPLIMIT;
1049 }
1050
1051 private void setRaParams(RaParams newParams) {
1052 if (mRaDaemon != null) {
1053 final RaParams deprecatedParams =
1054 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1055
1056 configureLocalIPv6Routes(deprecatedParams.prefixes,
1057 (newParams != null) ? newParams.prefixes : null);
1058
1059 configureLocalIPv6Dns(deprecatedParams.dnses,
1060 (newParams != null) ? newParams.dnses : null);
1061
1062 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1063 }
1064
1065 mLastRaParams = newParams;
1066 }
1067
markchien21021ef2021-06-01 10:58:04 +08001068 private void maybeLogMessage(State state, int what) {
1069 switch (what) {
1070 // Suppress some CMD_* to avoid log flooding.
1071 case CMD_IPV6_TETHER_UPDATE:
1072 case CMD_NEIGHBOR_EVENT:
1073 break;
1074 default:
1075 mLog.log(state.getName() + " got "
1076 + sMagicDecoderRing.get(what, Integer.toString(what)));
1077 }
markchien74a4fa92019-09-09 20:50:49 +08001078 }
1079
1080 private void sendInterfaceState(int newInterfaceState) {
1081 mServingMode = newInterfaceState;
1082 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1083 sendLinkProperties();
1084 }
1085
1086 private void sendLinkProperties() {
1087 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1088 }
1089
1090 private void resetLinkProperties() {
1091 mLinkProperties.clear();
1092 mLinkProperties.setInterfaceName(mIfaceName);
1093 }
1094
markchienf053e4b2020-03-16 21:49:48 +08001095 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001096 // Ignore static address configuration if they are invalid or null. In theory, static
1097 // addresses should not be invalid here because TetheringManager do not allow caller to
1098 // specify invalid static address configuration.
1099 if (request == null || request.localIPv4Address == null
1100 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1101 request.localIPv4Address, request.staticClientAddress)) {
1102 return;
1103 }
markchienf053e4b2020-03-16 21:49:48 +08001104
1105 mStaticIpv4ServerAddr = request.localIPv4Address;
1106 mStaticIpv4ClientAddr = request.staticClientAddress;
1107 }
1108
markchien74a4fa92019-09-09 20:50:49 +08001109 class InitialState extends State {
1110 @Override
1111 public void enter() {
1112 sendInterfaceState(STATE_AVAILABLE);
1113 }
1114
1115 @Override
1116 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001117 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001118 switch (message.what) {
1119 case CMD_TETHER_REQUESTED:
Mark74461fc2022-12-14 08:49:40 +00001120 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001121 switch (message.arg1) {
1122 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001123 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001124 transitionTo(mLocalHotspotState);
1125 break;
1126 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001127 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001128 transitionTo(mTetheredState);
1129 break;
1130 default:
1131 mLog.e("Invalid tethering interface serving state specified.");
1132 }
1133 break;
1134 case CMD_INTERFACE_DOWN:
1135 transitionTo(mUnavailableState);
1136 break;
markchien74a4fa92019-09-09 20:50:49 +08001137 default:
1138 return NOT_HANDLED;
1139 }
1140 return HANDLED;
1141 }
1142 }
1143
Hungming Chen46c30b12020-10-15 17:25:36 +08001144 private void startConntrackMonitoring() {
1145 mBpfCoordinator.startMonitoring(this);
1146 }
1147
1148 private void stopConntrackMonitoring() {
1149 mBpfCoordinator.stopMonitoring(this);
1150 }
1151
Mark3ec851e2023-05-19 08:50:38 +00001152 abstract class BaseServingState extends State {
1153 private final int mDesiredInterfaceState;
1154
1155 BaseServingState(int interfaceState) {
1156 mDesiredInterfaceState = interfaceState;
1157 }
1158
markchien74a4fa92019-09-09 20:50:49 +08001159 @Override
1160 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001161 startConntrackMonitoring();
1162
Mark3ec851e2023-05-19 08:50:38 +00001163 startServingInterface();
1164
1165 if (mLastError != TETHER_ERROR_NO_ERROR) {
Mark50eef832023-09-19 06:56:14 +00001166 // This will transition to InitialState right away, regardless of whether any
1167 // message is already waiting in the StateMachine queue (including maybe some
1168 // message to go to InitialState). InitialState will then process any pending
1169 // message (and generally ignores them). It is difficult to know for sure whether
1170 // this is correct in all cases, but this is equivalent to what IpServer was doing
1171 // in previous versions of the mainline module.
Markbe99f862022-12-21 16:39:23 +00001172 // TODO : remove sendMessageAtFrontOfQueueToAsyncSM after migrating to the Sync
1173 // StateMachine.
Markcf11be92023-12-05 08:19:15 +00001174 if (mIsSyncSM) {
Markbe99f862022-12-21 16:39:23 +00001175 sendSelfMessageToSyncSM(CMD_SERVICE_FAILED_TO_START, mLastError);
1176 } else {
1177 sendMessageAtFrontOfQueueToAsyncSM(CMD_SERVICE_FAILED_TO_START, mLastError);
1178 }
Mark3ec851e2023-05-19 08:50:38 +00001179 }
1180
1181 if (DBG) Log.d(TAG, getStateString(mDesiredInterfaceState) + " serve " + mIfaceName);
1182 sendInterfaceState(mDesiredInterfaceState);
1183 }
1184
Mark49649c92023-03-15 06:45:04 +00001185 private int getScope() {
1186 if (mDesiredInterfaceState == STATE_TETHERED) {
1187 return CONNECTIVITY_SCOPE_GLOBAL;
1188 }
1189
1190 return CONNECTIVITY_SCOPE_LOCAL;
1191 }
1192
Mark3ec851e2023-05-19 08:50:38 +00001193 private void startServingInterface() {
Mark49649c92023-03-15 06:45:04 +00001194 if (!startIPv4(getScope())) {
Mark74461fc2022-12-14 08:49:40 +00001195 mLastError = TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001196 return;
1197 }
1198
1199 try {
markchienc9daba32020-02-12 00:19:21 +08001200 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001201 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001202 mLog.e("Error Tethering", e);
Mark74461fc2022-12-14 08:49:40 +00001203 mLastError = TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001204 return;
1205 }
1206
1207 if (!startIPv6()) {
1208 mLog.e("Failed to startIPv6");
1209 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1210 return;
1211 }
1212 }
1213
1214 @Override
1215 public void exit() {
1216 // Note that at this point, we're leaving the tethered state. We can fail any
1217 // of these operations, but it doesn't really change that we have to try them
1218 // all in sequence.
1219 stopIPv6();
1220
1221 try {
markchien12c5bb82020-01-07 14:43:17 +08001222 NetdUtils.untetherInterface(mNetd, mIfaceName);
1223 } catch (RemoteException | ServiceSpecificException e) {
Mark74461fc2022-12-14 08:49:40 +00001224 mLastError = TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001225 mLog.e("Failed to untether interface: " + e);
1226 }
1227
1228 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001229 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001230
1231 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001232
1233 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1234 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001235 }
1236
1237 @Override
1238 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001239 switch (message.what) {
1240 case CMD_TETHER_UNREQUESTED:
1241 transitionTo(mInitialState);
1242 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1243 break;
1244 case CMD_INTERFACE_DOWN:
1245 transitionTo(mUnavailableState);
1246 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1247 break;
1248 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001249 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001250 sendLinkProperties();
1251 break;
1252 case CMD_IP_FORWARDING_ENABLE_ERROR:
1253 case CMD_IP_FORWARDING_DISABLE_ERROR:
1254 case CMD_START_TETHERING_ERROR:
1255 case CMD_STOP_TETHERING_ERROR:
1256 case CMD_SET_DNS_FORWARDERS_ERROR:
Mark74461fc2022-12-14 08:49:40 +00001257 mLastError = TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001258 transitionTo(mInitialState);
1259 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001260 case CMD_NEW_PREFIX_REQUEST:
1261 handleNewPrefixRequest((IpPrefix) message.obj);
1262 break;
markchienc9daba32020-02-12 00:19:21 +08001263 case CMD_NOTIFY_PREFIX_CONFLICT:
1264 mLog.i("restart tethering: " + mInterfaceType);
1265 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1266 transitionTo(mWaitingForRestartState);
1267 break;
Mark50eef832023-09-19 06:56:14 +00001268 case CMD_SERVICE_FAILED_TO_START:
1269 mLog.e("start serving fail, error: " + message.arg1);
1270 transitionTo(mInitialState);
markchien74a4fa92019-09-09 20:50:49 +08001271 default:
1272 return false;
1273 }
1274 return true;
1275 }
Mark3ec851e2023-05-19 08:50:38 +00001276
1277 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
1278 if (!currentPrefix.contains(mIpv4Address.getAddress())
1279 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
1280 Log.e(TAG, "Invalid prefix: " + currentPrefix);
1281 return;
1282 }
1283
1284 final LinkAddress deprecatedLinkAddress = mIpv4Address;
Mark49649c92023-03-15 06:45:04 +00001285 mIpv4Address = requestIpv4Address(getScope(), false);
Mark3ec851e2023-05-19 08:50:38 +00001286 if (mIpv4Address == null) {
1287 mLog.e("Fail to request a new downstream prefix");
1288 return;
1289 }
1290 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
1291
1292 // Add new IPv4 address on the interface.
1293 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1294 mLog.e("Failed to add new IP " + srvAddr);
1295 return;
1296 }
1297
1298 // Remove deprecated routes from local network.
1299 removeRoutesFromLocalNetwork(
1300 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1301 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1302
1303 // Add new routes to local network.
1304 addRoutesToLocalNetwork(
1305 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1306 mLinkProperties.addLinkAddress(mIpv4Address);
1307
1308 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1309 // listen on the interface configured with new IPv4 address, that results DNS validation
1310 // failure of downstream client even if appropriate routes have been configured.
1311 try {
1312 mNetd.tetherApplyDnsInterfaces();
1313 } catch (ServiceSpecificException | RemoteException e) {
1314 mLog.e("Failed to update local DNS caching server");
1315 return;
1316 }
1317 sendLinkProperties();
1318
1319 // Notify DHCP server that new prefix/route has been applied on IpServer.
1320 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1321 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1322 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1323 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1324 try {
1325 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1326 @Override
1327 public void callback(int statusCode) {
1328 if (statusCode != STATUS_SUCCESS) {
1329 mLog.e("Error updating DHCP serving params: " + statusCode);
1330 }
1331 }
1332 });
1333 } catch (RemoteException e) {
1334 mLog.e("Error updating DHCP serving params", e);
1335 }
1336 }
markchien74a4fa92019-09-09 20:50:49 +08001337 }
1338
1339 // Handling errors in BaseServingState.enter() by transitioning is
1340 // problematic because transitioning during a multi-state jump yields
1341 // a Log.wtf(). Ultimately, there should be only one ServingState,
1342 // and forwarding and NAT rules should be handled by a coordinating
1343 // functional element outside of IpServer.
1344 class LocalHotspotState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001345 LocalHotspotState() {
1346 super(STATE_LOCAL_ONLY);
markchien74a4fa92019-09-09 20:50:49 +08001347 }
1348
1349 @Override
1350 public boolean processMessage(Message message) {
1351 if (super.processMessage(message)) return true;
1352
markchien21021ef2021-06-01 10:58:04 +08001353 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001354 switch (message.what) {
1355 case CMD_TETHER_REQUESTED:
1356 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1357 break;
1358 case CMD_TETHER_CONNECTION_CHANGED:
1359 // Ignored in local hotspot state.
1360 break;
1361 default:
1362 return false;
1363 }
1364 return true;
1365 }
1366 }
1367
1368 // Handling errors in BaseServingState.enter() by transitioning is
1369 // problematic because transitioning during a multi-state jump yields
1370 // a Log.wtf(). Ultimately, there should be only one ServingState,
1371 // and forwarding and NAT rules should be handled by a coordinating
1372 // functional element outside of IpServer.
1373 class TetheredState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001374 TetheredState() {
1375 super(STATE_TETHERED);
markchien74a4fa92019-09-09 20:50:49 +08001376 }
1377
1378 @Override
1379 public void exit() {
1380 cleanupUpstream();
KH Shi701c3ca2023-08-16 13:19:33 +00001381 mBpfCoordinator.clearAllIpv6Rules(IpServer.this);
markchien74a4fa92019-09-09 20:50:49 +08001382 super.exit();
1383 }
1384
Hungming Chena6e78692021-02-08 17:15:35 +08001385 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1386 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1387 // and behaviour. While upstream is switching from offload supported interface to
1388 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1389 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1390 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1391 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1392 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1393 // in the state machine. Once there is any case out whish is not covered by previous cases,
1394 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001395 private void cleanupUpstream() {
1396 if (mUpstreamIfaceSet == null) return;
1397
1398 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1399 mUpstreamIfaceSet = null;
KH Shi701c3ca2023-08-16 13:19:33 +00001400 mBpfCoordinator.updateAllIpv6Rules(
KH Shi3f738fc2023-05-23 22:37:17 +08001401 IpServer.this, IpServer.this.mInterfaceParams, NO_UPSTREAM, Set.of());
markchien74a4fa92019-09-09 20:50:49 +08001402 }
1403
1404 private void cleanupUpstreamInterface(String upstreamIface) {
1405 // Note that we don't care about errors here.
1406 // Sometimes interfaces are gone before we get
1407 // to remove their rules, which generates errors.
1408 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001409 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
Chalard Jean820ce9d2023-10-06 18:31:08 +09001410 removeInterfaceForward(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001411 }
1412
1413 @Override
1414 public boolean processMessage(Message message) {
1415 if (super.processMessage(message)) return true;
1416
markchien21021ef2021-06-01 10:58:04 +08001417 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001418 switch (message.what) {
1419 case CMD_TETHER_REQUESTED:
1420 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1421 break;
1422 case CMD_TETHER_CONNECTION_CHANGED:
1423 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1424 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1425 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1426 break;
1427 }
1428
1429 if (newUpstreamIfaceSet == null) {
1430 cleanupUpstream();
1431 break;
1432 }
1433
1434 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1435 cleanupUpstreamInterface(removed);
1436 }
1437
1438 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1439 // This makes the call to cleanupUpstream() in the error
1440 // path for any interface neatly cleanup all the interfaces.
1441 mUpstreamIfaceSet = newUpstreamIfaceSet;
1442
1443 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001444 // Add upstream index to name mapping for the tether stats usage in the
1445 // coordinator. Although this mapping could be added by both class
1446 // Tethering and IpServer, adding mapping from IpServer guarantees that
1447 // the mapping is added before adding forwarding rules. That is because
1448 // there are different state machines in both classes. It is hard to
1449 // guarantee the link property update order between multiple state machines.
1450 // Note that both IPv4 and IPv6 interface may be added because
1451 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1452 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1453 // capability may be updated later. In that case, IPv6 interface mapping is
1454 // updated in updateUpstreamIPv6LinkProperties.
1455 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1456 final InterfaceParams upstreamIfaceParams =
1457 mDeps.getInterfaceParams(ifname);
1458 if (upstreamIfaceParams != null) {
KH Shi701c3ca2023-08-16 13:19:33 +00001459 mBpfCoordinator.maybeAddUpstreamToLookupTable(
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001460 upstreamIfaceParams.index, ifname);
1461 }
1462 }
1463
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001464 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001465 try {
Chalard Jean820ce9d2023-10-06 18:31:08 +09001466 addInterfaceForward(mIfaceName, ifname);
markchien12c5bb82020-01-07 14:43:17 +08001467 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean820ce9d2023-10-06 18:31:08 +09001468 mLog.e("Exception enabling iface forward", e);
markchien74a4fa92019-09-09 20:50:49 +08001469 cleanupUpstream();
Mark74461fc2022-12-14 08:49:40 +00001470 mLastError = TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001471 transitionTo(mInitialState);
1472 return true;
1473 }
1474 }
1475 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001476 case CMD_NEIGHBOR_EVENT:
1477 handleNeighborEvent((NeighborEvent) message.obj);
1478 break;
markchien74a4fa92019-09-09 20:50:49 +08001479 default:
1480 return false;
1481 }
1482 return true;
1483 }
1484
1485 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1486 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1487 if (mUpstreamIfaceSet != null && newIfaces != null) {
1488 return mUpstreamIfaceSet.equals(newIfaces);
1489 }
1490 return false;
1491 }
1492
1493 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1494 if (mUpstreamIfaceSet == null) return new HashSet<>();
1495
1496 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1497 removed.removeAll(newIfaces.ifnames);
1498 return removed;
1499 }
1500
1501 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1502 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1503 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1504 return added;
1505 }
1506 }
1507
1508 /**
1509 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001510 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001511 * specific state machine from its list of possible recipients of
1512 * tethering requests. The state machine itself will hang around until
1513 * the garbage collector finds it.
1514 */
1515 class UnavailableState extends State {
1516 @Override
1517 public void enter() {
KH Shi701c3ca2023-08-16 13:19:33 +00001518 // TODO: move mIpNeighborMonitor.stop() to TetheredState#exit, and trigger a neighbours
1519 // dump after starting mIpNeighborMonitor.
h.zhangd244bd02020-06-14 14:46:54 +08001520 mIpNeighborMonitor.stop();
Mark74461fc2022-12-14 08:49:40 +00001521 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001522 sendInterfaceState(STATE_UNAVAILABLE);
1523 }
1524 }
1525
markchienc9daba32020-02-12 00:19:21 +08001526 class WaitingForRestartState extends State {
1527 @Override
1528 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001529 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001530 switch (message.what) {
1531 case CMD_TETHER_UNREQUESTED:
1532 transitionTo(mInitialState);
1533 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1534 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1535 break;
1536 case CMD_INTERFACE_DOWN:
1537 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001538 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001539 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1540 break;
1541 default:
1542 return false;
1543 }
1544 return true;
1545 }
1546 }
1547
markchien74a4fa92019-09-09 20:50:49 +08001548 // Accumulate routes representing "prefixes to be assigned to the local
1549 // interface", for subsequent modification of local_network routing.
1550 private static ArrayList<RouteInfo> getLocalRoutesFor(
1551 String ifname, HashSet<IpPrefix> prefixes) {
1552 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1553 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001554 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001555 }
1556 return localRoutes;
1557 }
1558
1559 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1560 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1561 final byte[] dnsBytes = localPrefix.getRawAddress();
1562 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1563 try {
1564 return Inet6Address.getByAddress(null, dnsBytes, 0);
1565 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001566 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001567 return null;
1568 }
1569 }
1570
1571 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1572 final byte random = (byte) (new Random()).nextInt();
1573 for (int value : excluded) {
1574 if (random == value) return dflt;
1575 }
1576 return random;
1577 }
KH Shi3f738fc2023-05-23 22:37:17 +08001578
1579 /** Get IPv6 prefixes from LinkProperties */
1580 @NonNull
1581 @VisibleForTesting
1582 static HashSet<IpPrefix> getTetherableIpv6Prefixes(@NonNull Collection<LinkAddress> addrs) {
1583 final HashSet<IpPrefix> prefixes = new HashSet<>();
1584 for (LinkAddress linkAddr : addrs) {
1585 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
1586 prefixes.add(new IpPrefix(linkAddr.getAddress(), RFC7421_PREFIX_LENGTH));
1587 }
1588 return prefixes;
1589 }
1590
1591 @NonNull
1592 private HashSet<IpPrefix> getTetherableIpv6Prefixes(@NonNull LinkProperties lp) {
1593 return getTetherableIpv6Prefixes(lp.getLinkAddresses());
1594 }
markchien74a4fa92019-09-09 20:50:49 +08001595}