blob: c04d0dcfcd0272536988c7c87850160d511d0b69 [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;
Mark21502962022-12-21 06:58:23 +000036import static com.android.networkstack.tethering.TetheringConfiguration.USE_SYNC_SM;
markchien7dc1b4d2021-07-13 17:12:56 +080037import static com.android.networkstack.tethering.UpstreamNetworkState.isVcnInterface;
markchiend02f9af2021-11-04 11:26:03 +080038import static com.android.networkstack.tethering.util.PrefixUtils.asIpPrefix;
39import static com.android.networkstack.tethering.util.TetheringMessageBase.BASE_IPSERVER;
Chalard Jean78701642020-07-31 20:00:30 +090040
markchien74a4fa92019-09-09 20:50:49 +080041import android.net.INetd;
42import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080043import android.net.IpPrefix;
44import android.net.LinkAddress;
45import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090046import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080047import android.net.RouteInfo;
Chalard Jean2fb66f12023-08-25 12:50:37 +090048import android.net.RoutingCoordinatorManager;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090049import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080050import android.net.TetheringManager;
markchienf053e4b2020-03-16 21:49:48 +080051import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090052import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080053import android.net.dhcp.DhcpServerCallbacks;
54import android.net.dhcp.DhcpServingParamsParcel;
55import android.net.dhcp.DhcpServingParamsParcelExt;
Xiao Ma49889dd2020-04-03 17:01:33 +090056import android.net.dhcp.IDhcpEventCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080057import android.net.dhcp.IDhcpServer;
58import android.net.ip.RouterAdvertisementDaemon.RaParams;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090059import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080060import android.os.Message;
61import android.os.RemoteException;
62import android.os.ServiceSpecificException;
63import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080064import android.util.SparseArray;
65
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090066import androidx.annotation.NonNull;
Xiao Ma4455d6b2020-04-09 10:13:44 +090067import androidx.annotation.Nullable;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090068
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;
95import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080096import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090097import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080098import java.util.Objects;
99import java.util.Random;
100import java.util.Set;
101
102/**
103 * Provides the interface to IP-layer serving functionality for a given network
104 * interface, e.g. for tethering or "local-only hotspot" mode.
105 *
106 * @hide
107 */
Mark21502962022-12-21 06:58:23 +0000108public class IpServer extends StateMachineShim {
markchien74a4fa92019-09-09 20:50:49 +0800109 public static final int STATE_UNAVAILABLE = 0;
110 public static final int STATE_AVAILABLE = 1;
111 public static final int STATE_TETHERED = 2;
112 public static final int STATE_LOCAL_ONLY = 3;
113
114 /** Get string name of |state|.*/
115 public static String getStateString(int state) {
116 switch (state) {
117 case STATE_UNAVAILABLE: return "UNAVAILABLE";
118 case STATE_AVAILABLE: return "AVAILABLE";
119 case STATE_TETHERED: return "TETHERED";
120 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
121 }
122 return "UNKNOWN: " + state;
123 }
124
125 private static final byte DOUG_ADAMS = (byte) 42;
126
markchien74a4fa92019-09-09 20:50:49 +0800127 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800128 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800129
130 // TODO: have this configurable
131 private static final int DHCP_LEASE_TIME_SECS = 3600;
132
KH Shi701c3ca2023-08-16 13:19:33 +0000133 private static final int NO_UPSTREAM = 0;
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900134 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
135
markchien74a4fa92019-09-09 20:50:49 +0800136 private static final String TAG = "IpServer";
137 private static final boolean DBG = false;
138 private static final boolean VDBG = false;
139 private static final Class[] sMessageClasses = {
140 IpServer.class
141 };
142 private static final SparseArray<String> sMagicDecoderRing =
143 MessageUtils.findMessageNames(sMessageClasses);
144
145 /** IpServer callback. */
146 public static class Callback {
147 /**
148 * Notify that |who| has changed its tethering state.
149 *
150 * @param who the calling instance of IpServer
151 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800152 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800153 */
markchien9d353822019-12-16 20:15:20 +0800154 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800155
156 /**
157 * Notify that |who| has new LinkProperties.
158 *
159 * @param who the calling instance of IpServer
160 * @param newLp the new LinkProperties to report
161 */
markchien9d353822019-12-16 20:15:20 +0800162 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900163
164 /**
165 * Notify that the DHCP leases changed in one of the IpServers.
166 */
167 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800168
169 /**
170 * Request Tethering change.
171 *
172 * @param tetheringType the downstream type of this IpServer.
173 * @param enabled enable or disable tethering.
174 */
175 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800176 }
177
178 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800179 public abstract static class Dependencies {
Tyler Wear90e40632020-03-13 11:38:38 -0700180 /**
181 * Create a DadProxy instance to be used by IpServer.
182 * To support multiple tethered interfaces concurrently DAD Proxy
183 * needs to be supported per IpServer instead of per upstream.
184 */
185 public DadProxy getDadProxy(Handler handler, InterfaceParams ifParams) {
186 return new DadProxy(handler, ifParams);
187 }
188
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900189 /** Create an IpNeighborMonitor to be used by this IpServer */
190 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
191 IpNeighborMonitor.NeighborEventConsumer consumer) {
192 return new IpNeighborMonitor(handler, log, consumer);
193 }
194
markchien74a4fa92019-09-09 20:50:49 +0800195 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
196 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
197 return new RouterAdvertisementDaemon(ifParams);
198 }
199
200 /** Get |ifName|'s interface information.*/
201 public InterfaceParams getInterfaceParams(String ifName) {
202 return InterfaceParams.getByName(ifName);
203 }
204
markchien9d353822019-12-16 20:15:20 +0800205 /** Create a DhcpServer instance to be used by IpServer. */
206 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
207 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800208 }
209
markchien74a4fa92019-09-09 20:50:49 +0800210 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800211 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800212 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800213 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800214 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800215 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800216 // notification from the {@link Tethering.TetherMainSM} that it had trouble enabling IP
217 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800218 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800219 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble disabling IP
220 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800221 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800222 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble starting
223 // tethering
markchien6cf0e552019-12-06 15:24:53 +0800224 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800225 // notification from the {@link Tethering.TetherMainSM} that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800226 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800227 // notification from the {@link Tethering.TetherMainSM} that it had trouble setting the DNS
228 // forwarders
markchien6cf0e552019-12-06 15:24:53 +0800229 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800230 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800231 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800232 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800233 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900234 // new neighbor cache entry on our interface
235 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900236 // request from DHCP server that it wants to have a new prefix
237 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800238 // request from PrivateAddressCoordinator to restart tethering.
239 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
Mark50eef832023-09-19 06:56:14 +0000240 public static final int CMD_SERVICE_FAILED_TO_START = BASE_IPSERVER + 14;
markchien74a4fa92019-09-09 20:50:49 +0800241
242 private final State mInitialState;
243 private final State mLocalHotspotState;
244 private final State mTetheredState;
245 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800246 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800247
248 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800249 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800250 @NonNull
251 private final BpfCoordinator mBpfCoordinator;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900252 // Contains null if the connectivity module is unsupported, as the routing coordinator is not
253 // available. Must use LateSdk because MessageUtils enumerates fields in this class, so it
254 // must be able to find all classes at runtime.
255 @NonNull
256 private final LateSdk<RoutingCoordinatorManager> mRoutingCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800257 private final Callback mCallback;
258 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800259 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800260
261 private final String mIfaceName;
262 private final int mInterfaceType;
263 private final LinkProperties mLinkProperties;
264 private final boolean mUsingLegacyDhcp;
markchienfb65dfe2022-02-25 23:14:58 +0800265 private final int mP2pLeasesSubnetPrefixLength;
markchien74a4fa92019-09-09 20:50:49 +0800266
267 private final Dependencies mDeps;
268
269 private int mLastError;
270 private int mServingMode;
271 private InterfaceSet mUpstreamIfaceSet; // may change over time
KH Shi701c3ca2023-08-16 13:19:33 +0000272 // mInterfaceParams can't be final now because IpServer will be created when receives
273 // WIFI_AP_STATE_CHANGED broadcasts or when it detects that the wifi interface has come up.
274 // In the latter case, the interface is not fully initialized and the MAC address might not
275 // be correct (it will be set with a randomized MAC address later).
276 // TODO: Consider create the IpServer only when tethering want to enable it, then we can
277 // make mInterfaceParams final.
markchien74a4fa92019-09-09 20:50:49 +0800278 private InterfaceParams mInterfaceParams;
279 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
280 // properties are those selected by the IPv6TetheringCoordinator and relayed
281 // to us. By comparison, mLinkProperties contains the addresses and directly
282 // connected routes that have been formed from these properties iff. we have
283 // succeeded in configuring them and are able to announce them within Router
284 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
285 private LinkProperties mLastIPv6LinkProperties;
286 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700287 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800288
289 // To be accessed only on the handler thread
290 private int mDhcpServerStartIndex = 0;
291 private IDhcpServer mDhcpServer;
292 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800293
294 private LinkAddress mStaticIpv4ServerAddr;
295 private LinkAddress mStaticIpv4ClientAddr;
296
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900297 @NonNull
298 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800299
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900300 private int mLastIPv6UpstreamIfindex = 0;
KH Shi68770342023-08-17 14:34:31 +0000301 private boolean mUpstreamSupportsBpf = false;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900302
303 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
304 public void accept(NeighborEvent e) {
305 sendMessage(CMD_NEIGHBOR_EVENT, e);
306 }
307 }
308
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900309 private final IpNeighborMonitor mIpNeighborMonitor;
310
markchienc9daba32020-02-12 00:19:21 +0800311 private LinkAddress mIpv4Address;
312
Wayne Ma6cd440f2022-03-14 18:04:33 +0800313 private final TetheringMetrics mTetheringMetrics;
Mark21502962022-12-21 06:58:23 +0000314 private final Handler mHandler;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800315
Hungming Chen5bc3af92020-05-12 19:15:24 +0800316 // TODO: Add a dependency object to pass the data members or variables from the tethering
317 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800318 public IpServer(
Mark21502962022-12-21 06:58:23 +0000319 String ifaceName, Handler handler, int interfaceType, SharedLog log,
Chalard Jean2fb66f12023-08-25 12:50:37 +0900320 INetd netd, @NonNull BpfCoordinator bpfCoordinator,
321 @Nullable LateSdk<RoutingCoordinatorManager> routingCoordinator, Callback callback,
markchienb961d3d2022-02-26 00:39:06 +0800322 TetheringConfiguration config, PrivateAddressCoordinator addressCoordinator,
Wayne Ma6cd440f2022-03-14 18:04:33 +0800323 TetheringMetrics tetheringMetrics, Dependencies deps) {
Mark21502962022-12-21 06:58:23 +0000324 super(ifaceName, USE_SYNC_SM ? null : handler.getLooper());
325 mHandler = handler;
markchien74a4fa92019-09-09 20:50:49 +0800326 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800327 mNetd = netd;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900328 mBpfCoordinator = bpfCoordinator;
329 mRoutingCoordinator = routingCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800330 mCallback = callback;
331 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
332 mIfaceName = ifaceName;
333 mInterfaceType = interfaceType;
334 mLinkProperties = new LinkProperties();
markchienb961d3d2022-02-26 00:39:06 +0800335 mUsingLegacyDhcp = config.useLegacyDhcpServer();
markchienfb65dfe2022-02-25 23:14:58 +0800336 mP2pLeasesSubnetPrefixLength = config.getP2pLeasesSubnetPrefixLength();
markchienc9daba32020-02-12 00:19:21 +0800337 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800338 mDeps = deps;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800339 mTetheringMetrics = tetheringMetrics;
markchien74a4fa92019-09-09 20:50:49 +0800340 resetLinkProperties();
Mark74461fc2022-12-14 08:49:40 +0000341 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800342 mServingMode = STATE_AVAILABLE;
343
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900344 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
345 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800346
KH Shie4d549a2023-08-28 09:57:34 +0000347 // IP neighbor monitor monitors the neighbor events for adding/removing IPv6 downstream rule
348 // per client. If BPF offload is not supported, don't start listening for neighbor events.
349 if (mBpfCoordinator.isUsingBpfOffload() && !mIpNeighborMonitor.start()) {
Hungming Chen5bc3af92020-05-12 19:15:24 +0800350 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900351 }
352
markchien74a4fa92019-09-09 20:50:49 +0800353 mInitialState = new InitialState();
354 mLocalHotspotState = new LocalHotspotState();
355 mTetheredState = new TetheredState();
356 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800357 mWaitingForRestartState = new WaitingForRestartState();
Mark21502962022-12-21 06:58:23 +0000358 final ArrayList allStates = new ArrayList<StateInfo>();
359 allStates.add(new StateInfo(mInitialState, null));
360 allStates.add(new StateInfo(mLocalHotspotState, null));
361 allStates.add(new StateInfo(mTetheredState, null));
362 allStates.add(new StateInfo(mWaitingForRestartState, mTetheredState));
363 allStates.add(new StateInfo(mUnavailableState, null));
364 addAllStates(allStates);
365 }
markchien74a4fa92019-09-09 20:50:49 +0800366
Mark21502962022-12-21 06:58:23 +0000367 private Handler getHandler() {
368 return mHandler;
369 }
370
371 /** Start IpServer state machine. */
372 public void start() {
373 start(mInitialState);
markchien74a4fa92019-09-09 20:50:49 +0800374 }
375
376 /** Interface name which IpServer served.*/
377 public String interfaceName() {
378 return mIfaceName;
379 }
380
381 /**
markchien9b4d7572019-12-25 19:40:32 +0800382 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800383 */
384 public int interfaceType() {
385 return mInterfaceType;
386 }
387
388 /** Last error from this IpServer. */
389 public int lastError() {
390 return mLastError;
391 }
392
393 /** Serving mode is the current state of IpServer state machine. */
394 public int servingMode() {
395 return mServingMode;
396 }
397
398 /** The properties of the network link which IpServer is serving. */
399 public LinkProperties linkProperties() {
400 return new LinkProperties(mLinkProperties);
401 }
402
markchienc9daba32020-02-12 00:19:21 +0800403 /** The address which IpServer is using. */
404 public LinkAddress getAddress() {
405 return mIpv4Address;
406 }
407
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900408 /**
409 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
410 * thread.
411 */
412 public List<TetheredClient> getAllLeases() {
413 return Collections.unmodifiableList(mDhcpLeases);
414 }
415
Marka5424582022-12-01 13:46:32 +0000416 /** Enable this IpServer. IpServer state machine will be tethered or localHotspot state. */
417 public void enable(final int requestedState, final TetheringRequestParcel request) {
418 sendMessage(CMD_TETHER_REQUESTED, requestedState, 0, request);
419 }
420
markchien74a4fa92019-09-09 20:50:49 +0800421 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
422 public void stop() {
423 sendMessage(CMD_INTERFACE_DOWN);
424 }
425
426 /**
427 * Tethering is canceled. IpServer state machine will be available and wait for
428 * next tethering request.
429 */
430 public void unwanted() {
431 sendMessage(CMD_TETHER_UNREQUESTED);
432 }
433
434 /** Internals. */
435
Mark49649c92023-03-15 06:45:04 +0000436 private boolean startIPv4(int scope) {
437 return configureIPv4(true, scope);
markchien74a4fa92019-09-09 20:50:49 +0800438 }
439
440 /**
441 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
442 * handler.
443 *
444 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
445 * with different implementations of the callback, to differentiate handling of success/error in
446 * each call.
447 */
448 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
449 @Override
450 public void onStatusAvailable(int statusCode) {
451 getHandler().post(() -> callback(statusCode));
452 }
453
454 public abstract void callback(int statusCode);
455
456 @Override
457 public int getInterfaceVersion() {
458 return this.VERSION;
459 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900460
461 @Override
462 public String getInterfaceHash() {
463 return this.HASH;
464 }
markchien74a4fa92019-09-09 20:50:49 +0800465 }
466
467 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
468 private final int mStartIndex;
469
470 private DhcpServerCallbacksImpl(int startIndex) {
471 mStartIndex = startIndex;
472 }
473
474 @Override
475 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
476 getHandler().post(() -> {
477 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
478 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800479 // This start request is obsolete. Explicitly stop the DHCP server to shut
480 // down its thread. When the |server| binder token goes out of scope, the
481 // garbage collector will finalize it, which causes the network stack process
482 // garbage collector to collect the server itself.
483 try {
484 server.stop(null);
485 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800486 return;
487 }
488
489 if (statusCode != STATUS_SUCCESS) {
490 mLog.e("Error obtaining DHCP server: " + statusCode);
491 handleError();
492 return;
493 }
494
495 mDhcpServer = server;
496 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900497 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800498 @Override
499 public void callback(int startStatusCode) {
500 if (startStatusCode != STATUS_SUCCESS) {
501 mLog.e("Error starting DHCP server: " + startStatusCode);
502 handleError();
503 }
504 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900505 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800506 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800507 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800508 }
509 });
510 }
511
512 private void handleError() {
Mark74461fc2022-12-14 08:49:40 +0000513 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
Mark50eef832023-09-19 06:56:14 +0000514 sendMessageAtFrontOfQueueToAsyncSM(CMD_SERVICE_FAILED_TO_START,
515 TETHER_ERROR_DHCPSERVER_ERROR);
markchien74a4fa92019-09-09 20:50:49 +0800516 }
517 }
518
Xiao Ma4455d6b2020-04-09 10:13:44 +0900519 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900520 @Override
521 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
522 final ArrayList<TetheredClient> leases = new ArrayList<>();
523 for (DhcpLeaseParcelable lease : leaseParcelables) {
524 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900525 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
526 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
527 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900528
529 final MacAddress macAddress;
530 try {
531 macAddress = MacAddress.fromBytes(lease.hwAddr);
532 } catch (IllegalArgumentException e) {
533 Log.wtf(TAG, "Invalid address received from DhcpServer: "
534 + Arrays.toString(lease.hwAddr));
535 return;
536 }
537
538 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900539 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900540 leases.add(new TetheredClient(
541 macAddress,
542 Collections.singletonList(addressInfo),
543 mInterfaceType));
544 }
545
546 getHandler().post(() -> {
547 mDhcpLeases = leases;
548 mCallback.dhcpLeasesChanged();
549 });
550 }
551
552 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900553 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
554 Objects.requireNonNull(currentPrefix);
555 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900556 }
557
558 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900559 public int getInterfaceVersion() {
560 return this.VERSION;
561 }
562
563 @Override
564 public String getInterfaceHash() throws RemoteException {
565 return this.HASH;
566 }
567 }
568
Xiao Ma4455d6b2020-04-09 10:13:44 +0900569 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
570 Objects.requireNonNull(ipv4Address);
571 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
572 }
573
574 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
575 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
576 @Nullable Inet4Address clientAddr) {
577 final boolean changePrefixOnDecline =
578 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
markchienfb65dfe2022-02-25 23:14:58 +0800579 final int subnetPrefixLength = mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
580 ? mP2pLeasesSubnetPrefixLength : 0 /* default value */;
581
Xiao Ma4455d6b2020-04-09 10:13:44 +0900582 return new DhcpServingParamsParcelExt()
583 .setDefaultRouters(defaultRouter)
584 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
585 .setDnsServers(dnsServer)
586 .setServerAddr(serverAddr)
587 .setMetered(true)
588 .setSingleClientAddr(clientAddr)
markchienfb65dfe2022-02-25 23:14:58 +0800589 .setChangePrefixOnDecline(changePrefixOnDecline)
590 .setLeasesSubnetPrefixLength(subnetPrefixLength);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900591 // TODO: also advertise link MTU
592 }
593
markchien245352e2020-02-27 20:27:18 +0800594 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800595 if (mUsingLegacyDhcp) {
596 return true;
597 }
markchien245352e2020-02-27 20:27:18 +0800598
599 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800600 final Inet4Address clientAddr = clientLinkAddr == null ? null :
601 (Inet4Address) clientLinkAddr.getAddress();
602
Xiao Ma4455d6b2020-04-09 10:13:44 +0900603 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
604 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800605 mDhcpServerStartIndex++;
606 mDeps.makeDhcpServer(
607 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
608 return true;
609 }
610
611 private void stopDhcp() {
612 // Make all previous start requests obsolete so servers are not started later
613 mDhcpServerStartIndex++;
614
615 if (mDhcpServer != null) {
616 try {
617 mDhcpServer.stop(new OnHandlerStatusCallback() {
618 @Override
619 public void callback(int statusCode) {
620 if (statusCode != STATUS_SUCCESS) {
621 mLog.e("Error stopping DHCP server: " + statusCode);
Mark74461fc2022-12-14 08:49:40 +0000622 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800623 // Not much more we can do here
624 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900625 mDhcpLeases.clear();
626 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800627 }
628 });
629 mDhcpServer = null;
630 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900631 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800632 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800633 }
634 }
635 }
636
markchien245352e2020-02-27 20:27:18 +0800637 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
638 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800639 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800640 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800641 } else {
642 stopDhcp();
643 return true;
644 }
645 }
646
647 private void stopIPv4() {
Mark49649c92023-03-15 06:45:04 +0000648 configureIPv4(false /* enabled */, CONNECTIVITY_SCOPE_GLOBAL /* not used */);
markchien74a4fa92019-09-09 20:50:49 +0800649 // NOTE: All of configureIPv4() will be refactored out of existence
650 // into calls to InterfaceController, shared with startIPv4().
651 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800652 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800653 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800654 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800655 mStaticIpv4ServerAddr = null;
656 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800657 }
658
Mark49649c92023-03-15 06:45:04 +0000659 private boolean configureIPv4(boolean enabled, int scope) {
markchien74a4fa92019-09-09 20:50:49 +0800660 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
661
markchienc9daba32020-02-12 00:19:21 +0800662 if (enabled) {
Mark49649c92023-03-15 06:45:04 +0000663 mIpv4Address = requestIpv4Address(scope, true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800664 }
665
666 if (mIpv4Address == null) {
667 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800668 return false;
markchien74a4fa92019-09-09 20:50:49 +0800669 }
670
markchien69681d62021-11-15 23:58:05 +0800671 if (shouldNotConfigureBluetoothInterface()) {
672 // Interface was already configured elsewhere, only start DHCP.
markchienc9daba32020-02-12 00:19:21 +0800673 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
674 }
675
676 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
677
markchien12c5bb82020-01-07 14:43:17 +0800678 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800679 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900680 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200681 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
682 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900683 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800684 // It is unclear whether the Bluetooth or USB stacks will manage their own
685 // state.
686 setIfaceUp = null;
687 } else {
688 setIfaceUp = enabled;
689 }
690 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
691 mLog.e("Error configuring interface");
692 if (!enabled) stopDhcp();
693 return false;
694 }
markchien74a4fa92019-09-09 20:50:49 +0800695
markchien74a4fa92019-09-09 20:50:49 +0800696 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800697 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900698 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800699 } else {
markchien12c5bb82020-01-07 14:43:17 +0800700 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900701 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800702 }
markchien245352e2020-02-27 20:27:18 +0800703 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800704 }
705
markchien69681d62021-11-15 23:58:05 +0800706 private boolean shouldNotConfigureBluetoothInterface() {
707 // Before T, bluetooth tethering configures the interface elsewhere.
708 return (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) && !SdkLevel.isAtLeastT();
709 }
710
Mark49649c92023-03-15 06:45:04 +0000711 private LinkAddress requestIpv4Address(final int scope, final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800712 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800713
markchien69681d62021-11-15 23:58:05 +0800714 if (shouldNotConfigureBluetoothInterface()) return new LinkAddress(BLUETOOTH_IFACE_ADDR);
markchienc9daba32020-02-12 00:19:21 +0800715
Mark49649c92023-03-15 06:45:04 +0000716 return mPrivateAddressCoordinator.requestDownstreamAddress(this, scope, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900717 }
718
markchien74a4fa92019-09-09 20:50:49 +0800719 private boolean startIPv6() {
720 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
721 if (mInterfaceParams == null) {
722 mLog.e("Failed to find InterfaceParams");
723 stopIPv6();
724 return false;
725 }
726
727 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
728 if (!mRaDaemon.start()) {
729 stopIPv6();
730 return false;
731 }
732
markchien932df542021-08-12 13:56:43 +0800733 if (SdkLevel.isAtLeastS()) {
Tyler Wear90e40632020-03-13 11:38:38 -0700734 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
735 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
736 }
737
markchien74a4fa92019-09-09 20:50:49 +0800738 return true;
739 }
740
741 private void stopIPv6() {
742 mInterfaceParams = null;
743 setRaParams(null);
744
745 if (mRaDaemon != null) {
746 mRaDaemon.stop();
747 mRaDaemon = null;
748 }
Tyler Wear90e40632020-03-13 11:38:38 -0700749
750 if (mDadProxy != null) {
751 mDadProxy.stop();
752 mDadProxy = null;
753 }
markchien74a4fa92019-09-09 20:50:49 +0800754 }
755
756 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
757 // LinkProperties. These have extraneous data filtered out and only the
758 // necessary prefixes included (per its prefix distribution policy).
759 //
760 // TODO: Evaluate using a data structure than is more directly suited to
761 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800762 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800763 if (mRaDaemon == null) return;
764
765 // Avoid unnecessary work on spurious updates.
766 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
767 return;
768 }
769
770 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700771 String upstreamIface = null;
772 InterfaceParams upstreamIfaceParams = null;
KH Shi701c3ca2023-08-16 13:19:33 +0000773 int upstreamIfIndex = NO_UPSTREAM;
markchien74a4fa92019-09-09 20:50:49 +0800774
775 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700776 upstreamIface = v6only.getInterfaceName();
777 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
778 if (upstreamIfaceParams != null) {
779 upstreamIfIndex = upstreamIfaceParams.index;
780 }
markchien74a4fa92019-09-09 20:50:49 +0800781 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700782 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800783 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
784
markchiend63c4f32020-05-21 17:38:28 +0800785 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800786
787 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
788 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
789
790 final IpPrefix prefix = new IpPrefix(
791 linkAddr.getAddress(), linkAddr.getPrefixLength());
792 params.prefixes.add(prefix);
793
794 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
795 if (dnsServer != null) {
796 params.dnses.add(dnsServer);
797 }
798 }
799 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900800
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900801 // Add upstream index to name mapping. See the comment of the interface mapping update in
802 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
803 // timing issue. It prevents that the IPv6 capability is updated later than
804 // CMD_TETHER_CONNECTION_CHANGED.
KH Shi701c3ca2023-08-16 13:19:33 +0000805 mBpfCoordinator.maybeAddUpstreamToLookupTable(upstreamIfIndex, upstreamIface);
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900806
markchien74a4fa92019-09-09 20:50:49 +0800807 // If v6only is null, we pass in null to setRaParams(), which handles
808 // deprecation of any existing RA data.
markchien74a4fa92019-09-09 20:50:49 +0800809 setRaParams(params);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900810
KH Shi68770342023-08-17 14:34:31 +0000811 // Not support BPF on virtual upstream interface
812 final boolean upstreamSupportsBpf = upstreamIface != null && !isVcnInterface(upstreamIface);
KH Shi701c3ca2023-08-16 13:19:33 +0000813 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfIndex, upstreamSupportsBpf);
KH Shi68770342023-08-17 14:34:31 +0000814 mLastIPv6LinkProperties = v6only;
Tyler Wear90e40632020-03-13 11:38:38 -0700815 mLastIPv6UpstreamIfindex = upstreamIfIndex;
KH Shi68770342023-08-17 14:34:31 +0000816 mUpstreamSupportsBpf = upstreamSupportsBpf;
Tyler Wear90e40632020-03-13 11:38:38 -0700817 if (mDadProxy != null) {
818 mDadProxy.setUpstreamIface(upstreamIfaceParams);
819 }
markchien74a4fa92019-09-09 20:50:49 +0800820 }
821
Xiao Ma4455d6b2020-04-09 10:13:44 +0900822 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900823 final int removalFailures = NetdUtils.removeRoutesFromLocalNetwork(
Xiao Ma4455d6b2020-04-09 10:13:44 +0900824 mNetd, toBeRemoved);
825 if (removalFailures > 0) {
826 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
827 removalFailures));
828 }
829
830 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
831 }
832
Chalard Jean2fb66f12023-08-25 12:50:37 +0900833 private void addInterfaceToNetwork(final int netId, @NonNull final String ifaceName) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900834 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +0900835 if (null != mRoutingCoordinator.value) {
836 // TODO : remove this call in favor of using the LocalNetworkConfiguration
837 // correctly, which will let ConnectivityService do it automatically.
838 mRoutingCoordinator.value.addInterfaceToNetwork(netId, ifaceName);
839 } else {
840 mNetd.networkAddInterface(netId, ifaceName);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900841 }
842 } catch (ServiceSpecificException | RemoteException e) {
843 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
844 return;
845 }
Chalard Jean2fb66f12023-08-25 12:50:37 +0900846 }
847
848 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
849 // It's safe to call addInterfaceToNetwork() even if
850 // the interface is already in the local_network.
851 addInterfaceToNetwork(INetd.LOCAL_NET_ID, mIfaceName);
852 try {
853 // Add routes from local network. Note that adding routes that
854 // already exist does not cause an error (EEXIST is silently ignored).
855 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
856 } catch (IllegalStateException e) {
857 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
858 return;
859 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900860
861 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
862 }
863
markchien74a4fa92019-09-09 20:50:49 +0800864 private void configureLocalIPv6Routes(
865 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
866 // [1] Remove the routes that are deprecated.
867 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900868 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800869 }
870
871 // [2] Add only the routes that have not previously been added.
872 if (newPrefixes != null && !newPrefixes.isEmpty()) {
873 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
874 if (mLastRaParams != null) {
875 addedPrefixes.removeAll(mLastRaParams.prefixes);
876 }
877
878 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900879 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800880 }
881 }
882 }
883
884 private void configureLocalIPv6Dns(
885 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
886 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
887 if (mNetd == null) {
888 if (newDnses != null) newDnses.clear();
889 mLog.e("No netd service instance available; not setting local IPv6 addresses");
890 return;
891 }
892
893 // [1] Remove deprecated local DNS IP addresses.
894 if (!deprecatedDnses.isEmpty()) {
895 for (Inet6Address dns : deprecatedDnses) {
896 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
897 mLog.e("Failed to remove local dns IP " + dns);
898 }
899
900 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
901 }
902 }
903
904 // [2] Add only the local DNS IP addresses that have not previously been added.
905 if (newDnses != null && !newDnses.isEmpty()) {
906 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
907 if (mLastRaParams != null) {
908 addedDnses.removeAll(mLastRaParams.dnses);
909 }
910
911 for (Inet6Address dns : addedDnses) {
912 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
913 mLog.e("Failed to add local dns IP " + dns);
914 newDnses.remove(dns);
915 }
916
917 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
918 }
919 }
920
921 try {
922 mNetd.tetherApplyDnsInterfaces();
923 } catch (ServiceSpecificException | RemoteException e) {
924 mLog.e("Failed to update local DNS caching server");
925 if (newDnses != null) newDnses.clear();
926 }
927 }
928
KH Shi701c3ca2023-08-16 13:19:33 +0000929 private int getInterfaceIndexForRule(int ifindex, boolean supportsBpf) {
930 return supportsBpf ? ifindex : NO_UPSTREAM;
931 }
932
933 // Handles updates to IPv6 forwarding rules if the upstream changes.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900934 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
KH Shi701c3ca2023-08-16 13:19:33 +0000935 boolean upstreamSupportsBpf) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900936 // If the upstream interface has changed, remove all rules and re-add them with the new
KH Shi701c3ca2023-08-16 13:19:33 +0000937 // upstream interface. If upstream is a virtual network, treated as no upstream.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900938 if (prevUpstreamIfindex != upstreamIfindex) {
KH Shi701c3ca2023-08-16 13:19:33 +0000939 mBpfCoordinator.updateAllIpv6Rules(this, this.mInterfaceParams,
940 getInterfaceIndexForRule(upstreamIfindex, upstreamSupportsBpf));
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900941 }
KH Shi701c3ca2023-08-16 13:19:33 +0000942 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900943
KH Shi701c3ca2023-08-16 13:19:33 +0000944 // Handles updates to IPv6 downstream rules if a neighbor event is received.
945 private void addOrRemoveIpv6Downstream(NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900946 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900947 if (e == null) return;
948 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
949 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
950 return;
951 }
952
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900953 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
KH Shi59ad35e2023-08-15 07:13:00 +0000954 // Do this here instead of in the Ipv6DownstreamRule constructor to ensure that we
955 // never add rules with a null MAC, only delete them.
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900956 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
KH Shi701c3ca2023-08-16 13:19:33 +0000957 Ipv6DownstreamRule rule = new Ipv6DownstreamRule(
958 getInterfaceIndexForRule(mLastIPv6UpstreamIfindex, mUpstreamSupportsBpf),
959 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900960 if (e.isValid()) {
KH Shie4d549a2023-08-28 09:57:34 +0000961 mBpfCoordinator.addIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900962 } else {
KH Shie4d549a2023-08-28 09:57:34 +0000963 mBpfCoordinator.removeIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900964 }
965 }
966
Hungming Chend71c06e2020-12-21 19:39:49 +0800967 // TODO: consider moving into BpfCoordinator.
968 private void updateClientInfoIpv4(NeighborEvent e) {
Hungming Chend71c06e2020-12-21 19:39:49 +0800969 if (e == null) return;
970 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
971 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
972 return;
973 }
974
975 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
976 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
977 // IpServer never add clients with a null MAC, only delete them.
978 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
979 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
980 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
981 if (e.isValid()) {
982 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
983 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +0800984 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
985 }
986 }
987
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900988 private void handleNeighborEvent(NeighborEvent e) {
989 if (mInterfaceParams != null
990 && mInterfaceParams.index == e.ifindex
991 && mInterfaceParams.hasMacAddress) {
KH Shi701c3ca2023-08-16 13:19:33 +0000992 addOrRemoveIpv6Downstream(e);
Hungming Chend71c06e2020-12-21 19:39:49 +0800993 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900994 }
995 }
996
markchiend63c4f32020-05-21 17:38:28 +0800997 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +0800998 try {
999 int upstreamHopLimit = Integer.parseUnsignedInt(
1000 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001001 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001002 // Cap the hop limit to 255.
1003 return (byte) Integer.min(upstreamHopLimit, 255);
1004 } catch (Exception e) {
1005 mLog.e("Failed to find upstream interface hop limit", e);
1006 }
1007 return RaParams.DEFAULT_HOPLIMIT;
1008 }
1009
1010 private void setRaParams(RaParams newParams) {
1011 if (mRaDaemon != null) {
1012 final RaParams deprecatedParams =
1013 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1014
1015 configureLocalIPv6Routes(deprecatedParams.prefixes,
1016 (newParams != null) ? newParams.prefixes : null);
1017
1018 configureLocalIPv6Dns(deprecatedParams.dnses,
1019 (newParams != null) ? newParams.dnses : null);
1020
1021 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1022 }
1023
1024 mLastRaParams = newParams;
1025 }
1026
markchien21021ef2021-06-01 10:58:04 +08001027 private void maybeLogMessage(State state, int what) {
1028 switch (what) {
1029 // Suppress some CMD_* to avoid log flooding.
1030 case CMD_IPV6_TETHER_UPDATE:
1031 case CMD_NEIGHBOR_EVENT:
1032 break;
1033 default:
1034 mLog.log(state.getName() + " got "
1035 + sMagicDecoderRing.get(what, Integer.toString(what)));
1036 }
markchien74a4fa92019-09-09 20:50:49 +08001037 }
1038
1039 private void sendInterfaceState(int newInterfaceState) {
1040 mServingMode = newInterfaceState;
1041 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1042 sendLinkProperties();
1043 }
1044
1045 private void sendLinkProperties() {
1046 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1047 }
1048
1049 private void resetLinkProperties() {
1050 mLinkProperties.clear();
1051 mLinkProperties.setInterfaceName(mIfaceName);
1052 }
1053
markchienf053e4b2020-03-16 21:49:48 +08001054 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001055 // Ignore static address configuration if they are invalid or null. In theory, static
1056 // addresses should not be invalid here because TetheringManager do not allow caller to
1057 // specify invalid static address configuration.
1058 if (request == null || request.localIPv4Address == null
1059 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1060 request.localIPv4Address, request.staticClientAddress)) {
1061 return;
1062 }
markchienf053e4b2020-03-16 21:49:48 +08001063
1064 mStaticIpv4ServerAddr = request.localIPv4Address;
1065 mStaticIpv4ClientAddr = request.staticClientAddress;
1066 }
1067
markchien74a4fa92019-09-09 20:50:49 +08001068 class InitialState extends State {
1069 @Override
1070 public void enter() {
1071 sendInterfaceState(STATE_AVAILABLE);
1072 }
1073
1074 @Override
1075 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001076 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001077 switch (message.what) {
1078 case CMD_TETHER_REQUESTED:
Mark74461fc2022-12-14 08:49:40 +00001079 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001080 switch (message.arg1) {
1081 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001082 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001083 transitionTo(mLocalHotspotState);
1084 break;
1085 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001086 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001087 transitionTo(mTetheredState);
1088 break;
1089 default:
1090 mLog.e("Invalid tethering interface serving state specified.");
1091 }
1092 break;
1093 case CMD_INTERFACE_DOWN:
1094 transitionTo(mUnavailableState);
1095 break;
markchien74a4fa92019-09-09 20:50:49 +08001096 default:
1097 return NOT_HANDLED;
1098 }
1099 return HANDLED;
1100 }
1101 }
1102
Hungming Chen46c30b12020-10-15 17:25:36 +08001103 private void startConntrackMonitoring() {
1104 mBpfCoordinator.startMonitoring(this);
1105 }
1106
1107 private void stopConntrackMonitoring() {
1108 mBpfCoordinator.stopMonitoring(this);
1109 }
1110
Mark3ec851e2023-05-19 08:50:38 +00001111 abstract class BaseServingState extends State {
1112 private final int mDesiredInterfaceState;
1113
1114 BaseServingState(int interfaceState) {
1115 mDesiredInterfaceState = interfaceState;
1116 }
1117
markchien74a4fa92019-09-09 20:50:49 +08001118 @Override
1119 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001120 startConntrackMonitoring();
1121
Mark3ec851e2023-05-19 08:50:38 +00001122 startServingInterface();
1123
1124 if (mLastError != TETHER_ERROR_NO_ERROR) {
Mark50eef832023-09-19 06:56:14 +00001125 // This will transition to InitialState right away, regardless of whether any
1126 // message is already waiting in the StateMachine queue (including maybe some
1127 // message to go to InitialState). InitialState will then process any pending
1128 // message (and generally ignores them). It is difficult to know for sure whether
1129 // this is correct in all cases, but this is equivalent to what IpServer was doing
1130 // in previous versions of the mainline module.
1131 // TODO : remove this after migrating to the Sync StateMachine.
1132 sendMessageAtFrontOfQueueToAsyncSM(CMD_SERVICE_FAILED_TO_START, mLastError);
Mark3ec851e2023-05-19 08:50:38 +00001133 }
1134
1135 if (DBG) Log.d(TAG, getStateString(mDesiredInterfaceState) + " serve " + mIfaceName);
1136 sendInterfaceState(mDesiredInterfaceState);
1137 }
1138
Mark49649c92023-03-15 06:45:04 +00001139 private int getScope() {
1140 if (mDesiredInterfaceState == STATE_TETHERED) {
1141 return CONNECTIVITY_SCOPE_GLOBAL;
1142 }
1143
1144 return CONNECTIVITY_SCOPE_LOCAL;
1145 }
1146
Mark3ec851e2023-05-19 08:50:38 +00001147 private void startServingInterface() {
Mark49649c92023-03-15 06:45:04 +00001148 if (!startIPv4(getScope())) {
Mark74461fc2022-12-14 08:49:40 +00001149 mLastError = TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001150 return;
1151 }
1152
1153 try {
markchienc9daba32020-02-12 00:19:21 +08001154 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001155 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001156 mLog.e("Error Tethering", e);
Mark74461fc2022-12-14 08:49:40 +00001157 mLastError = TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001158 return;
1159 }
1160
1161 if (!startIPv6()) {
1162 mLog.e("Failed to startIPv6");
1163 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1164 return;
1165 }
1166 }
1167
1168 @Override
1169 public void exit() {
1170 // Note that at this point, we're leaving the tethered state. We can fail any
1171 // of these operations, but it doesn't really change that we have to try them
1172 // all in sequence.
1173 stopIPv6();
1174
1175 try {
markchien12c5bb82020-01-07 14:43:17 +08001176 NetdUtils.untetherInterface(mNetd, mIfaceName);
1177 } catch (RemoteException | ServiceSpecificException e) {
Mark74461fc2022-12-14 08:49:40 +00001178 mLastError = TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001179 mLog.e("Failed to untether interface: " + e);
1180 }
1181
1182 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001183 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001184
1185 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001186
1187 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1188 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001189 }
1190
1191 @Override
1192 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001193 switch (message.what) {
1194 case CMD_TETHER_UNREQUESTED:
1195 transitionTo(mInitialState);
1196 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1197 break;
1198 case CMD_INTERFACE_DOWN:
1199 transitionTo(mUnavailableState);
1200 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1201 break;
1202 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001203 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001204 sendLinkProperties();
1205 break;
1206 case CMD_IP_FORWARDING_ENABLE_ERROR:
1207 case CMD_IP_FORWARDING_DISABLE_ERROR:
1208 case CMD_START_TETHERING_ERROR:
1209 case CMD_STOP_TETHERING_ERROR:
1210 case CMD_SET_DNS_FORWARDERS_ERROR:
Mark74461fc2022-12-14 08:49:40 +00001211 mLastError = TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001212 transitionTo(mInitialState);
1213 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001214 case CMD_NEW_PREFIX_REQUEST:
1215 handleNewPrefixRequest((IpPrefix) message.obj);
1216 break;
markchienc9daba32020-02-12 00:19:21 +08001217 case CMD_NOTIFY_PREFIX_CONFLICT:
1218 mLog.i("restart tethering: " + mInterfaceType);
1219 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1220 transitionTo(mWaitingForRestartState);
1221 break;
Mark50eef832023-09-19 06:56:14 +00001222 case CMD_SERVICE_FAILED_TO_START:
1223 mLog.e("start serving fail, error: " + message.arg1);
1224 transitionTo(mInitialState);
markchien74a4fa92019-09-09 20:50:49 +08001225 default:
1226 return false;
1227 }
1228 return true;
1229 }
Mark3ec851e2023-05-19 08:50:38 +00001230
1231 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
1232 if (!currentPrefix.contains(mIpv4Address.getAddress())
1233 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
1234 Log.e(TAG, "Invalid prefix: " + currentPrefix);
1235 return;
1236 }
1237
1238 final LinkAddress deprecatedLinkAddress = mIpv4Address;
Mark49649c92023-03-15 06:45:04 +00001239 mIpv4Address = requestIpv4Address(getScope(), false);
Mark3ec851e2023-05-19 08:50:38 +00001240 if (mIpv4Address == null) {
1241 mLog.e("Fail to request a new downstream prefix");
1242 return;
1243 }
1244 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
1245
1246 // Add new IPv4 address on the interface.
1247 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1248 mLog.e("Failed to add new IP " + srvAddr);
1249 return;
1250 }
1251
1252 // Remove deprecated routes from local network.
1253 removeRoutesFromLocalNetwork(
1254 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1255 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1256
1257 // Add new routes to local network.
1258 addRoutesToLocalNetwork(
1259 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1260 mLinkProperties.addLinkAddress(mIpv4Address);
1261
1262 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1263 // listen on the interface configured with new IPv4 address, that results DNS validation
1264 // failure of downstream client even if appropriate routes have been configured.
1265 try {
1266 mNetd.tetherApplyDnsInterfaces();
1267 } catch (ServiceSpecificException | RemoteException e) {
1268 mLog.e("Failed to update local DNS caching server");
1269 return;
1270 }
1271 sendLinkProperties();
1272
1273 // Notify DHCP server that new prefix/route has been applied on IpServer.
1274 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1275 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1276 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1277 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1278 try {
1279 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1280 @Override
1281 public void callback(int statusCode) {
1282 if (statusCode != STATUS_SUCCESS) {
1283 mLog.e("Error updating DHCP serving params: " + statusCode);
1284 }
1285 }
1286 });
1287 } catch (RemoteException e) {
1288 mLog.e("Error updating DHCP serving params", e);
1289 }
1290 }
markchien74a4fa92019-09-09 20:50:49 +08001291 }
1292
1293 // Handling errors in BaseServingState.enter() by transitioning is
1294 // problematic because transitioning during a multi-state jump yields
1295 // a Log.wtf(). Ultimately, there should be only one ServingState,
1296 // and forwarding and NAT rules should be handled by a coordinating
1297 // functional element outside of IpServer.
1298 class LocalHotspotState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001299 LocalHotspotState() {
1300 super(STATE_LOCAL_ONLY);
markchien74a4fa92019-09-09 20:50:49 +08001301 }
1302
1303 @Override
1304 public boolean processMessage(Message message) {
1305 if (super.processMessage(message)) return true;
1306
markchien21021ef2021-06-01 10:58:04 +08001307 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001308 switch (message.what) {
1309 case CMD_TETHER_REQUESTED:
1310 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1311 break;
1312 case CMD_TETHER_CONNECTION_CHANGED:
1313 // Ignored in local hotspot state.
1314 break;
1315 default:
1316 return false;
1317 }
1318 return true;
1319 }
1320 }
1321
1322 // Handling errors in BaseServingState.enter() by transitioning is
1323 // problematic because transitioning during a multi-state jump yields
1324 // a Log.wtf(). Ultimately, there should be only one ServingState,
1325 // and forwarding and NAT rules should be handled by a coordinating
1326 // functional element outside of IpServer.
1327 class TetheredState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001328 TetheredState() {
1329 super(STATE_TETHERED);
markchien74a4fa92019-09-09 20:50:49 +08001330 }
1331
1332 @Override
1333 public void exit() {
1334 cleanupUpstream();
KH Shi701c3ca2023-08-16 13:19:33 +00001335 mBpfCoordinator.clearAllIpv6Rules(IpServer.this);
markchien74a4fa92019-09-09 20:50:49 +08001336 super.exit();
1337 }
1338
Hungming Chena6e78692021-02-08 17:15:35 +08001339 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1340 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1341 // and behaviour. While upstream is switching from offload supported interface to
1342 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1343 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1344 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1345 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1346 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1347 // in the state machine. Once there is any case out whish is not covered by previous cases,
1348 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001349 private void cleanupUpstream() {
1350 if (mUpstreamIfaceSet == null) return;
1351
1352 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1353 mUpstreamIfaceSet = null;
KH Shi701c3ca2023-08-16 13:19:33 +00001354 mBpfCoordinator.updateAllIpv6Rules(
1355 IpServer.this, IpServer.this.mInterfaceParams, NO_UPSTREAM);
markchien74a4fa92019-09-09 20:50:49 +08001356 }
1357
1358 private void cleanupUpstreamInterface(String upstreamIface) {
1359 // Note that we don't care about errors here.
1360 // Sometimes interfaces are gone before we get
1361 // to remove their rules, which generates errors.
1362 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001363 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001364 try {
markchien12c5bb82020-01-07 14:43:17 +08001365 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1366 } catch (RemoteException | ServiceSpecificException e) {
1367 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001368 }
1369 try {
markchien12c5bb82020-01-07 14:43:17 +08001370 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1371 } catch (RemoteException | ServiceSpecificException e) {
1372 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001373 }
1374 }
1375
1376 @Override
1377 public boolean processMessage(Message message) {
1378 if (super.processMessage(message)) return true;
1379
markchien21021ef2021-06-01 10:58:04 +08001380 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001381 switch (message.what) {
1382 case CMD_TETHER_REQUESTED:
1383 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1384 break;
1385 case CMD_TETHER_CONNECTION_CHANGED:
1386 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1387 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1388 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1389 break;
1390 }
1391
1392 if (newUpstreamIfaceSet == null) {
1393 cleanupUpstream();
1394 break;
1395 }
1396
1397 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1398 cleanupUpstreamInterface(removed);
1399 }
1400
1401 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1402 // This makes the call to cleanupUpstream() in the error
1403 // path for any interface neatly cleanup all the interfaces.
1404 mUpstreamIfaceSet = newUpstreamIfaceSet;
1405
1406 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001407 // Add upstream index to name mapping for the tether stats usage in the
1408 // coordinator. Although this mapping could be added by both class
1409 // Tethering and IpServer, adding mapping from IpServer guarantees that
1410 // the mapping is added before adding forwarding rules. That is because
1411 // there are different state machines in both classes. It is hard to
1412 // guarantee the link property update order between multiple state machines.
1413 // Note that both IPv4 and IPv6 interface may be added because
1414 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1415 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1416 // capability may be updated later. In that case, IPv6 interface mapping is
1417 // updated in updateUpstreamIPv6LinkProperties.
1418 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1419 final InterfaceParams upstreamIfaceParams =
1420 mDeps.getInterfaceParams(ifname);
1421 if (upstreamIfaceParams != null) {
KH Shi701c3ca2023-08-16 13:19:33 +00001422 mBpfCoordinator.maybeAddUpstreamToLookupTable(
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001423 upstreamIfaceParams.index, ifname);
1424 }
1425 }
1426
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001427 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001428 try {
markchien12c5bb82020-01-07 14:43:17 +08001429 mNetd.tetherAddForward(mIfaceName, ifname);
1430 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1431 } catch (RemoteException | ServiceSpecificException e) {
1432 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001433 cleanupUpstream();
Mark74461fc2022-12-14 08:49:40 +00001434 mLastError = TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001435 transitionTo(mInitialState);
1436 return true;
1437 }
1438 }
1439 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001440 case CMD_NEIGHBOR_EVENT:
1441 handleNeighborEvent((NeighborEvent) message.obj);
1442 break;
markchien74a4fa92019-09-09 20:50:49 +08001443 default:
1444 return false;
1445 }
1446 return true;
1447 }
1448
1449 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1450 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1451 if (mUpstreamIfaceSet != null && newIfaces != null) {
1452 return mUpstreamIfaceSet.equals(newIfaces);
1453 }
1454 return false;
1455 }
1456
1457 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1458 if (mUpstreamIfaceSet == null) return new HashSet<>();
1459
1460 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1461 removed.removeAll(newIfaces.ifnames);
1462 return removed;
1463 }
1464
1465 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1466 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1467 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1468 return added;
1469 }
1470 }
1471
1472 /**
1473 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001474 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001475 * specific state machine from its list of possible recipients of
1476 * tethering requests. The state machine itself will hang around until
1477 * the garbage collector finds it.
1478 */
1479 class UnavailableState extends State {
1480 @Override
1481 public void enter() {
KH Shi701c3ca2023-08-16 13:19:33 +00001482 // TODO: move mIpNeighborMonitor.stop() to TetheredState#exit, and trigger a neighbours
1483 // dump after starting mIpNeighborMonitor.
h.zhangd244bd02020-06-14 14:46:54 +08001484 mIpNeighborMonitor.stop();
Mark74461fc2022-12-14 08:49:40 +00001485 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001486 sendInterfaceState(STATE_UNAVAILABLE);
1487 }
1488 }
1489
markchienc9daba32020-02-12 00:19:21 +08001490 class WaitingForRestartState extends State {
1491 @Override
1492 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001493 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001494 switch (message.what) {
1495 case CMD_TETHER_UNREQUESTED:
1496 transitionTo(mInitialState);
1497 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1498 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1499 break;
1500 case CMD_INTERFACE_DOWN:
1501 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001502 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001503 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1504 break;
1505 default:
1506 return false;
1507 }
1508 return true;
1509 }
1510 }
1511
markchien74a4fa92019-09-09 20:50:49 +08001512 // Accumulate routes representing "prefixes to be assigned to the local
1513 // interface", for subsequent modification of local_network routing.
1514 private static ArrayList<RouteInfo> getLocalRoutesFor(
1515 String ifname, HashSet<IpPrefix> prefixes) {
1516 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1517 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001518 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001519 }
1520 return localRoutes;
1521 }
1522
1523 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1524 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1525 final byte[] dnsBytes = localPrefix.getRawAddress();
1526 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1527 try {
1528 return Inet6Address.getByAddress(null, dnsBytes, 0);
1529 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001530 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001531 return null;
1532 }
1533 }
1534
1535 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1536 final byte random = (byte) (new Random()).nextInt();
1537 for (int value : excluded) {
1538 if (random == value) return dflt;
1539 }
1540 return random;
1541 }
1542}