blob: 8d672214f70e5666d5c29a6f9bdc046102a68ed4 [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;
markchien74a4fa92019-09-09 20:50:49 +0800240
241 private final State mInitialState;
242 private final State mLocalHotspotState;
243 private final State mTetheredState;
244 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800245 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800246
247 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800248 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800249 @NonNull
250 private final BpfCoordinator mBpfCoordinator;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900251 // Contains null if the connectivity module is unsupported, as the routing coordinator is not
252 // available. Must use LateSdk because MessageUtils enumerates fields in this class, so it
253 // must be able to find all classes at runtime.
254 @NonNull
255 private final LateSdk<RoutingCoordinatorManager> mRoutingCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800256 private final Callback mCallback;
257 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800258 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800259
260 private final String mIfaceName;
261 private final int mInterfaceType;
262 private final LinkProperties mLinkProperties;
263 private final boolean mUsingLegacyDhcp;
markchienfb65dfe2022-02-25 23:14:58 +0800264 private final int mP2pLeasesSubnetPrefixLength;
markchien74a4fa92019-09-09 20:50:49 +0800265
266 private final Dependencies mDeps;
267
268 private int mLastError;
269 private int mServingMode;
270 private InterfaceSet mUpstreamIfaceSet; // may change over time
KH Shi701c3ca2023-08-16 13:19:33 +0000271 // mInterfaceParams can't be final now because IpServer will be created when receives
272 // WIFI_AP_STATE_CHANGED broadcasts or when it detects that the wifi interface has come up.
273 // In the latter case, the interface is not fully initialized and the MAC address might not
274 // be correct (it will be set with a randomized MAC address later).
275 // TODO: Consider create the IpServer only when tethering want to enable it, then we can
276 // make mInterfaceParams final.
markchien74a4fa92019-09-09 20:50:49 +0800277 private InterfaceParams mInterfaceParams;
278 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
279 // properties are those selected by the IPv6TetheringCoordinator and relayed
280 // to us. By comparison, mLinkProperties contains the addresses and directly
281 // connected routes that have been formed from these properties iff. we have
282 // succeeded in configuring them and are able to announce them within Router
283 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
284 private LinkProperties mLastIPv6LinkProperties;
285 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700286 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800287
288 // To be accessed only on the handler thread
289 private int mDhcpServerStartIndex = 0;
290 private IDhcpServer mDhcpServer;
291 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800292
293 private LinkAddress mStaticIpv4ServerAddr;
294 private LinkAddress mStaticIpv4ClientAddr;
295
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900296 @NonNull
297 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800298
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900299 private int mLastIPv6UpstreamIfindex = 0;
KH Shi68770342023-08-17 14:34:31 +0000300 private boolean mUpstreamSupportsBpf = false;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900301
302 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
303 public void accept(NeighborEvent e) {
304 sendMessage(CMD_NEIGHBOR_EVENT, e);
305 }
306 }
307
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900308 private final IpNeighborMonitor mIpNeighborMonitor;
309
markchienc9daba32020-02-12 00:19:21 +0800310 private LinkAddress mIpv4Address;
311
Wayne Ma6cd440f2022-03-14 18:04:33 +0800312 private final TetheringMetrics mTetheringMetrics;
Mark21502962022-12-21 06:58:23 +0000313 private final Handler mHandler;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800314
Hungming Chen5bc3af92020-05-12 19:15:24 +0800315 // TODO: Add a dependency object to pass the data members or variables from the tethering
316 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800317 public IpServer(
Mark21502962022-12-21 06:58:23 +0000318 String ifaceName, Handler handler, int interfaceType, SharedLog log,
Chalard Jean2fb66f12023-08-25 12:50:37 +0900319 INetd netd, @NonNull BpfCoordinator bpfCoordinator,
320 @Nullable LateSdk<RoutingCoordinatorManager> routingCoordinator, Callback callback,
markchienb961d3d2022-02-26 00:39:06 +0800321 TetheringConfiguration config, PrivateAddressCoordinator addressCoordinator,
Wayne Ma6cd440f2022-03-14 18:04:33 +0800322 TetheringMetrics tetheringMetrics, Dependencies deps) {
Mark21502962022-12-21 06:58:23 +0000323 super(ifaceName, USE_SYNC_SM ? null : handler.getLooper());
324 mHandler = handler;
markchien74a4fa92019-09-09 20:50:49 +0800325 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800326 mNetd = netd;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900327 mBpfCoordinator = bpfCoordinator;
328 mRoutingCoordinator = routingCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800329 mCallback = callback;
330 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
331 mIfaceName = ifaceName;
332 mInterfaceType = interfaceType;
333 mLinkProperties = new LinkProperties();
markchienb961d3d2022-02-26 00:39:06 +0800334 mUsingLegacyDhcp = config.useLegacyDhcpServer();
markchienfb65dfe2022-02-25 23:14:58 +0800335 mP2pLeasesSubnetPrefixLength = config.getP2pLeasesSubnetPrefixLength();
markchienc9daba32020-02-12 00:19:21 +0800336 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800337 mDeps = deps;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800338 mTetheringMetrics = tetheringMetrics;
markchien74a4fa92019-09-09 20:50:49 +0800339 resetLinkProperties();
Mark74461fc2022-12-14 08:49:40 +0000340 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800341 mServingMode = STATE_AVAILABLE;
342
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900343 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
344 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800345
KH Shie4d549a2023-08-28 09:57:34 +0000346 // IP neighbor monitor monitors the neighbor events for adding/removing IPv6 downstream rule
347 // per client. If BPF offload is not supported, don't start listening for neighbor events.
348 if (mBpfCoordinator.isUsingBpfOffload() && !mIpNeighborMonitor.start()) {
Hungming Chen5bc3af92020-05-12 19:15:24 +0800349 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900350 }
351
markchien74a4fa92019-09-09 20:50:49 +0800352 mInitialState = new InitialState();
353 mLocalHotspotState = new LocalHotspotState();
354 mTetheredState = new TetheredState();
355 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800356 mWaitingForRestartState = new WaitingForRestartState();
Mark21502962022-12-21 06:58:23 +0000357 final ArrayList allStates = new ArrayList<StateInfo>();
358 allStates.add(new StateInfo(mInitialState, null));
359 allStates.add(new StateInfo(mLocalHotspotState, null));
360 allStates.add(new StateInfo(mTetheredState, null));
361 allStates.add(new StateInfo(mWaitingForRestartState, mTetheredState));
362 allStates.add(new StateInfo(mUnavailableState, null));
363 addAllStates(allStates);
364 }
markchien74a4fa92019-09-09 20:50:49 +0800365
Mark21502962022-12-21 06:58:23 +0000366 private Handler getHandler() {
367 return mHandler;
368 }
369
370 /** Start IpServer state machine. */
371 public void start() {
372 start(mInitialState);
markchien74a4fa92019-09-09 20:50:49 +0800373 }
374
375 /** Interface name which IpServer served.*/
376 public String interfaceName() {
377 return mIfaceName;
378 }
379
380 /**
markchien9b4d7572019-12-25 19:40:32 +0800381 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800382 */
383 public int interfaceType() {
384 return mInterfaceType;
385 }
386
387 /** Last error from this IpServer. */
388 public int lastError() {
389 return mLastError;
390 }
391
392 /** Serving mode is the current state of IpServer state machine. */
393 public int servingMode() {
394 return mServingMode;
395 }
396
397 /** The properties of the network link which IpServer is serving. */
398 public LinkProperties linkProperties() {
399 return new LinkProperties(mLinkProperties);
400 }
401
markchienc9daba32020-02-12 00:19:21 +0800402 /** The address which IpServer is using. */
403 public LinkAddress getAddress() {
404 return mIpv4Address;
405 }
406
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900407 /**
408 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
409 * thread.
410 */
411 public List<TetheredClient> getAllLeases() {
412 return Collections.unmodifiableList(mDhcpLeases);
413 }
414
Marka5424582022-12-01 13:46:32 +0000415 /** Enable this IpServer. IpServer state machine will be tethered or localHotspot state. */
416 public void enable(final int requestedState, final TetheringRequestParcel request) {
417 sendMessage(CMD_TETHER_REQUESTED, requestedState, 0, request);
418 }
419
markchien74a4fa92019-09-09 20:50:49 +0800420 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
421 public void stop() {
422 sendMessage(CMD_INTERFACE_DOWN);
423 }
424
425 /**
426 * Tethering is canceled. IpServer state machine will be available and wait for
427 * next tethering request.
428 */
429 public void unwanted() {
430 sendMessage(CMD_TETHER_UNREQUESTED);
431 }
432
433 /** Internals. */
434
Mark49649c92023-03-15 06:45:04 +0000435 private boolean startIPv4(int scope) {
436 return configureIPv4(true, scope);
markchien74a4fa92019-09-09 20:50:49 +0800437 }
438
439 /**
440 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
441 * handler.
442 *
443 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
444 * with different implementations of the callback, to differentiate handling of success/error in
445 * each call.
446 */
447 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
448 @Override
449 public void onStatusAvailable(int statusCode) {
450 getHandler().post(() -> callback(statusCode));
451 }
452
453 public abstract void callback(int statusCode);
454
455 @Override
456 public int getInterfaceVersion() {
457 return this.VERSION;
458 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900459
460 @Override
461 public String getInterfaceHash() {
462 return this.HASH;
463 }
markchien74a4fa92019-09-09 20:50:49 +0800464 }
465
466 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
467 private final int mStartIndex;
468
469 private DhcpServerCallbacksImpl(int startIndex) {
470 mStartIndex = startIndex;
471 }
472
473 @Override
474 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
475 getHandler().post(() -> {
476 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
477 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800478 // This start request is obsolete. Explicitly stop the DHCP server to shut
479 // down its thread. When the |server| binder token goes out of scope, the
480 // garbage collector will finalize it, which causes the network stack process
481 // garbage collector to collect the server itself.
482 try {
483 server.stop(null);
484 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800485 return;
486 }
487
488 if (statusCode != STATUS_SUCCESS) {
489 mLog.e("Error obtaining DHCP server: " + statusCode);
490 handleError();
491 return;
492 }
493
494 mDhcpServer = server;
495 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900496 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800497 @Override
498 public void callback(int startStatusCode) {
499 if (startStatusCode != STATUS_SUCCESS) {
500 mLog.e("Error starting DHCP server: " + startStatusCode);
501 handleError();
502 }
503 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900504 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800505 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800506 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800507 }
508 });
509 }
510
511 private void handleError() {
Mark74461fc2022-12-14 08:49:40 +0000512 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800513 transitionTo(mInitialState);
514 }
515 }
516
Xiao Ma4455d6b2020-04-09 10:13:44 +0900517 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900518 @Override
519 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
520 final ArrayList<TetheredClient> leases = new ArrayList<>();
521 for (DhcpLeaseParcelable lease : leaseParcelables) {
522 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900523 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
524 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
525 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900526
527 final MacAddress macAddress;
528 try {
529 macAddress = MacAddress.fromBytes(lease.hwAddr);
530 } catch (IllegalArgumentException e) {
531 Log.wtf(TAG, "Invalid address received from DhcpServer: "
532 + Arrays.toString(lease.hwAddr));
533 return;
534 }
535
536 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900537 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900538 leases.add(new TetheredClient(
539 macAddress,
540 Collections.singletonList(addressInfo),
541 mInterfaceType));
542 }
543
544 getHandler().post(() -> {
545 mDhcpLeases = leases;
546 mCallback.dhcpLeasesChanged();
547 });
548 }
549
550 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900551 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
552 Objects.requireNonNull(currentPrefix);
553 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900554 }
555
556 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900557 public int getInterfaceVersion() {
558 return this.VERSION;
559 }
560
561 @Override
562 public String getInterfaceHash() throws RemoteException {
563 return this.HASH;
564 }
565 }
566
Xiao Ma4455d6b2020-04-09 10:13:44 +0900567 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
568 Objects.requireNonNull(ipv4Address);
569 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
570 }
571
572 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
573 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
574 @Nullable Inet4Address clientAddr) {
575 final boolean changePrefixOnDecline =
576 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
markchienfb65dfe2022-02-25 23:14:58 +0800577 final int subnetPrefixLength = mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
578 ? mP2pLeasesSubnetPrefixLength : 0 /* default value */;
579
Xiao Ma4455d6b2020-04-09 10:13:44 +0900580 return new DhcpServingParamsParcelExt()
581 .setDefaultRouters(defaultRouter)
582 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
583 .setDnsServers(dnsServer)
584 .setServerAddr(serverAddr)
585 .setMetered(true)
586 .setSingleClientAddr(clientAddr)
markchienfb65dfe2022-02-25 23:14:58 +0800587 .setChangePrefixOnDecline(changePrefixOnDecline)
588 .setLeasesSubnetPrefixLength(subnetPrefixLength);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900589 // TODO: also advertise link MTU
590 }
591
markchien245352e2020-02-27 20:27:18 +0800592 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800593 if (mUsingLegacyDhcp) {
594 return true;
595 }
markchien245352e2020-02-27 20:27:18 +0800596
597 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800598 final Inet4Address clientAddr = clientLinkAddr == null ? null :
599 (Inet4Address) clientLinkAddr.getAddress();
600
Xiao Ma4455d6b2020-04-09 10:13:44 +0900601 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
602 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800603 mDhcpServerStartIndex++;
604 mDeps.makeDhcpServer(
605 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
606 return true;
607 }
608
609 private void stopDhcp() {
610 // Make all previous start requests obsolete so servers are not started later
611 mDhcpServerStartIndex++;
612
613 if (mDhcpServer != null) {
614 try {
615 mDhcpServer.stop(new OnHandlerStatusCallback() {
616 @Override
617 public void callback(int statusCode) {
618 if (statusCode != STATUS_SUCCESS) {
619 mLog.e("Error stopping DHCP server: " + statusCode);
Mark74461fc2022-12-14 08:49:40 +0000620 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800621 // Not much more we can do here
622 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900623 mDhcpLeases.clear();
624 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800625 }
626 });
627 mDhcpServer = null;
628 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900629 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800630 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800631 }
632 }
633 }
634
markchien245352e2020-02-27 20:27:18 +0800635 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
636 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800637 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800638 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800639 } else {
640 stopDhcp();
641 return true;
642 }
643 }
644
645 private void stopIPv4() {
Mark49649c92023-03-15 06:45:04 +0000646 configureIPv4(false /* enabled */, CONNECTIVITY_SCOPE_GLOBAL /* not used */);
markchien74a4fa92019-09-09 20:50:49 +0800647 // NOTE: All of configureIPv4() will be refactored out of existence
648 // into calls to InterfaceController, shared with startIPv4().
649 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800650 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800651 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800652 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800653 mStaticIpv4ServerAddr = null;
654 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800655 }
656
Mark49649c92023-03-15 06:45:04 +0000657 private boolean configureIPv4(boolean enabled, int scope) {
markchien74a4fa92019-09-09 20:50:49 +0800658 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
659
markchienc9daba32020-02-12 00:19:21 +0800660 if (enabled) {
Mark49649c92023-03-15 06:45:04 +0000661 mIpv4Address = requestIpv4Address(scope, true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800662 }
663
664 if (mIpv4Address == null) {
665 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800666 return false;
markchien74a4fa92019-09-09 20:50:49 +0800667 }
668
markchien69681d62021-11-15 23:58:05 +0800669 if (shouldNotConfigureBluetoothInterface()) {
670 // Interface was already configured elsewhere, only start DHCP.
markchienc9daba32020-02-12 00:19:21 +0800671 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
672 }
673
674 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
675
markchien12c5bb82020-01-07 14:43:17 +0800676 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800677 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900678 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200679 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
680 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900681 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800682 // It is unclear whether the Bluetooth or USB stacks will manage their own
683 // state.
684 setIfaceUp = null;
685 } else {
686 setIfaceUp = enabled;
687 }
688 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
689 mLog.e("Error configuring interface");
690 if (!enabled) stopDhcp();
691 return false;
692 }
markchien74a4fa92019-09-09 20:50:49 +0800693
markchien74a4fa92019-09-09 20:50:49 +0800694 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800695 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900696 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800697 } else {
markchien12c5bb82020-01-07 14:43:17 +0800698 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900699 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800700 }
markchien245352e2020-02-27 20:27:18 +0800701 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800702 }
703
markchien69681d62021-11-15 23:58:05 +0800704 private boolean shouldNotConfigureBluetoothInterface() {
705 // Before T, bluetooth tethering configures the interface elsewhere.
706 return (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) && !SdkLevel.isAtLeastT();
707 }
708
Mark49649c92023-03-15 06:45:04 +0000709 private LinkAddress requestIpv4Address(final int scope, final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800710 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800711
markchien69681d62021-11-15 23:58:05 +0800712 if (shouldNotConfigureBluetoothInterface()) return new LinkAddress(BLUETOOTH_IFACE_ADDR);
markchienc9daba32020-02-12 00:19:21 +0800713
Mark49649c92023-03-15 06:45:04 +0000714 return mPrivateAddressCoordinator.requestDownstreamAddress(this, scope, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900715 }
716
markchien74a4fa92019-09-09 20:50:49 +0800717 private boolean startIPv6() {
718 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
719 if (mInterfaceParams == null) {
720 mLog.e("Failed to find InterfaceParams");
721 stopIPv6();
722 return false;
723 }
724
725 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
726 if (!mRaDaemon.start()) {
727 stopIPv6();
728 return false;
729 }
730
markchien932df542021-08-12 13:56:43 +0800731 if (SdkLevel.isAtLeastS()) {
Tyler Wear90e40632020-03-13 11:38:38 -0700732 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
733 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
734 }
735
markchien74a4fa92019-09-09 20:50:49 +0800736 return true;
737 }
738
739 private void stopIPv6() {
740 mInterfaceParams = null;
741 setRaParams(null);
742
743 if (mRaDaemon != null) {
744 mRaDaemon.stop();
745 mRaDaemon = null;
746 }
Tyler Wear90e40632020-03-13 11:38:38 -0700747
748 if (mDadProxy != null) {
749 mDadProxy.stop();
750 mDadProxy = null;
751 }
markchien74a4fa92019-09-09 20:50:49 +0800752 }
753
754 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
755 // LinkProperties. These have extraneous data filtered out and only the
756 // necessary prefixes included (per its prefix distribution policy).
757 //
758 // TODO: Evaluate using a data structure than is more directly suited to
759 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800760 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800761 if (mRaDaemon == null) return;
762
763 // Avoid unnecessary work on spurious updates.
764 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
765 return;
766 }
767
768 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700769 String upstreamIface = null;
770 InterfaceParams upstreamIfaceParams = null;
KH Shi701c3ca2023-08-16 13:19:33 +0000771 int upstreamIfIndex = NO_UPSTREAM;
markchien74a4fa92019-09-09 20:50:49 +0800772
773 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700774 upstreamIface = v6only.getInterfaceName();
775 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
776 if (upstreamIfaceParams != null) {
777 upstreamIfIndex = upstreamIfaceParams.index;
778 }
markchien74a4fa92019-09-09 20:50:49 +0800779 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700780 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800781 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
782
markchiend63c4f32020-05-21 17:38:28 +0800783 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800784
785 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
786 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
787
788 final IpPrefix prefix = new IpPrefix(
789 linkAddr.getAddress(), linkAddr.getPrefixLength());
790 params.prefixes.add(prefix);
791
792 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
793 if (dnsServer != null) {
794 params.dnses.add(dnsServer);
795 }
796 }
797 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900798
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900799 // Add upstream index to name mapping. See the comment of the interface mapping update in
800 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
801 // timing issue. It prevents that the IPv6 capability is updated later than
802 // CMD_TETHER_CONNECTION_CHANGED.
KH Shi701c3ca2023-08-16 13:19:33 +0000803 mBpfCoordinator.maybeAddUpstreamToLookupTable(upstreamIfIndex, upstreamIface);
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900804
markchien74a4fa92019-09-09 20:50:49 +0800805 // If v6only is null, we pass in null to setRaParams(), which handles
806 // deprecation of any existing RA data.
markchien74a4fa92019-09-09 20:50:49 +0800807 setRaParams(params);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900808
KH Shi68770342023-08-17 14:34:31 +0000809 // Not support BPF on virtual upstream interface
810 final boolean upstreamSupportsBpf = upstreamIface != null && !isVcnInterface(upstreamIface);
KH Shi701c3ca2023-08-16 13:19:33 +0000811 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfIndex, upstreamSupportsBpf);
KH Shi68770342023-08-17 14:34:31 +0000812 mLastIPv6LinkProperties = v6only;
Tyler Wear90e40632020-03-13 11:38:38 -0700813 mLastIPv6UpstreamIfindex = upstreamIfIndex;
KH Shi68770342023-08-17 14:34:31 +0000814 mUpstreamSupportsBpf = upstreamSupportsBpf;
Tyler Wear90e40632020-03-13 11:38:38 -0700815 if (mDadProxy != null) {
816 mDadProxy.setUpstreamIface(upstreamIfaceParams);
817 }
markchien74a4fa92019-09-09 20:50:49 +0800818 }
819
Xiao Ma4455d6b2020-04-09 10:13:44 +0900820 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900821 final int removalFailures = NetdUtils.removeRoutesFromLocalNetwork(
Xiao Ma4455d6b2020-04-09 10:13:44 +0900822 mNetd, toBeRemoved);
823 if (removalFailures > 0) {
824 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
825 removalFailures));
826 }
827
828 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
829 }
830
Chalard Jean2fb66f12023-08-25 12:50:37 +0900831 private void addInterfaceToNetwork(final int netId, @NonNull final String ifaceName) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900832 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +0900833 if (null != mRoutingCoordinator.value) {
834 // TODO : remove this call in favor of using the LocalNetworkConfiguration
835 // correctly, which will let ConnectivityService do it automatically.
836 mRoutingCoordinator.value.addInterfaceToNetwork(netId, ifaceName);
837 } else {
838 mNetd.networkAddInterface(netId, ifaceName);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900839 }
840 } catch (ServiceSpecificException | RemoteException e) {
841 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
Chalard Jean55ccfe12023-10-06 18:31:08 +0900842 }
843 }
844
845 private void addInterfaceForward(@NonNull final String fromIface,
846 @NonNull final String toIface) throws ServiceSpecificException, RemoteException {
847 if (null != mRoutingCoordinator.value) {
848 mRoutingCoordinator.value.addInterfaceForward(fromIface, toIface);
849 } else {
850 mNetd.tetherAddForward(fromIface, toIface);
851 mNetd.ipfwdAddInterfaceForward(fromIface, toIface);
852 }
853 }
854
855 private void removeInterfaceForward(@NonNull final String fromIface,
856 @NonNull final String toIface) {
857 if (null != mRoutingCoordinator.value) {
858 try {
859 mRoutingCoordinator.value.removeInterfaceForward(fromIface, toIface);
860 } catch (ServiceSpecificException e) {
861 mLog.e("Exception in removeInterfaceForward", e);
862 }
863 } else {
864 try {
865 mNetd.ipfwdRemoveInterfaceForward(fromIface, toIface);
866 } catch (RemoteException | ServiceSpecificException e) {
867 mLog.e("Exception in ipfwdRemoveInterfaceForward", e);
868 }
869 try {
870 mNetd.tetherRemoveForward(fromIface, toIface);
871 } catch (RemoteException | ServiceSpecificException e) {
872 mLog.e("Exception in disableNat", e);
873 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900874 }
Chalard Jean2fb66f12023-08-25 12:50:37 +0900875 }
876
877 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
878 // It's safe to call addInterfaceToNetwork() even if
879 // the interface is already in the local_network.
880 addInterfaceToNetwork(INetd.LOCAL_NET_ID, mIfaceName);
881 try {
882 // Add routes from local network. Note that adding routes that
883 // already exist does not cause an error (EEXIST is silently ignored).
884 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
885 } catch (IllegalStateException e) {
886 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
887 return;
888 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900889
890 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
891 }
892
markchien74a4fa92019-09-09 20:50:49 +0800893 private void configureLocalIPv6Routes(
894 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
895 // [1] Remove the routes that are deprecated.
896 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900897 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800898 }
899
900 // [2] Add only the routes that have not previously been added.
901 if (newPrefixes != null && !newPrefixes.isEmpty()) {
902 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
903 if (mLastRaParams != null) {
904 addedPrefixes.removeAll(mLastRaParams.prefixes);
905 }
906
907 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900908 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800909 }
910 }
911 }
912
913 private void configureLocalIPv6Dns(
914 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
915 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
916 if (mNetd == null) {
917 if (newDnses != null) newDnses.clear();
918 mLog.e("No netd service instance available; not setting local IPv6 addresses");
919 return;
920 }
921
922 // [1] Remove deprecated local DNS IP addresses.
923 if (!deprecatedDnses.isEmpty()) {
924 for (Inet6Address dns : deprecatedDnses) {
925 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
926 mLog.e("Failed to remove local dns IP " + dns);
927 }
928
929 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
930 }
931 }
932
933 // [2] Add only the local DNS IP addresses that have not previously been added.
934 if (newDnses != null && !newDnses.isEmpty()) {
935 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
936 if (mLastRaParams != null) {
937 addedDnses.removeAll(mLastRaParams.dnses);
938 }
939
940 for (Inet6Address dns : addedDnses) {
941 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
942 mLog.e("Failed to add local dns IP " + dns);
943 newDnses.remove(dns);
944 }
945
946 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
947 }
948 }
949
950 try {
951 mNetd.tetherApplyDnsInterfaces();
952 } catch (ServiceSpecificException | RemoteException e) {
953 mLog.e("Failed to update local DNS caching server");
954 if (newDnses != null) newDnses.clear();
955 }
956 }
957
KH Shi701c3ca2023-08-16 13:19:33 +0000958 private int getInterfaceIndexForRule(int ifindex, boolean supportsBpf) {
959 return supportsBpf ? ifindex : NO_UPSTREAM;
960 }
961
962 // Handles updates to IPv6 forwarding rules if the upstream changes.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900963 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
KH Shi701c3ca2023-08-16 13:19:33 +0000964 boolean upstreamSupportsBpf) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900965 // If the upstream interface has changed, remove all rules and re-add them with the new
KH Shi701c3ca2023-08-16 13:19:33 +0000966 // upstream interface. If upstream is a virtual network, treated as no upstream.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900967 if (prevUpstreamIfindex != upstreamIfindex) {
KH Shi701c3ca2023-08-16 13:19:33 +0000968 mBpfCoordinator.updateAllIpv6Rules(this, this.mInterfaceParams,
969 getInterfaceIndexForRule(upstreamIfindex, upstreamSupportsBpf));
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900970 }
KH Shi701c3ca2023-08-16 13:19:33 +0000971 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900972
KH Shi701c3ca2023-08-16 13:19:33 +0000973 // Handles updates to IPv6 downstream rules if a neighbor event is received.
974 private void addOrRemoveIpv6Downstream(NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900975 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900976 if (e == null) return;
977 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
978 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
979 return;
980 }
981
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900982 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
KH Shi59ad35e2023-08-15 07:13:00 +0000983 // Do this here instead of in the Ipv6DownstreamRule constructor to ensure that we
984 // never add rules with a null MAC, only delete them.
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900985 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
KH Shi701c3ca2023-08-16 13:19:33 +0000986 Ipv6DownstreamRule rule = new Ipv6DownstreamRule(
987 getInterfaceIndexForRule(mLastIPv6UpstreamIfindex, mUpstreamSupportsBpf),
988 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900989 if (e.isValid()) {
KH Shie4d549a2023-08-28 09:57:34 +0000990 mBpfCoordinator.addIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900991 } else {
KH Shie4d549a2023-08-28 09:57:34 +0000992 mBpfCoordinator.removeIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900993 }
994 }
995
Hungming Chend71c06e2020-12-21 19:39:49 +0800996 // TODO: consider moving into BpfCoordinator.
997 private void updateClientInfoIpv4(NeighborEvent e) {
Hungming Chend71c06e2020-12-21 19:39:49 +0800998 if (e == null) return;
999 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
1000 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
1001 return;
1002 }
1003
1004 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
1005 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
1006 // IpServer never add clients with a null MAC, only delete them.
1007 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
1008 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
1009 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
1010 if (e.isValid()) {
1011 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
1012 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +08001013 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
1014 }
1015 }
1016
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001017 private void handleNeighborEvent(NeighborEvent e) {
1018 if (mInterfaceParams != null
1019 && mInterfaceParams.index == e.ifindex
1020 && mInterfaceParams.hasMacAddress) {
KH Shi701c3ca2023-08-16 13:19:33 +00001021 addOrRemoveIpv6Downstream(e);
Hungming Chend71c06e2020-12-21 19:39:49 +08001022 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001023 }
1024 }
1025
markchiend63c4f32020-05-21 17:38:28 +08001026 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001027 try {
1028 int upstreamHopLimit = Integer.parseUnsignedInt(
1029 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001030 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001031 // Cap the hop limit to 255.
1032 return (byte) Integer.min(upstreamHopLimit, 255);
1033 } catch (Exception e) {
1034 mLog.e("Failed to find upstream interface hop limit", e);
1035 }
1036 return RaParams.DEFAULT_HOPLIMIT;
1037 }
1038
1039 private void setRaParams(RaParams newParams) {
1040 if (mRaDaemon != null) {
1041 final RaParams deprecatedParams =
1042 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1043
1044 configureLocalIPv6Routes(deprecatedParams.prefixes,
1045 (newParams != null) ? newParams.prefixes : null);
1046
1047 configureLocalIPv6Dns(deprecatedParams.dnses,
1048 (newParams != null) ? newParams.dnses : null);
1049
1050 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1051 }
1052
1053 mLastRaParams = newParams;
1054 }
1055
markchien21021ef2021-06-01 10:58:04 +08001056 private void maybeLogMessage(State state, int what) {
1057 switch (what) {
1058 // Suppress some CMD_* to avoid log flooding.
1059 case CMD_IPV6_TETHER_UPDATE:
1060 case CMD_NEIGHBOR_EVENT:
1061 break;
1062 default:
1063 mLog.log(state.getName() + " got "
1064 + sMagicDecoderRing.get(what, Integer.toString(what)));
1065 }
markchien74a4fa92019-09-09 20:50:49 +08001066 }
1067
1068 private void sendInterfaceState(int newInterfaceState) {
1069 mServingMode = newInterfaceState;
1070 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1071 sendLinkProperties();
1072 }
1073
1074 private void sendLinkProperties() {
1075 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1076 }
1077
1078 private void resetLinkProperties() {
1079 mLinkProperties.clear();
1080 mLinkProperties.setInterfaceName(mIfaceName);
1081 }
1082
markchienf053e4b2020-03-16 21:49:48 +08001083 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001084 // Ignore static address configuration if they are invalid or null. In theory, static
1085 // addresses should not be invalid here because TetheringManager do not allow caller to
1086 // specify invalid static address configuration.
1087 if (request == null || request.localIPv4Address == null
1088 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1089 request.localIPv4Address, request.staticClientAddress)) {
1090 return;
1091 }
markchienf053e4b2020-03-16 21:49:48 +08001092
1093 mStaticIpv4ServerAddr = request.localIPv4Address;
1094 mStaticIpv4ClientAddr = request.staticClientAddress;
1095 }
1096
markchien74a4fa92019-09-09 20:50:49 +08001097 class InitialState extends State {
1098 @Override
1099 public void enter() {
1100 sendInterfaceState(STATE_AVAILABLE);
1101 }
1102
1103 @Override
1104 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001105 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001106 switch (message.what) {
1107 case CMD_TETHER_REQUESTED:
Mark74461fc2022-12-14 08:49:40 +00001108 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001109 switch (message.arg1) {
1110 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001111 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001112 transitionTo(mLocalHotspotState);
1113 break;
1114 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001115 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001116 transitionTo(mTetheredState);
1117 break;
1118 default:
1119 mLog.e("Invalid tethering interface serving state specified.");
1120 }
1121 break;
1122 case CMD_INTERFACE_DOWN:
1123 transitionTo(mUnavailableState);
1124 break;
markchien74a4fa92019-09-09 20:50:49 +08001125 default:
1126 return NOT_HANDLED;
1127 }
1128 return HANDLED;
1129 }
1130 }
1131
Hungming Chen46c30b12020-10-15 17:25:36 +08001132 private void startConntrackMonitoring() {
1133 mBpfCoordinator.startMonitoring(this);
1134 }
1135
1136 private void stopConntrackMonitoring() {
1137 mBpfCoordinator.stopMonitoring(this);
1138 }
1139
Mark3ec851e2023-05-19 08:50:38 +00001140 abstract class BaseServingState extends State {
1141 private final int mDesiredInterfaceState;
1142
1143 BaseServingState(int interfaceState) {
1144 mDesiredInterfaceState = interfaceState;
1145 }
1146
markchien74a4fa92019-09-09 20:50:49 +08001147 @Override
1148 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001149 startConntrackMonitoring();
1150
Mark3ec851e2023-05-19 08:50:38 +00001151 startServingInterface();
1152
1153 if (mLastError != TETHER_ERROR_NO_ERROR) {
1154 transitionTo(mInitialState);
1155 }
1156
1157 if (DBG) Log.d(TAG, getStateString(mDesiredInterfaceState) + " serve " + mIfaceName);
1158 sendInterfaceState(mDesiredInterfaceState);
1159 }
1160
Mark49649c92023-03-15 06:45:04 +00001161 private int getScope() {
1162 if (mDesiredInterfaceState == STATE_TETHERED) {
1163 return CONNECTIVITY_SCOPE_GLOBAL;
1164 }
1165
1166 return CONNECTIVITY_SCOPE_LOCAL;
1167 }
1168
Mark3ec851e2023-05-19 08:50:38 +00001169 private void startServingInterface() {
Mark49649c92023-03-15 06:45:04 +00001170 if (!startIPv4(getScope())) {
Mark74461fc2022-12-14 08:49:40 +00001171 mLastError = TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001172 return;
1173 }
1174
1175 try {
markchienc9daba32020-02-12 00:19:21 +08001176 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001177 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001178 mLog.e("Error Tethering", e);
Mark74461fc2022-12-14 08:49:40 +00001179 mLastError = TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001180 return;
1181 }
1182
1183 if (!startIPv6()) {
1184 mLog.e("Failed to startIPv6");
1185 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1186 return;
1187 }
1188 }
1189
1190 @Override
1191 public void exit() {
1192 // Note that at this point, we're leaving the tethered state. We can fail any
1193 // of these operations, but it doesn't really change that we have to try them
1194 // all in sequence.
1195 stopIPv6();
1196
1197 try {
markchien12c5bb82020-01-07 14:43:17 +08001198 NetdUtils.untetherInterface(mNetd, mIfaceName);
1199 } catch (RemoteException | ServiceSpecificException e) {
Mark74461fc2022-12-14 08:49:40 +00001200 mLastError = TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001201 mLog.e("Failed to untether interface: " + e);
1202 }
1203
1204 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001205 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001206
1207 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001208
1209 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1210 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001211 }
1212
1213 @Override
1214 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001215 switch (message.what) {
1216 case CMD_TETHER_UNREQUESTED:
1217 transitionTo(mInitialState);
1218 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1219 break;
1220 case CMD_INTERFACE_DOWN:
1221 transitionTo(mUnavailableState);
1222 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1223 break;
1224 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001225 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001226 sendLinkProperties();
1227 break;
1228 case CMD_IP_FORWARDING_ENABLE_ERROR:
1229 case CMD_IP_FORWARDING_DISABLE_ERROR:
1230 case CMD_START_TETHERING_ERROR:
1231 case CMD_STOP_TETHERING_ERROR:
1232 case CMD_SET_DNS_FORWARDERS_ERROR:
Mark74461fc2022-12-14 08:49:40 +00001233 mLastError = TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001234 transitionTo(mInitialState);
1235 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001236 case CMD_NEW_PREFIX_REQUEST:
1237 handleNewPrefixRequest((IpPrefix) message.obj);
1238 break;
markchienc9daba32020-02-12 00:19:21 +08001239 case CMD_NOTIFY_PREFIX_CONFLICT:
1240 mLog.i("restart tethering: " + mInterfaceType);
1241 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1242 transitionTo(mWaitingForRestartState);
1243 break;
markchien74a4fa92019-09-09 20:50:49 +08001244 default:
1245 return false;
1246 }
1247 return true;
1248 }
Mark3ec851e2023-05-19 08:50:38 +00001249
1250 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
1251 if (!currentPrefix.contains(mIpv4Address.getAddress())
1252 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
1253 Log.e(TAG, "Invalid prefix: " + currentPrefix);
1254 return;
1255 }
1256
1257 final LinkAddress deprecatedLinkAddress = mIpv4Address;
Mark49649c92023-03-15 06:45:04 +00001258 mIpv4Address = requestIpv4Address(getScope(), false);
Mark3ec851e2023-05-19 08:50:38 +00001259 if (mIpv4Address == null) {
1260 mLog.e("Fail to request a new downstream prefix");
1261 return;
1262 }
1263 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
1264
1265 // Add new IPv4 address on the interface.
1266 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1267 mLog.e("Failed to add new IP " + srvAddr);
1268 return;
1269 }
1270
1271 // Remove deprecated routes from local network.
1272 removeRoutesFromLocalNetwork(
1273 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1274 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1275
1276 // Add new routes to local network.
1277 addRoutesToLocalNetwork(
1278 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1279 mLinkProperties.addLinkAddress(mIpv4Address);
1280
1281 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1282 // listen on the interface configured with new IPv4 address, that results DNS validation
1283 // failure of downstream client even if appropriate routes have been configured.
1284 try {
1285 mNetd.tetherApplyDnsInterfaces();
1286 } catch (ServiceSpecificException | RemoteException e) {
1287 mLog.e("Failed to update local DNS caching server");
1288 return;
1289 }
1290 sendLinkProperties();
1291
1292 // Notify DHCP server that new prefix/route has been applied on IpServer.
1293 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1294 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1295 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1296 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1297 try {
1298 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1299 @Override
1300 public void callback(int statusCode) {
1301 if (statusCode != STATUS_SUCCESS) {
1302 mLog.e("Error updating DHCP serving params: " + statusCode);
1303 }
1304 }
1305 });
1306 } catch (RemoteException e) {
1307 mLog.e("Error updating DHCP serving params", e);
1308 }
1309 }
markchien74a4fa92019-09-09 20:50:49 +08001310 }
1311
1312 // Handling errors in BaseServingState.enter() by transitioning is
1313 // problematic because transitioning during a multi-state jump yields
1314 // a Log.wtf(). Ultimately, there should be only one ServingState,
1315 // and forwarding and NAT rules should be handled by a coordinating
1316 // functional element outside of IpServer.
1317 class LocalHotspotState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001318 LocalHotspotState() {
1319 super(STATE_LOCAL_ONLY);
markchien74a4fa92019-09-09 20:50:49 +08001320 }
1321
1322 @Override
1323 public boolean processMessage(Message message) {
1324 if (super.processMessage(message)) return true;
1325
markchien21021ef2021-06-01 10:58:04 +08001326 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001327 switch (message.what) {
1328 case CMD_TETHER_REQUESTED:
1329 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1330 break;
1331 case CMD_TETHER_CONNECTION_CHANGED:
1332 // Ignored in local hotspot state.
1333 break;
1334 default:
1335 return false;
1336 }
1337 return true;
1338 }
1339 }
1340
1341 // Handling errors in BaseServingState.enter() by transitioning is
1342 // problematic because transitioning during a multi-state jump yields
1343 // a Log.wtf(). Ultimately, there should be only one ServingState,
1344 // and forwarding and NAT rules should be handled by a coordinating
1345 // functional element outside of IpServer.
1346 class TetheredState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001347 TetheredState() {
1348 super(STATE_TETHERED);
markchien74a4fa92019-09-09 20:50:49 +08001349 }
1350
1351 @Override
1352 public void exit() {
1353 cleanupUpstream();
KH Shi701c3ca2023-08-16 13:19:33 +00001354 mBpfCoordinator.clearAllIpv6Rules(IpServer.this);
markchien74a4fa92019-09-09 20:50:49 +08001355 super.exit();
1356 }
1357
Hungming Chena6e78692021-02-08 17:15:35 +08001358 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1359 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1360 // and behaviour. While upstream is switching from offload supported interface to
1361 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1362 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1363 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1364 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1365 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1366 // in the state machine. Once there is any case out whish is not covered by previous cases,
1367 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001368 private void cleanupUpstream() {
1369 if (mUpstreamIfaceSet == null) return;
1370
1371 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1372 mUpstreamIfaceSet = null;
KH Shi701c3ca2023-08-16 13:19:33 +00001373 mBpfCoordinator.updateAllIpv6Rules(
1374 IpServer.this, IpServer.this.mInterfaceParams, NO_UPSTREAM);
markchien74a4fa92019-09-09 20:50:49 +08001375 }
1376
1377 private void cleanupUpstreamInterface(String upstreamIface) {
1378 // Note that we don't care about errors here.
1379 // Sometimes interfaces are gone before we get
1380 // to remove their rules, which generates errors.
1381 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001382 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
Chalard Jean55ccfe12023-10-06 18:31:08 +09001383 removeInterfaceForward(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001384 }
1385
1386 @Override
1387 public boolean processMessage(Message message) {
1388 if (super.processMessage(message)) return true;
1389
markchien21021ef2021-06-01 10:58:04 +08001390 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001391 switch (message.what) {
1392 case CMD_TETHER_REQUESTED:
1393 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1394 break;
1395 case CMD_TETHER_CONNECTION_CHANGED:
1396 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1397 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1398 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1399 break;
1400 }
1401
1402 if (newUpstreamIfaceSet == null) {
1403 cleanupUpstream();
1404 break;
1405 }
1406
1407 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1408 cleanupUpstreamInterface(removed);
1409 }
1410
1411 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1412 // This makes the call to cleanupUpstream() in the error
1413 // path for any interface neatly cleanup all the interfaces.
1414 mUpstreamIfaceSet = newUpstreamIfaceSet;
1415
1416 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001417 // Add upstream index to name mapping for the tether stats usage in the
1418 // coordinator. Although this mapping could be added by both class
1419 // Tethering and IpServer, adding mapping from IpServer guarantees that
1420 // the mapping is added before adding forwarding rules. That is because
1421 // there are different state machines in both classes. It is hard to
1422 // guarantee the link property update order between multiple state machines.
1423 // Note that both IPv4 and IPv6 interface may be added because
1424 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1425 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1426 // capability may be updated later. In that case, IPv6 interface mapping is
1427 // updated in updateUpstreamIPv6LinkProperties.
1428 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1429 final InterfaceParams upstreamIfaceParams =
1430 mDeps.getInterfaceParams(ifname);
1431 if (upstreamIfaceParams != null) {
KH Shi701c3ca2023-08-16 13:19:33 +00001432 mBpfCoordinator.maybeAddUpstreamToLookupTable(
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001433 upstreamIfaceParams.index, ifname);
1434 }
1435 }
1436
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001437 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001438 try {
Chalard Jean55ccfe12023-10-06 18:31:08 +09001439 addInterfaceForward(mIfaceName, ifname);
markchien12c5bb82020-01-07 14:43:17 +08001440 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean55ccfe12023-10-06 18:31:08 +09001441 mLog.e("Exception enabling iface forward", e);
markchien74a4fa92019-09-09 20:50:49 +08001442 cleanupUpstream();
Mark74461fc2022-12-14 08:49:40 +00001443 mLastError = TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001444 transitionTo(mInitialState);
1445 return true;
1446 }
1447 }
1448 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001449 case CMD_NEIGHBOR_EVENT:
1450 handleNeighborEvent((NeighborEvent) message.obj);
1451 break;
markchien74a4fa92019-09-09 20:50:49 +08001452 default:
1453 return false;
1454 }
1455 return true;
1456 }
1457
1458 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1459 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1460 if (mUpstreamIfaceSet != null && newIfaces != null) {
1461 return mUpstreamIfaceSet.equals(newIfaces);
1462 }
1463 return false;
1464 }
1465
1466 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1467 if (mUpstreamIfaceSet == null) return new HashSet<>();
1468
1469 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1470 removed.removeAll(newIfaces.ifnames);
1471 return removed;
1472 }
1473
1474 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1475 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1476 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1477 return added;
1478 }
1479 }
1480
1481 /**
1482 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001483 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001484 * specific state machine from its list of possible recipients of
1485 * tethering requests. The state machine itself will hang around until
1486 * the garbage collector finds it.
1487 */
1488 class UnavailableState extends State {
1489 @Override
1490 public void enter() {
KH Shi701c3ca2023-08-16 13:19:33 +00001491 // TODO: move mIpNeighborMonitor.stop() to TetheredState#exit, and trigger a neighbours
1492 // dump after starting mIpNeighborMonitor.
h.zhangd244bd02020-06-14 14:46:54 +08001493 mIpNeighborMonitor.stop();
Mark74461fc2022-12-14 08:49:40 +00001494 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001495 sendInterfaceState(STATE_UNAVAILABLE);
1496 }
1497 }
1498
markchienc9daba32020-02-12 00:19:21 +08001499 class WaitingForRestartState extends State {
1500 @Override
1501 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001502 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001503 switch (message.what) {
1504 case CMD_TETHER_UNREQUESTED:
1505 transitionTo(mInitialState);
1506 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1507 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1508 break;
1509 case CMD_INTERFACE_DOWN:
1510 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001511 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001512 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1513 break;
1514 default:
1515 return false;
1516 }
1517 return true;
1518 }
1519 }
1520
markchien74a4fa92019-09-09 20:50:49 +08001521 // Accumulate routes representing "prefixes to be assigned to the local
1522 // interface", for subsequent modification of local_network routing.
1523 private static ArrayList<RouteInfo> getLocalRoutesFor(
1524 String ifname, HashSet<IpPrefix> prefixes) {
1525 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1526 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001527 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001528 }
1529 return localRoutes;
1530 }
1531
1532 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1533 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1534 final byte[] dnsBytes = localPrefix.getRawAddress();
1535 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1536 try {
1537 return Inet6Address.getByAddress(null, dnsBytes, 0);
1538 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001539 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001540 return null;
1541 }
1542 }
1543
1544 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1545 final byte random = (byte) (new Random()).nextInt();
1546 for (int value : excluded) {
1547 if (random == value) return dflt;
1548 }
1549 return random;
1550 }
1551}