blob: 5ec4d15518c0ce8ae3cbe6e9056eec394cdf3efb [file] [log] [blame]
markchien74a4fa92019-09-09 20:50:49 +08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net.ip;
18
markchien6cf0e552019-12-06 15:24:53 +080019import static android.net.RouteInfo.RTN_UNICAST;
Mark49649c92023-03-15 06:45:04 +000020import static android.net.TetheringManager.CONNECTIVITY_SCOPE_GLOBAL;
21import static android.net.TetheringManager.CONNECTIVITY_SCOPE_LOCAL;
Mark74461fc2022-12-14 08:49:40 +000022import static android.net.TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
23import static android.net.TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
24import static android.net.TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
25import static android.net.TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
26import static android.net.TetheringManager.TETHER_ERROR_NO_ERROR;
27import static android.net.TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
28import static android.net.TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien245352e2020-02-27 20:27:18 +080029import static android.net.TetheringManager.TetheringRequest.checkStaticAddressConfiguration;
markchien74a4fa92019-09-09 20:50:49 +080030import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
markchien74a4fa92019-09-09 20:50:49 +080031import static android.net.util.NetworkConstants.asByte;
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +090032import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080033
Chalard Jean78701642020-07-31 20:00:30 +090034import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH;
Xiao Ma1f993302023-08-09 18:55:49 +090035import static com.android.net.module.util.NetworkStackConstants.RFC7421_PREFIX_LENGTH;
markchien7dc1b4d2021-07-13 17:12:56 +080036import static com.android.networkstack.tethering.UpstreamNetworkState.isVcnInterface;
markchiend02f9af2021-11-04 11:26:03 +080037import static com.android.networkstack.tethering.util.PrefixUtils.asIpPrefix;
38import static com.android.networkstack.tethering.util.TetheringMessageBase.BASE_IPSERVER;
Chalard Jean78701642020-07-31 20:00:30 +090039
markchien74a4fa92019-09-09 20:50:49 +080040import android.net.INetd;
41import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080042import android.net.IpPrefix;
43import android.net.LinkAddress;
44import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090045import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080046import android.net.RouteInfo;
Chalard Jean2fb66f12023-08-25 12:50:37 +090047import android.net.RoutingCoordinatorManager;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090048import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080049import android.net.TetheringManager;
markchienf053e4b2020-03-16 21:49:48 +080050import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090051import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080052import android.net.dhcp.DhcpServerCallbacks;
53import android.net.dhcp.DhcpServingParamsParcel;
54import android.net.dhcp.DhcpServingParamsParcelExt;
Xiao Ma49889dd2020-04-03 17:01:33 +090055import android.net.dhcp.IDhcpEventCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080056import android.net.dhcp.IDhcpServer;
57import android.net.ip.RouterAdvertisementDaemon.RaParams;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090058import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080059import android.os.Message;
60import android.os.RemoteException;
61import android.os.ServiceSpecificException;
KH Shiff1400b2023-11-08 14:50:15 +000062import android.util.ArraySet;
markchien74a4fa92019-09-09 20:50:49 +080063import 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
KH Shi3f738fc2023-05-23 22:37:17 +080069import com.android.internal.annotations.VisibleForTesting;
markchien74a4fa92019-09-09 20:50:49 +080070import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080071import com.android.internal.util.State;
markchien932df542021-08-12 13:56:43 +080072import com.android.modules.utils.build.SdkLevel;
Patrick Rohr9f371f02022-03-04 15:14:27 +010073import com.android.net.module.util.InterfaceParams;
Chalard Jeanadcec9e2021-10-29 15:57:22 +090074import com.android.net.module.util.NetdUtils;
Chalard Jean2fb66f12023-08-25 12:50:37 +090075import com.android.net.module.util.SdkUtil.LateSdk;
Patrick Rohrb873e252022-06-16 16:38:43 -070076import com.android.net.module.util.SharedLog;
Xiao Mac81c0662022-06-17 14:58:03 +090077import com.android.net.module.util.ip.InterfaceController;
78import com.android.net.module.util.ip.IpNeighborMonitor;
79import com.android.net.module.util.ip.IpNeighborMonitor.NeighborEvent;
Hungming Chen68f1c2a2020-03-12 21:24:01 +080080import com.android.networkstack.tethering.BpfCoordinator;
Hungming Chend71c06e2020-12-21 19:39:49 +080081import com.android.networkstack.tethering.BpfCoordinator.ClientInfo;
KH Shi59ad35e2023-08-15 07:13:00 +000082import com.android.networkstack.tethering.BpfCoordinator.Ipv6DownstreamRule;
markchienc9daba32020-02-12 00:19:21 +080083import com.android.networkstack.tethering.PrivateAddressCoordinator;
markchienb961d3d2022-02-26 00:39:06 +080084import com.android.networkstack.tethering.TetheringConfiguration;
Wayne Ma6cd440f2022-03-14 18:04:33 +080085import com.android.networkstack.tethering.metrics.TetheringMetrics;
markchiend02f9af2021-11-04 11:26:03 +080086import com.android.networkstack.tethering.util.InterfaceSet;
87import com.android.networkstack.tethering.util.PrefixUtils;
Mark21502962022-12-21 06:58:23 +000088import com.android.networkstack.tethering.util.StateMachineShim;
89import com.android.networkstack.tethering.util.SyncStateMachine.StateInfo;
markchien74a4fa92019-09-09 20:50:49 +080090
91import java.net.Inet4Address;
92import java.net.Inet6Address;
markchien74a4fa92019-09-09 20:50:49 +080093import java.net.UnknownHostException;
94import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090095import java.util.Arrays;
KH Shi3f738fc2023-05-23 22:37:17 +080096import java.util.Collection;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090097import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080098import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090099import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +0800100import java.util.Objects;
101import java.util.Random;
102import java.util.Set;
103
104/**
105 * Provides the interface to IP-layer serving functionality for a given network
106 * interface, e.g. for tethering or "local-only hotspot" mode.
107 *
108 * @hide
109 */
Mark21502962022-12-21 06:58:23 +0000110public class IpServer extends StateMachineShim {
markchien74a4fa92019-09-09 20:50:49 +0800111 public static final int STATE_UNAVAILABLE = 0;
112 public static final int STATE_AVAILABLE = 1;
113 public static final int STATE_TETHERED = 2;
114 public static final int STATE_LOCAL_ONLY = 3;
115
116 /** Get string name of |state|.*/
117 public static String getStateString(int state) {
118 switch (state) {
119 case STATE_UNAVAILABLE: return "UNAVAILABLE";
120 case STATE_AVAILABLE: return "AVAILABLE";
121 case STATE_TETHERED: return "TETHERED";
122 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
123 }
124 return "UNKNOWN: " + state;
125 }
126
127 private static final byte DOUG_ADAMS = (byte) 42;
128
markchien74a4fa92019-09-09 20:50:49 +0800129 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800130 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800131
132 // TODO: have this configurable
133 private static final int DHCP_LEASE_TIME_SECS = 3600;
134
KH Shi701c3ca2023-08-16 13:19:33 +0000135 private static final int NO_UPSTREAM = 0;
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900136 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
137
markchien74a4fa92019-09-09 20:50:49 +0800138 private static final String TAG = "IpServer";
139 private static final boolean DBG = false;
140 private static final boolean VDBG = false;
141 private static final Class[] sMessageClasses = {
142 IpServer.class
143 };
144 private static final SparseArray<String> sMagicDecoderRing =
145 MessageUtils.findMessageNames(sMessageClasses);
146
147 /** IpServer callback. */
148 public static class Callback {
149 /**
150 * Notify that |who| has changed its tethering state.
151 *
152 * @param who the calling instance of IpServer
153 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800154 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800155 */
markchien9d353822019-12-16 20:15:20 +0800156 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800157
158 /**
159 * Notify that |who| has new LinkProperties.
160 *
161 * @param who the calling instance of IpServer
162 * @param newLp the new LinkProperties to report
163 */
markchien9d353822019-12-16 20:15:20 +0800164 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900165
166 /**
167 * Notify that the DHCP leases changed in one of the IpServers.
168 */
169 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800170
171 /**
172 * Request Tethering change.
173 *
174 * @param tetheringType the downstream type of this IpServer.
175 * @param enabled enable or disable tethering.
176 */
177 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800178 }
179
180 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800181 public abstract static class Dependencies {
Tyler Wear90e40632020-03-13 11:38:38 -0700182 /**
183 * Create a DadProxy instance to be used by IpServer.
184 * To support multiple tethered interfaces concurrently DAD Proxy
185 * needs to be supported per IpServer instead of per upstream.
186 */
187 public DadProxy getDadProxy(Handler handler, InterfaceParams ifParams) {
188 return new DadProxy(handler, ifParams);
189 }
190
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900191 /** Create an IpNeighborMonitor to be used by this IpServer */
192 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
193 IpNeighborMonitor.NeighborEventConsumer consumer) {
194 return new IpNeighborMonitor(handler, log, consumer);
195 }
196
markchien74a4fa92019-09-09 20:50:49 +0800197 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
198 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
199 return new RouterAdvertisementDaemon(ifParams);
200 }
201
202 /** Get |ifName|'s interface information.*/
203 public InterfaceParams getInterfaceParams(String ifName) {
204 return InterfaceParams.getByName(ifName);
205 }
206
markchien9d353822019-12-16 20:15:20 +0800207 /** Create a DhcpServer instance to be used by IpServer. */
208 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
209 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800210 }
211
markchien74a4fa92019-09-09 20:50:49 +0800212 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800213 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800214 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800215 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800216 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800217 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800218 // notification from the {@link Tethering.TetherMainSM} that it had trouble enabling IP
219 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800220 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800221 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble disabling IP
222 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800223 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800224 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble starting
225 // tethering
markchien6cf0e552019-12-06 15:24:53 +0800226 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800227 // notification from the {@link Tethering.TetherMainSM} that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800228 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800229 // notification from the {@link Tethering.TetherMainSM} that it had trouble setting the DNS
230 // forwarders
markchien6cf0e552019-12-06 15:24:53 +0800231 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800232 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800233 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800234 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800235 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900236 // new neighbor cache entry on our interface
237 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900238 // request from DHCP server that it wants to have a new prefix
239 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800240 // request from PrivateAddressCoordinator to restart tethering.
241 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
Mark50eef832023-09-19 06:56:14 +0000242 public static final int CMD_SERVICE_FAILED_TO_START = BASE_IPSERVER + 14;
markchien74a4fa92019-09-09 20:50:49 +0800243
244 private final State mInitialState;
245 private final State mLocalHotspotState;
246 private final State mTetheredState;
247 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800248 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800249
250 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800251 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800252 @NonNull
253 private final BpfCoordinator mBpfCoordinator;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900254 // Contains null if the connectivity module is unsupported, as the routing coordinator is not
255 // available. Must use LateSdk because MessageUtils enumerates fields in this class, so it
256 // must be able to find all classes at runtime.
257 @NonNull
258 private final LateSdk<RoutingCoordinatorManager> mRoutingCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800259 private final Callback mCallback;
260 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800261 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800262
263 private final String mIfaceName;
264 private final int mInterfaceType;
265 private final LinkProperties mLinkProperties;
266 private final boolean mUsingLegacyDhcp;
markchienfb65dfe2022-02-25 23:14:58 +0800267 private final int mP2pLeasesSubnetPrefixLength;
markchien74a4fa92019-09-09 20:50:49 +0800268
269 private final Dependencies mDeps;
270
271 private int mLastError;
272 private int mServingMode;
273 private InterfaceSet mUpstreamIfaceSet; // may change over time
KH Shi701c3ca2023-08-16 13:19:33 +0000274 // mInterfaceParams can't be final now because IpServer will be created when receives
275 // WIFI_AP_STATE_CHANGED broadcasts or when it detects that the wifi interface has come up.
276 // In the latter case, the interface is not fully initialized and the MAC address might not
277 // be correct (it will be set with a randomized MAC address later).
278 // TODO: Consider create the IpServer only when tethering want to enable it, then we can
279 // make mInterfaceParams final.
markchien74a4fa92019-09-09 20:50:49 +0800280 private InterfaceParams mInterfaceParams;
281 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
282 // properties are those selected by the IPv6TetheringCoordinator and relayed
283 // to us. By comparison, mLinkProperties contains the addresses and directly
284 // connected routes that have been formed from these properties iff. we have
285 // succeeded in configuring them and are able to announce them within Router
286 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
287 private LinkProperties mLastIPv6LinkProperties;
288 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700289 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800290
291 // To be accessed only on the handler thread
292 private int mDhcpServerStartIndex = 0;
293 private IDhcpServer mDhcpServer;
294 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800295
296 private LinkAddress mStaticIpv4ServerAddr;
297 private LinkAddress mStaticIpv4ClientAddr;
298
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900299 @NonNull
300 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800301
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900302 private int mLastIPv6UpstreamIfindex = 0;
KH Shi68770342023-08-17 14:34:31 +0000303 private boolean mUpstreamSupportsBpf = false;
KH Shi3f738fc2023-05-23 22:37:17 +0800304 @NonNull
305 private Set<IpPrefix> mLastIPv6UpstreamPrefixes = Collections.emptySet();
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900306
307 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
308 public void accept(NeighborEvent e) {
309 sendMessage(CMD_NEIGHBOR_EVENT, e);
310 }
311 }
312
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900313 private final IpNeighborMonitor mIpNeighborMonitor;
314
markchienc9daba32020-02-12 00:19:21 +0800315 private LinkAddress mIpv4Address;
316
Wayne Ma6cd440f2022-03-14 18:04:33 +0800317 private final TetheringMetrics mTetheringMetrics;
Mark21502962022-12-21 06:58:23 +0000318 private final Handler mHandler;
Markcf11be92023-12-05 08:19:15 +0000319 private final boolean mIsSyncSM;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800320
Hungming Chen5bc3af92020-05-12 19:15:24 +0800321 // TODO: Add a dependency object to pass the data members or variables from the tethering
322 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800323 public IpServer(
Mark21502962022-12-21 06:58:23 +0000324 String ifaceName, Handler handler, int interfaceType, SharedLog log,
Chalard Jean2fb66f12023-08-25 12:50:37 +0900325 INetd netd, @NonNull BpfCoordinator bpfCoordinator,
326 @Nullable LateSdk<RoutingCoordinatorManager> routingCoordinator, Callback callback,
markchienb961d3d2022-02-26 00:39:06 +0800327 TetheringConfiguration config, PrivateAddressCoordinator addressCoordinator,
Wayne Ma6cd440f2022-03-14 18:04:33 +0800328 TetheringMetrics tetheringMetrics, Dependencies deps) {
Markcf11be92023-12-05 08:19:15 +0000329 super(ifaceName, config.isSyncSM() ? null : handler.getLooper());
Mark21502962022-12-21 06:58:23 +0000330 mHandler = handler;
markchien74a4fa92019-09-09 20:50:49 +0800331 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800332 mNetd = netd;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900333 mBpfCoordinator = bpfCoordinator;
334 mRoutingCoordinator = routingCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800335 mCallback = callback;
336 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
337 mIfaceName = ifaceName;
338 mInterfaceType = interfaceType;
339 mLinkProperties = new LinkProperties();
markchienb961d3d2022-02-26 00:39:06 +0800340 mUsingLegacyDhcp = config.useLegacyDhcpServer();
markchienfb65dfe2022-02-25 23:14:58 +0800341 mP2pLeasesSubnetPrefixLength = config.getP2pLeasesSubnetPrefixLength();
Markcf11be92023-12-05 08:19:15 +0000342 mIsSyncSM = config.isSyncSM();
markchienc9daba32020-02-12 00:19:21 +0800343 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800344 mDeps = deps;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800345 mTetheringMetrics = tetheringMetrics;
markchien74a4fa92019-09-09 20:50:49 +0800346 resetLinkProperties();
Mark74461fc2022-12-14 08:49:40 +0000347 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800348 mServingMode = STATE_AVAILABLE;
349
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900350 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
351 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800352
KH Shie4d549a2023-08-28 09:57:34 +0000353 // IP neighbor monitor monitors the neighbor events for adding/removing IPv6 downstream rule
354 // per client. If BPF offload is not supported, don't start listening for neighbor events.
355 if (mBpfCoordinator.isUsingBpfOffload() && !mIpNeighborMonitor.start()) {
Hungming Chen5bc3af92020-05-12 19:15:24 +0800356 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900357 }
358
markchien74a4fa92019-09-09 20:50:49 +0800359 mInitialState = new InitialState();
360 mLocalHotspotState = new LocalHotspotState();
361 mTetheredState = new TetheredState();
362 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800363 mWaitingForRestartState = new WaitingForRestartState();
Mark21502962022-12-21 06:58:23 +0000364 final ArrayList allStates = new ArrayList<StateInfo>();
365 allStates.add(new StateInfo(mInitialState, null));
366 allStates.add(new StateInfo(mLocalHotspotState, null));
367 allStates.add(new StateInfo(mTetheredState, null));
368 allStates.add(new StateInfo(mWaitingForRestartState, mTetheredState));
369 allStates.add(new StateInfo(mUnavailableState, null));
370 addAllStates(allStates);
371 }
markchien74a4fa92019-09-09 20:50:49 +0800372
Mark21502962022-12-21 06:58:23 +0000373 private Handler getHandler() {
374 return mHandler;
375 }
376
377 /** Start IpServer state machine. */
378 public void start() {
379 start(mInitialState);
markchien74a4fa92019-09-09 20:50:49 +0800380 }
381
382 /** Interface name which IpServer served.*/
383 public String interfaceName() {
384 return mIfaceName;
385 }
386
387 /**
markchien9b4d7572019-12-25 19:40:32 +0800388 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800389 */
390 public int interfaceType() {
391 return mInterfaceType;
392 }
393
394 /** Last error from this IpServer. */
395 public int lastError() {
396 return mLastError;
397 }
398
399 /** Serving mode is the current state of IpServer state machine. */
400 public int servingMode() {
401 return mServingMode;
402 }
403
404 /** The properties of the network link which IpServer is serving. */
405 public LinkProperties linkProperties() {
406 return new LinkProperties(mLinkProperties);
407 }
408
markchienc9daba32020-02-12 00:19:21 +0800409 /** The address which IpServer is using. */
410 public LinkAddress getAddress() {
411 return mIpv4Address;
412 }
413
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900414 /**
415 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
416 * thread.
417 */
418 public List<TetheredClient> getAllLeases() {
419 return Collections.unmodifiableList(mDhcpLeases);
420 }
421
Marka5424582022-12-01 13:46:32 +0000422 /** Enable this IpServer. IpServer state machine will be tethered or localHotspot state. */
423 public void enable(final int requestedState, final TetheringRequestParcel request) {
424 sendMessage(CMD_TETHER_REQUESTED, requestedState, 0, request);
425 }
426
markchien74a4fa92019-09-09 20:50:49 +0800427 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
428 public void stop() {
429 sendMessage(CMD_INTERFACE_DOWN);
430 }
431
432 /**
433 * Tethering is canceled. IpServer state machine will be available and wait for
434 * next tethering request.
435 */
436 public void unwanted() {
437 sendMessage(CMD_TETHER_UNREQUESTED);
438 }
439
440 /** Internals. */
441
Mark49649c92023-03-15 06:45:04 +0000442 private boolean startIPv4(int scope) {
443 return configureIPv4(true, scope);
markchien74a4fa92019-09-09 20:50:49 +0800444 }
445
446 /**
447 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
448 * handler.
449 *
450 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
451 * with different implementations of the callback, to differentiate handling of success/error in
452 * each call.
453 */
454 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
455 @Override
456 public void onStatusAvailable(int statusCode) {
457 getHandler().post(() -> callback(statusCode));
458 }
459
460 public abstract void callback(int statusCode);
461
462 @Override
463 public int getInterfaceVersion() {
464 return this.VERSION;
465 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900466
467 @Override
468 public String getInterfaceHash() {
469 return this.HASH;
470 }
markchien74a4fa92019-09-09 20:50:49 +0800471 }
472
473 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
474 private final int mStartIndex;
475
476 private DhcpServerCallbacksImpl(int startIndex) {
477 mStartIndex = startIndex;
478 }
479
480 @Override
481 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
482 getHandler().post(() -> {
483 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
484 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800485 // This start request is obsolete. Explicitly stop the DHCP server to shut
486 // down its thread. When the |server| binder token goes out of scope, the
487 // garbage collector will finalize it, which causes the network stack process
488 // garbage collector to collect the server itself.
489 try {
490 server.stop(null);
491 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800492 return;
493 }
494
495 if (statusCode != STATUS_SUCCESS) {
496 mLog.e("Error obtaining DHCP server: " + statusCode);
497 handleError();
498 return;
499 }
500
501 mDhcpServer = server;
502 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900503 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800504 @Override
505 public void callback(int startStatusCode) {
506 if (startStatusCode != STATUS_SUCCESS) {
507 mLog.e("Error starting DHCP server: " + startStatusCode);
508 handleError();
509 }
510 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900511 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800512 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800513 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800514 }
515 });
516 }
517
518 private void handleError() {
Mark74461fc2022-12-14 08:49:40 +0000519 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
Markcf11be92023-12-05 08:19:15 +0000520 if (mIsSyncSM) {
Markbe99f862022-12-21 16:39:23 +0000521 sendMessage(CMD_SERVICE_FAILED_TO_START, TETHER_ERROR_DHCPSERVER_ERROR);
522 } else {
523 sendMessageAtFrontOfQueueToAsyncSM(CMD_SERVICE_FAILED_TO_START,
524 TETHER_ERROR_DHCPSERVER_ERROR);
525 }
markchien74a4fa92019-09-09 20:50:49 +0800526 }
527 }
528
Xiao Ma4455d6b2020-04-09 10:13:44 +0900529 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900530 @Override
531 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
532 final ArrayList<TetheredClient> leases = new ArrayList<>();
533 for (DhcpLeaseParcelable lease : leaseParcelables) {
534 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900535 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
536 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
537 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900538
539 final MacAddress macAddress;
540 try {
541 macAddress = MacAddress.fromBytes(lease.hwAddr);
542 } catch (IllegalArgumentException e) {
543 Log.wtf(TAG, "Invalid address received from DhcpServer: "
544 + Arrays.toString(lease.hwAddr));
545 return;
546 }
547
548 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900549 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900550 leases.add(new TetheredClient(
551 macAddress,
552 Collections.singletonList(addressInfo),
553 mInterfaceType));
554 }
555
556 getHandler().post(() -> {
557 mDhcpLeases = leases;
558 mCallback.dhcpLeasesChanged();
559 });
560 }
561
562 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900563 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
564 Objects.requireNonNull(currentPrefix);
565 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900566 }
567
568 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900569 public int getInterfaceVersion() {
570 return this.VERSION;
571 }
572
573 @Override
574 public String getInterfaceHash() throws RemoteException {
575 return this.HASH;
576 }
577 }
578
Xiao Ma4455d6b2020-04-09 10:13:44 +0900579 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
580 Objects.requireNonNull(ipv4Address);
581 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
582 }
583
584 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
585 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
586 @Nullable Inet4Address clientAddr) {
587 final boolean changePrefixOnDecline =
588 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
markchienfb65dfe2022-02-25 23:14:58 +0800589 final int subnetPrefixLength = mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
590 ? mP2pLeasesSubnetPrefixLength : 0 /* default value */;
591
Xiao Ma4455d6b2020-04-09 10:13:44 +0900592 return new DhcpServingParamsParcelExt()
593 .setDefaultRouters(defaultRouter)
594 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
595 .setDnsServers(dnsServer)
596 .setServerAddr(serverAddr)
597 .setMetered(true)
598 .setSingleClientAddr(clientAddr)
markchienfb65dfe2022-02-25 23:14:58 +0800599 .setChangePrefixOnDecline(changePrefixOnDecline)
600 .setLeasesSubnetPrefixLength(subnetPrefixLength);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900601 // TODO: also advertise link MTU
602 }
603
markchien245352e2020-02-27 20:27:18 +0800604 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800605 if (mUsingLegacyDhcp) {
606 return true;
607 }
markchien245352e2020-02-27 20:27:18 +0800608
609 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800610 final Inet4Address clientAddr = clientLinkAddr == null ? null :
611 (Inet4Address) clientLinkAddr.getAddress();
612
Xiao Ma4455d6b2020-04-09 10:13:44 +0900613 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
614 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800615 mDhcpServerStartIndex++;
616 mDeps.makeDhcpServer(
617 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
618 return true;
619 }
620
621 private void stopDhcp() {
622 // Make all previous start requests obsolete so servers are not started later
623 mDhcpServerStartIndex++;
624
625 if (mDhcpServer != null) {
626 try {
627 mDhcpServer.stop(new OnHandlerStatusCallback() {
628 @Override
629 public void callback(int statusCode) {
630 if (statusCode != STATUS_SUCCESS) {
631 mLog.e("Error stopping DHCP server: " + statusCode);
Mark74461fc2022-12-14 08:49:40 +0000632 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800633 // Not much more we can do here
634 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900635 mDhcpLeases.clear();
636 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800637 }
638 });
639 mDhcpServer = null;
640 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900641 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800642 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800643 }
644 }
645 }
646
markchien245352e2020-02-27 20:27:18 +0800647 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
648 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800649 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800650 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800651 } else {
652 stopDhcp();
653 return true;
654 }
655 }
656
657 private void stopIPv4() {
Mark49649c92023-03-15 06:45:04 +0000658 configureIPv4(false /* enabled */, CONNECTIVITY_SCOPE_GLOBAL /* not used */);
markchien74a4fa92019-09-09 20:50:49 +0800659 // NOTE: All of configureIPv4() will be refactored out of existence
660 // into calls to InterfaceController, shared with startIPv4().
661 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800662 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800663 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800664 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800665 mStaticIpv4ServerAddr = null;
666 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800667 }
668
Mark49649c92023-03-15 06:45:04 +0000669 private boolean configureIPv4(boolean enabled, int scope) {
markchien74a4fa92019-09-09 20:50:49 +0800670 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
671
markchienc9daba32020-02-12 00:19:21 +0800672 if (enabled) {
Mark49649c92023-03-15 06:45:04 +0000673 mIpv4Address = requestIpv4Address(scope, true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800674 }
675
676 if (mIpv4Address == null) {
677 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800678 return false;
markchien74a4fa92019-09-09 20:50:49 +0800679 }
680
markchien69681d62021-11-15 23:58:05 +0800681 if (shouldNotConfigureBluetoothInterface()) {
682 // Interface was already configured elsewhere, only start DHCP.
markchienc9daba32020-02-12 00:19:21 +0800683 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
684 }
685
686 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
687
markchien12c5bb82020-01-07 14:43:17 +0800688 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800689 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900690 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200691 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
692 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900693 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800694 // It is unclear whether the Bluetooth or USB stacks will manage their own
695 // state.
696 setIfaceUp = null;
697 } else {
698 setIfaceUp = enabled;
699 }
700 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
701 mLog.e("Error configuring interface");
702 if (!enabled) stopDhcp();
703 return false;
704 }
markchien74a4fa92019-09-09 20:50:49 +0800705
markchien74a4fa92019-09-09 20:50:49 +0800706 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800707 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900708 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800709 } else {
markchien12c5bb82020-01-07 14:43:17 +0800710 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900711 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800712 }
markchien245352e2020-02-27 20:27:18 +0800713 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800714 }
715
markchien69681d62021-11-15 23:58:05 +0800716 private boolean shouldNotConfigureBluetoothInterface() {
717 // Before T, bluetooth tethering configures the interface elsewhere.
718 return (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) && !SdkLevel.isAtLeastT();
719 }
720
Mark49649c92023-03-15 06:45:04 +0000721 private LinkAddress requestIpv4Address(final int scope, final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800722 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800723
markchien69681d62021-11-15 23:58:05 +0800724 if (shouldNotConfigureBluetoothInterface()) return new LinkAddress(BLUETOOTH_IFACE_ADDR);
markchienc9daba32020-02-12 00:19:21 +0800725
Mark49649c92023-03-15 06:45:04 +0000726 return mPrivateAddressCoordinator.requestDownstreamAddress(this, scope, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900727 }
728
markchien74a4fa92019-09-09 20:50:49 +0800729 private boolean startIPv6() {
730 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
731 if (mInterfaceParams == null) {
732 mLog.e("Failed to find InterfaceParams");
733 stopIPv6();
734 return false;
735 }
736
737 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
738 if (!mRaDaemon.start()) {
739 stopIPv6();
740 return false;
741 }
742
markchien932df542021-08-12 13:56:43 +0800743 if (SdkLevel.isAtLeastS()) {
Tyler Wear90e40632020-03-13 11:38:38 -0700744 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
745 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
746 }
747
markchien74a4fa92019-09-09 20:50:49 +0800748 return true;
749 }
750
751 private void stopIPv6() {
752 mInterfaceParams = null;
753 setRaParams(null);
754
755 if (mRaDaemon != null) {
756 mRaDaemon.stop();
757 mRaDaemon = null;
758 }
Tyler Wear90e40632020-03-13 11:38:38 -0700759
760 if (mDadProxy != null) {
761 mDadProxy.stop();
762 mDadProxy = null;
763 }
markchien74a4fa92019-09-09 20:50:49 +0800764 }
765
766 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
767 // LinkProperties. These have extraneous data filtered out and only the
768 // necessary prefixes included (per its prefix distribution policy).
769 //
770 // TODO: Evaluate using a data structure than is more directly suited to
771 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800772 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800773 if (mRaDaemon == null) return;
774
775 // Avoid unnecessary work on spurious updates.
776 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
777 return;
778 }
779
780 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700781 String upstreamIface = null;
782 InterfaceParams upstreamIfaceParams = null;
KH Shi701c3ca2023-08-16 13:19:33 +0000783 int upstreamIfIndex = NO_UPSTREAM;
markchien74a4fa92019-09-09 20:50:49 +0800784
785 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700786 upstreamIface = v6only.getInterfaceName();
787 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
788 if (upstreamIfaceParams != null) {
789 upstreamIfIndex = upstreamIfaceParams.index;
790 }
markchien74a4fa92019-09-09 20:50:49 +0800791 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700792 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800793 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
794
markchiend63c4f32020-05-21 17:38:28 +0800795 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800796
KH Shi3f738fc2023-05-23 22:37:17 +0800797 params.prefixes = getTetherableIpv6Prefixes(v6only);
798 for (IpPrefix prefix : params.prefixes) {
markchien74a4fa92019-09-09 20:50:49 +0800799 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
800 if (dnsServer != null) {
801 params.dnses.add(dnsServer);
802 }
803 }
804 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900805
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900806 // Add upstream index to name mapping. See the comment of the interface mapping update in
807 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
808 // timing issue. It prevents that the IPv6 capability is updated later than
809 // CMD_TETHER_CONNECTION_CHANGED.
KH Shi701c3ca2023-08-16 13:19:33 +0000810 mBpfCoordinator.maybeAddUpstreamToLookupTable(upstreamIfIndex, upstreamIface);
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900811
markchien74a4fa92019-09-09 20:50:49 +0800812 // If v6only is null, we pass in null to setRaParams(), which handles
813 // deprecation of any existing RA data.
markchien74a4fa92019-09-09 20:50:49 +0800814 setRaParams(params);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900815
KH Shi68770342023-08-17 14:34:31 +0000816 // Not support BPF on virtual upstream interface
817 final boolean upstreamSupportsBpf = upstreamIface != null && !isVcnInterface(upstreamIface);
KH Shi3f738fc2023-05-23 22:37:17 +0800818 final Set<IpPrefix> upstreamPrefixes = params != null ? params.prefixes : Set.of();
819 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamPrefixes,
820 upstreamIfIndex, upstreamPrefixes, upstreamSupportsBpf);
KH Shi68770342023-08-17 14:34:31 +0000821 mLastIPv6LinkProperties = v6only;
Tyler Wear90e40632020-03-13 11:38:38 -0700822 mLastIPv6UpstreamIfindex = upstreamIfIndex;
KH Shi3f738fc2023-05-23 22:37:17 +0800823 mLastIPv6UpstreamPrefixes = upstreamPrefixes;
KH Shi68770342023-08-17 14:34:31 +0000824 mUpstreamSupportsBpf = upstreamSupportsBpf;
Tyler Wear90e40632020-03-13 11:38:38 -0700825 if (mDadProxy != null) {
826 mDadProxy.setUpstreamIface(upstreamIfaceParams);
827 }
markchien74a4fa92019-09-09 20:50:49 +0800828 }
829
Xiao Ma4455d6b2020-04-09 10:13:44 +0900830 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900831 final int removalFailures = NetdUtils.removeRoutesFromLocalNetwork(
Xiao Ma4455d6b2020-04-09 10:13:44 +0900832 mNetd, toBeRemoved);
833 if (removalFailures > 0) {
834 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
835 removalFailures));
836 }
837
838 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
839 }
840
Chalard Jean2fb66f12023-08-25 12:50:37 +0900841 private void addInterfaceToNetwork(final int netId, @NonNull final String ifaceName) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900842 try {
Motomu Utsumiac7c5722023-11-15 11:51:42 +0900843 if (SdkLevel.isAtLeastS() && null != mRoutingCoordinator.value) {
Chalard Jean2fb66f12023-08-25 12:50:37 +0900844 // TODO : remove this call in favor of using the LocalNetworkConfiguration
845 // correctly, which will let ConnectivityService do it automatically.
846 mRoutingCoordinator.value.addInterfaceToNetwork(netId, ifaceName);
847 } else {
848 mNetd.networkAddInterface(netId, ifaceName);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900849 }
850 } catch (ServiceSpecificException | RemoteException e) {
851 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
Chalard Jean820ce9d2023-10-06 18:31:08 +0900852 }
853 }
854
855 private void addInterfaceForward(@NonNull final String fromIface,
856 @NonNull final String toIface) throws ServiceSpecificException, RemoteException {
Motomu Utsumiac7c5722023-11-15 11:51:42 +0900857 if (SdkLevel.isAtLeastS() && null != mRoutingCoordinator.value) {
Chalard Jean820ce9d2023-10-06 18:31:08 +0900858 mRoutingCoordinator.value.addInterfaceForward(fromIface, toIface);
859 } else {
860 mNetd.tetherAddForward(fromIface, toIface);
861 mNetd.ipfwdAddInterfaceForward(fromIface, toIface);
862 }
863 }
864
865 private void removeInterfaceForward(@NonNull final String fromIface,
866 @NonNull final String toIface) {
Motomu Utsumiac7c5722023-11-15 11:51:42 +0900867 if (SdkLevel.isAtLeastS() && null != mRoutingCoordinator.value) {
Chalard Jean820ce9d2023-10-06 18:31:08 +0900868 try {
869 mRoutingCoordinator.value.removeInterfaceForward(fromIface, toIface);
870 } catch (ServiceSpecificException e) {
871 mLog.e("Exception in removeInterfaceForward", e);
872 }
873 } else {
874 try {
875 mNetd.ipfwdRemoveInterfaceForward(fromIface, toIface);
876 } catch (RemoteException | ServiceSpecificException e) {
877 mLog.e("Exception in ipfwdRemoveInterfaceForward", e);
878 }
879 try {
880 mNetd.tetherRemoveForward(fromIface, toIface);
881 } catch (RemoteException | ServiceSpecificException e) {
882 mLog.e("Exception in disableNat", e);
883 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900884 }
Chalard Jean2fb66f12023-08-25 12:50:37 +0900885 }
886
887 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
888 // It's safe to call addInterfaceToNetwork() even if
889 // the interface is already in the local_network.
890 addInterfaceToNetwork(INetd.LOCAL_NET_ID, mIfaceName);
891 try {
892 // Add routes from local network. Note that adding routes that
893 // already exist does not cause an error (EEXIST is silently ignored).
894 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
895 } catch (IllegalStateException e) {
896 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
897 return;
898 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900899
900 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
901 }
902
markchien74a4fa92019-09-09 20:50:49 +0800903 private void configureLocalIPv6Routes(
KH Shiff1400b2023-11-08 14:50:15 +0000904 ArraySet<IpPrefix> deprecatedPrefixes, ArraySet<IpPrefix> newPrefixes) {
markchien74a4fa92019-09-09 20:50:49 +0800905 // [1] Remove the routes that are deprecated.
906 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900907 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800908 }
909
910 // [2] Add only the routes that have not previously been added.
911 if (newPrefixes != null && !newPrefixes.isEmpty()) {
KH Shiff1400b2023-11-08 14:50:15 +0000912 ArraySet<IpPrefix> addedPrefixes = new ArraySet<IpPrefix>(newPrefixes);
markchien74a4fa92019-09-09 20:50:49 +0800913 if (mLastRaParams != null) {
914 addedPrefixes.removeAll(mLastRaParams.prefixes);
915 }
916
917 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900918 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800919 }
920 }
921 }
922
923 private void configureLocalIPv6Dns(
KH Shiff1400b2023-11-08 14:50:15 +0000924 ArraySet<Inet6Address> deprecatedDnses, ArraySet<Inet6Address> newDnses) {
markchien74a4fa92019-09-09 20:50:49 +0800925 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
926 if (mNetd == null) {
927 if (newDnses != null) newDnses.clear();
928 mLog.e("No netd service instance available; not setting local IPv6 addresses");
929 return;
930 }
931
932 // [1] Remove deprecated local DNS IP addresses.
933 if (!deprecatedDnses.isEmpty()) {
934 for (Inet6Address dns : deprecatedDnses) {
935 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
936 mLog.e("Failed to remove local dns IP " + dns);
937 }
938
939 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
940 }
941 }
942
943 // [2] Add only the local DNS IP addresses that have not previously been added.
944 if (newDnses != null && !newDnses.isEmpty()) {
KH Shiff1400b2023-11-08 14:50:15 +0000945 final ArraySet<Inet6Address> addedDnses = new ArraySet<Inet6Address>(newDnses);
markchien74a4fa92019-09-09 20:50:49 +0800946 if (mLastRaParams != null) {
947 addedDnses.removeAll(mLastRaParams.dnses);
948 }
949
950 for (Inet6Address dns : addedDnses) {
951 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
952 mLog.e("Failed to add local dns IP " + dns);
953 newDnses.remove(dns);
954 }
955
956 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
957 }
958 }
959
960 try {
961 mNetd.tetherApplyDnsInterfaces();
962 } catch (ServiceSpecificException | RemoteException e) {
963 mLog.e("Failed to update local DNS caching server");
964 if (newDnses != null) newDnses.clear();
965 }
966 }
967
KH Shi701c3ca2023-08-16 13:19:33 +0000968 private int getInterfaceIndexForRule(int ifindex, boolean supportsBpf) {
969 return supportsBpf ? ifindex : NO_UPSTREAM;
970 }
971
KH Shi3f738fc2023-05-23 22:37:17 +0800972 // Handles updates to IPv6 forwarding rules if the upstream or its prefixes change.
973 private void updateIpv6ForwardingRules(int prevUpstreamIfindex,
974 @NonNull Set<IpPrefix> prevUpstreamPrefixes, int upstreamIfindex,
975 @NonNull Set<IpPrefix> upstreamPrefixes, boolean upstreamSupportsBpf) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900976 // If the upstream interface has changed, remove all rules and re-add them with the new
KH Shi701c3ca2023-08-16 13:19:33 +0000977 // upstream interface. If upstream is a virtual network, treated as no upstream.
KH Shi3f738fc2023-05-23 22:37:17 +0800978 if (prevUpstreamIfindex != upstreamIfindex
979 || !prevUpstreamPrefixes.equals(upstreamPrefixes)) {
KH Shi701c3ca2023-08-16 13:19:33 +0000980 mBpfCoordinator.updateAllIpv6Rules(this, this.mInterfaceParams,
KH Shi3f738fc2023-05-23 22:37:17 +0800981 getInterfaceIndexForRule(upstreamIfindex, upstreamSupportsBpf),
982 upstreamPrefixes);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900983 }
KH Shi701c3ca2023-08-16 13:19:33 +0000984 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900985
KH Shi701c3ca2023-08-16 13:19:33 +0000986 // Handles updates to IPv6 downstream rules if a neighbor event is received.
987 private void addOrRemoveIpv6Downstream(NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900988 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900989 if (e == null) return;
990 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
991 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
992 return;
993 }
994
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900995 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
KH Shi59ad35e2023-08-15 07:13:00 +0000996 // Do this here instead of in the Ipv6DownstreamRule constructor to ensure that we
997 // never add rules with a null MAC, only delete them.
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900998 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
KH Shi701c3ca2023-08-16 13:19:33 +0000999 Ipv6DownstreamRule rule = new Ipv6DownstreamRule(
1000 getInterfaceIndexForRule(mLastIPv6UpstreamIfindex, mUpstreamSupportsBpf),
1001 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001002 if (e.isValid()) {
KH Shie4d549a2023-08-28 09:57:34 +00001003 mBpfCoordinator.addIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001004 } else {
KH Shie4d549a2023-08-28 09:57:34 +00001005 mBpfCoordinator.removeIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001006 }
1007 }
1008
Hungming Chend71c06e2020-12-21 19:39:49 +08001009 // TODO: consider moving into BpfCoordinator.
1010 private void updateClientInfoIpv4(NeighborEvent e) {
Hungming Chend71c06e2020-12-21 19:39:49 +08001011 if (e == null) return;
1012 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
1013 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
1014 return;
1015 }
1016
1017 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
1018 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
1019 // IpServer never add clients with a null MAC, only delete them.
1020 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
1021 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
1022 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
1023 if (e.isValid()) {
1024 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
1025 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +08001026 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
1027 }
1028 }
1029
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001030 private void handleNeighborEvent(NeighborEvent e) {
1031 if (mInterfaceParams != null
1032 && mInterfaceParams.index == e.ifindex
1033 && mInterfaceParams.hasMacAddress) {
KH Shi701c3ca2023-08-16 13:19:33 +00001034 addOrRemoveIpv6Downstream(e);
Hungming Chend71c06e2020-12-21 19:39:49 +08001035 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001036 }
1037 }
1038
markchiend63c4f32020-05-21 17:38:28 +08001039 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001040 try {
1041 int upstreamHopLimit = Integer.parseUnsignedInt(
1042 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001043 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001044 // Cap the hop limit to 255.
1045 return (byte) Integer.min(upstreamHopLimit, 255);
1046 } catch (Exception e) {
1047 mLog.e("Failed to find upstream interface hop limit", e);
1048 }
1049 return RaParams.DEFAULT_HOPLIMIT;
1050 }
1051
1052 private void setRaParams(RaParams newParams) {
1053 if (mRaDaemon != null) {
1054 final RaParams deprecatedParams =
1055 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1056
1057 configureLocalIPv6Routes(deprecatedParams.prefixes,
1058 (newParams != null) ? newParams.prefixes : null);
1059
1060 configureLocalIPv6Dns(deprecatedParams.dnses,
1061 (newParams != null) ? newParams.dnses : null);
1062
1063 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1064 }
1065
1066 mLastRaParams = newParams;
1067 }
1068
markchien21021ef2021-06-01 10:58:04 +08001069 private void maybeLogMessage(State state, int what) {
1070 switch (what) {
1071 // Suppress some CMD_* to avoid log flooding.
1072 case CMD_IPV6_TETHER_UPDATE:
1073 case CMD_NEIGHBOR_EVENT:
1074 break;
1075 default:
1076 mLog.log(state.getName() + " got "
1077 + sMagicDecoderRing.get(what, Integer.toString(what)));
1078 }
markchien74a4fa92019-09-09 20:50:49 +08001079 }
1080
1081 private void sendInterfaceState(int newInterfaceState) {
1082 mServingMode = newInterfaceState;
1083 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1084 sendLinkProperties();
1085 }
1086
1087 private void sendLinkProperties() {
1088 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1089 }
1090
1091 private void resetLinkProperties() {
1092 mLinkProperties.clear();
1093 mLinkProperties.setInterfaceName(mIfaceName);
1094 }
1095
markchienf053e4b2020-03-16 21:49:48 +08001096 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001097 // Ignore static address configuration if they are invalid or null. In theory, static
1098 // addresses should not be invalid here because TetheringManager do not allow caller to
1099 // specify invalid static address configuration.
1100 if (request == null || request.localIPv4Address == null
1101 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1102 request.localIPv4Address, request.staticClientAddress)) {
1103 return;
1104 }
markchienf053e4b2020-03-16 21:49:48 +08001105
1106 mStaticIpv4ServerAddr = request.localIPv4Address;
1107 mStaticIpv4ClientAddr = request.staticClientAddress;
1108 }
1109
markchien74a4fa92019-09-09 20:50:49 +08001110 class InitialState extends State {
1111 @Override
1112 public void enter() {
1113 sendInterfaceState(STATE_AVAILABLE);
1114 }
1115
1116 @Override
1117 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001118 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001119 switch (message.what) {
1120 case CMD_TETHER_REQUESTED:
Mark74461fc2022-12-14 08:49:40 +00001121 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001122 switch (message.arg1) {
1123 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001124 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001125 transitionTo(mLocalHotspotState);
1126 break;
1127 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001128 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001129 transitionTo(mTetheredState);
1130 break;
1131 default:
1132 mLog.e("Invalid tethering interface serving state specified.");
1133 }
1134 break;
1135 case CMD_INTERFACE_DOWN:
1136 transitionTo(mUnavailableState);
1137 break;
markchien74a4fa92019-09-09 20:50:49 +08001138 default:
1139 return NOT_HANDLED;
1140 }
1141 return HANDLED;
1142 }
1143 }
1144
Hungming Chen46c30b12020-10-15 17:25:36 +08001145 private void startConntrackMonitoring() {
1146 mBpfCoordinator.startMonitoring(this);
1147 }
1148
1149 private void stopConntrackMonitoring() {
1150 mBpfCoordinator.stopMonitoring(this);
1151 }
1152
Mark3ec851e2023-05-19 08:50:38 +00001153 abstract class BaseServingState extends State {
1154 private final int mDesiredInterfaceState;
1155
1156 BaseServingState(int interfaceState) {
1157 mDesiredInterfaceState = interfaceState;
1158 }
1159
markchien74a4fa92019-09-09 20:50:49 +08001160 @Override
1161 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001162 startConntrackMonitoring();
1163
Mark3ec851e2023-05-19 08:50:38 +00001164 startServingInterface();
1165
1166 if (mLastError != TETHER_ERROR_NO_ERROR) {
Mark50eef832023-09-19 06:56:14 +00001167 // This will transition to InitialState right away, regardless of whether any
1168 // message is already waiting in the StateMachine queue (including maybe some
1169 // message to go to InitialState). InitialState will then process any pending
1170 // message (and generally ignores them). It is difficult to know for sure whether
1171 // this is correct in all cases, but this is equivalent to what IpServer was doing
1172 // in previous versions of the mainline module.
Markbe99f862022-12-21 16:39:23 +00001173 // TODO : remove sendMessageAtFrontOfQueueToAsyncSM after migrating to the Sync
1174 // StateMachine.
Markcf11be92023-12-05 08:19:15 +00001175 if (mIsSyncSM) {
Markbe99f862022-12-21 16:39:23 +00001176 sendSelfMessageToSyncSM(CMD_SERVICE_FAILED_TO_START, mLastError);
1177 } else {
1178 sendMessageAtFrontOfQueueToAsyncSM(CMD_SERVICE_FAILED_TO_START, mLastError);
1179 }
Mark3ec851e2023-05-19 08:50:38 +00001180 }
1181
1182 if (DBG) Log.d(TAG, getStateString(mDesiredInterfaceState) + " serve " + mIfaceName);
1183 sendInterfaceState(mDesiredInterfaceState);
1184 }
1185
Mark49649c92023-03-15 06:45:04 +00001186 private int getScope() {
1187 if (mDesiredInterfaceState == STATE_TETHERED) {
1188 return CONNECTIVITY_SCOPE_GLOBAL;
1189 }
1190
1191 return CONNECTIVITY_SCOPE_LOCAL;
1192 }
1193
Mark3ec851e2023-05-19 08:50:38 +00001194 private void startServingInterface() {
Mark49649c92023-03-15 06:45:04 +00001195 if (!startIPv4(getScope())) {
Mark74461fc2022-12-14 08:49:40 +00001196 mLastError = TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001197 return;
1198 }
1199
1200 try {
markchienc9daba32020-02-12 00:19:21 +08001201 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001202 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001203 mLog.e("Error Tethering", e);
Mark74461fc2022-12-14 08:49:40 +00001204 mLastError = TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001205 return;
1206 }
1207
1208 if (!startIPv6()) {
1209 mLog.e("Failed to startIPv6");
1210 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1211 return;
1212 }
1213 }
1214
1215 @Override
1216 public void exit() {
1217 // Note that at this point, we're leaving the tethered state. We can fail any
1218 // of these operations, but it doesn't really change that we have to try them
1219 // all in sequence.
1220 stopIPv6();
1221
1222 try {
markchien12c5bb82020-01-07 14:43:17 +08001223 NetdUtils.untetherInterface(mNetd, mIfaceName);
1224 } catch (RemoteException | ServiceSpecificException e) {
Mark74461fc2022-12-14 08:49:40 +00001225 mLastError = TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001226 mLog.e("Failed to untether interface: " + e);
1227 }
1228
1229 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001230 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001231
1232 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001233
1234 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1235 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001236 }
1237
1238 @Override
1239 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001240 switch (message.what) {
1241 case CMD_TETHER_UNREQUESTED:
1242 transitionTo(mInitialState);
1243 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1244 break;
1245 case CMD_INTERFACE_DOWN:
1246 transitionTo(mUnavailableState);
1247 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1248 break;
1249 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001250 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001251 sendLinkProperties();
1252 break;
1253 case CMD_IP_FORWARDING_ENABLE_ERROR:
1254 case CMD_IP_FORWARDING_DISABLE_ERROR:
1255 case CMD_START_TETHERING_ERROR:
1256 case CMD_STOP_TETHERING_ERROR:
1257 case CMD_SET_DNS_FORWARDERS_ERROR:
Mark74461fc2022-12-14 08:49:40 +00001258 mLastError = TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001259 transitionTo(mInitialState);
1260 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001261 case CMD_NEW_PREFIX_REQUEST:
1262 handleNewPrefixRequest((IpPrefix) message.obj);
1263 break;
markchienc9daba32020-02-12 00:19:21 +08001264 case CMD_NOTIFY_PREFIX_CONFLICT:
1265 mLog.i("restart tethering: " + mInterfaceType);
1266 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1267 transitionTo(mWaitingForRestartState);
1268 break;
Mark50eef832023-09-19 06:56:14 +00001269 case CMD_SERVICE_FAILED_TO_START:
1270 mLog.e("start serving fail, error: " + message.arg1);
1271 transitionTo(mInitialState);
markchien74a4fa92019-09-09 20:50:49 +08001272 default:
1273 return false;
1274 }
1275 return true;
1276 }
Mark3ec851e2023-05-19 08:50:38 +00001277
1278 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
1279 if (!currentPrefix.contains(mIpv4Address.getAddress())
1280 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
1281 Log.e(TAG, "Invalid prefix: " + currentPrefix);
1282 return;
1283 }
1284
1285 final LinkAddress deprecatedLinkAddress = mIpv4Address;
Mark49649c92023-03-15 06:45:04 +00001286 mIpv4Address = requestIpv4Address(getScope(), false);
Mark3ec851e2023-05-19 08:50:38 +00001287 if (mIpv4Address == null) {
1288 mLog.e("Fail to request a new downstream prefix");
1289 return;
1290 }
1291 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
1292
1293 // Add new IPv4 address on the interface.
1294 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1295 mLog.e("Failed to add new IP " + srvAddr);
1296 return;
1297 }
1298
1299 // Remove deprecated routes from local network.
1300 removeRoutesFromLocalNetwork(
1301 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1302 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1303
1304 // Add new routes to local network.
1305 addRoutesToLocalNetwork(
1306 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1307 mLinkProperties.addLinkAddress(mIpv4Address);
1308
1309 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1310 // listen on the interface configured with new IPv4 address, that results DNS validation
1311 // failure of downstream client even if appropriate routes have been configured.
1312 try {
1313 mNetd.tetherApplyDnsInterfaces();
1314 } catch (ServiceSpecificException | RemoteException e) {
1315 mLog.e("Failed to update local DNS caching server");
1316 return;
1317 }
1318 sendLinkProperties();
1319
1320 // Notify DHCP server that new prefix/route has been applied on IpServer.
1321 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1322 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1323 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1324 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1325 try {
1326 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1327 @Override
1328 public void callback(int statusCode) {
1329 if (statusCode != STATUS_SUCCESS) {
1330 mLog.e("Error updating DHCP serving params: " + statusCode);
1331 }
1332 }
1333 });
1334 } catch (RemoteException e) {
1335 mLog.e("Error updating DHCP serving params", e);
1336 }
1337 }
markchien74a4fa92019-09-09 20:50:49 +08001338 }
1339
1340 // Handling errors in BaseServingState.enter() by transitioning is
1341 // problematic because transitioning during a multi-state jump yields
1342 // a Log.wtf(). Ultimately, there should be only one ServingState,
1343 // and forwarding and NAT rules should be handled by a coordinating
1344 // functional element outside of IpServer.
1345 class LocalHotspotState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001346 LocalHotspotState() {
1347 super(STATE_LOCAL_ONLY);
markchien74a4fa92019-09-09 20:50:49 +08001348 }
1349
1350 @Override
1351 public boolean processMessage(Message message) {
1352 if (super.processMessage(message)) return true;
1353
markchien21021ef2021-06-01 10:58:04 +08001354 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001355 switch (message.what) {
1356 case CMD_TETHER_REQUESTED:
1357 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1358 break;
1359 case CMD_TETHER_CONNECTION_CHANGED:
1360 // Ignored in local hotspot state.
1361 break;
1362 default:
1363 return false;
1364 }
1365 return true;
1366 }
1367 }
1368
1369 // Handling errors in BaseServingState.enter() by transitioning is
1370 // problematic because transitioning during a multi-state jump yields
1371 // a Log.wtf(). Ultimately, there should be only one ServingState,
1372 // and forwarding and NAT rules should be handled by a coordinating
1373 // functional element outside of IpServer.
1374 class TetheredState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001375 TetheredState() {
1376 super(STATE_TETHERED);
markchien74a4fa92019-09-09 20:50:49 +08001377 }
1378
1379 @Override
1380 public void exit() {
1381 cleanupUpstream();
KH Shi701c3ca2023-08-16 13:19:33 +00001382 mBpfCoordinator.clearAllIpv6Rules(IpServer.this);
markchien74a4fa92019-09-09 20:50:49 +08001383 super.exit();
1384 }
1385
Hungming Chena6e78692021-02-08 17:15:35 +08001386 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1387 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1388 // and behaviour. While upstream is switching from offload supported interface to
1389 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1390 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1391 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1392 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1393 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1394 // in the state machine. Once there is any case out whish is not covered by previous cases,
1395 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001396 private void cleanupUpstream() {
1397 if (mUpstreamIfaceSet == null) return;
1398
1399 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1400 mUpstreamIfaceSet = null;
KH Shi701c3ca2023-08-16 13:19:33 +00001401 mBpfCoordinator.updateAllIpv6Rules(
KH Shi3f738fc2023-05-23 22:37:17 +08001402 IpServer.this, IpServer.this.mInterfaceParams, NO_UPSTREAM, Set.of());
markchien74a4fa92019-09-09 20:50:49 +08001403 }
1404
1405 private void cleanupUpstreamInterface(String upstreamIface) {
1406 // Note that we don't care about errors here.
1407 // Sometimes interfaces are gone before we get
1408 // to remove their rules, which generates errors.
1409 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001410 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
Chalard Jean820ce9d2023-10-06 18:31:08 +09001411 removeInterfaceForward(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001412 }
1413
1414 @Override
1415 public boolean processMessage(Message message) {
1416 if (super.processMessage(message)) return true;
1417
markchien21021ef2021-06-01 10:58:04 +08001418 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001419 switch (message.what) {
1420 case CMD_TETHER_REQUESTED:
1421 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1422 break;
1423 case CMD_TETHER_CONNECTION_CHANGED:
1424 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1425 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1426 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1427 break;
1428 }
1429
1430 if (newUpstreamIfaceSet == null) {
1431 cleanupUpstream();
1432 break;
1433 }
1434
1435 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1436 cleanupUpstreamInterface(removed);
1437 }
1438
1439 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1440 // This makes the call to cleanupUpstream() in the error
1441 // path for any interface neatly cleanup all the interfaces.
1442 mUpstreamIfaceSet = newUpstreamIfaceSet;
1443
1444 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001445 // Add upstream index to name mapping for the tether stats usage in the
1446 // coordinator. Although this mapping could be added by both class
1447 // Tethering and IpServer, adding mapping from IpServer guarantees that
1448 // the mapping is added before adding forwarding rules. That is because
1449 // there are different state machines in both classes. It is hard to
1450 // guarantee the link property update order between multiple state machines.
1451 // Note that both IPv4 and IPv6 interface may be added because
1452 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1453 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1454 // capability may be updated later. In that case, IPv6 interface mapping is
1455 // updated in updateUpstreamIPv6LinkProperties.
1456 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1457 final InterfaceParams upstreamIfaceParams =
1458 mDeps.getInterfaceParams(ifname);
1459 if (upstreamIfaceParams != null) {
KH Shi701c3ca2023-08-16 13:19:33 +00001460 mBpfCoordinator.maybeAddUpstreamToLookupTable(
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001461 upstreamIfaceParams.index, ifname);
1462 }
1463 }
1464
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001465 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001466 try {
Chalard Jean820ce9d2023-10-06 18:31:08 +09001467 addInterfaceForward(mIfaceName, ifname);
markchien12c5bb82020-01-07 14:43:17 +08001468 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean820ce9d2023-10-06 18:31:08 +09001469 mLog.e("Exception enabling iface forward", e);
markchien74a4fa92019-09-09 20:50:49 +08001470 cleanupUpstream();
Mark74461fc2022-12-14 08:49:40 +00001471 mLastError = TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001472 transitionTo(mInitialState);
1473 return true;
1474 }
1475 }
1476 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001477 case CMD_NEIGHBOR_EVENT:
1478 handleNeighborEvent((NeighborEvent) message.obj);
1479 break;
markchien74a4fa92019-09-09 20:50:49 +08001480 default:
1481 return false;
1482 }
1483 return true;
1484 }
1485
1486 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1487 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1488 if (mUpstreamIfaceSet != null && newIfaces != null) {
1489 return mUpstreamIfaceSet.equals(newIfaces);
1490 }
1491 return false;
1492 }
1493
1494 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1495 if (mUpstreamIfaceSet == null) return new HashSet<>();
1496
1497 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1498 removed.removeAll(newIfaces.ifnames);
1499 return removed;
1500 }
1501
1502 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1503 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1504 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1505 return added;
1506 }
1507 }
1508
1509 /**
1510 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001511 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001512 * specific state machine from its list of possible recipients of
1513 * tethering requests. The state machine itself will hang around until
1514 * the garbage collector finds it.
1515 */
1516 class UnavailableState extends State {
1517 @Override
1518 public void enter() {
KH Shi701c3ca2023-08-16 13:19:33 +00001519 // TODO: move mIpNeighborMonitor.stop() to TetheredState#exit, and trigger a neighbours
1520 // dump after starting mIpNeighborMonitor.
h.zhangd244bd02020-06-14 14:46:54 +08001521 mIpNeighborMonitor.stop();
Mark74461fc2022-12-14 08:49:40 +00001522 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001523 sendInterfaceState(STATE_UNAVAILABLE);
1524 }
1525 }
1526
markchienc9daba32020-02-12 00:19:21 +08001527 class WaitingForRestartState extends State {
1528 @Override
1529 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001530 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001531 switch (message.what) {
1532 case CMD_TETHER_UNREQUESTED:
1533 transitionTo(mInitialState);
1534 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1535 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1536 break;
1537 case CMD_INTERFACE_DOWN:
1538 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001539 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001540 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1541 break;
1542 default:
1543 return false;
1544 }
1545 return true;
1546 }
1547 }
1548
markchien74a4fa92019-09-09 20:50:49 +08001549 // Accumulate routes representing "prefixes to be assigned to the local
1550 // interface", for subsequent modification of local_network routing.
1551 private static ArrayList<RouteInfo> getLocalRoutesFor(
KH Shiff1400b2023-11-08 14:50:15 +00001552 String ifname, ArraySet<IpPrefix> prefixes) {
markchien74a4fa92019-09-09 20:50:49 +08001553 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1554 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001555 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001556 }
1557 return localRoutes;
1558 }
1559
1560 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1561 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1562 final byte[] dnsBytes = localPrefix.getRawAddress();
1563 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1564 try {
1565 return Inet6Address.getByAddress(null, dnsBytes, 0);
1566 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001567 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001568 return null;
1569 }
1570 }
1571
1572 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1573 final byte random = (byte) (new Random()).nextInt();
1574 for (int value : excluded) {
1575 if (random == value) return dflt;
1576 }
1577 return random;
1578 }
KH Shi3f738fc2023-05-23 22:37:17 +08001579
1580 /** Get IPv6 prefixes from LinkProperties */
1581 @NonNull
1582 @VisibleForTesting
KH Shiff1400b2023-11-08 14:50:15 +00001583 static ArraySet<IpPrefix> getTetherableIpv6Prefixes(@NonNull Collection<LinkAddress> addrs) {
1584 final ArraySet<IpPrefix> prefixes = new ArraySet<>();
KH Shi3f738fc2023-05-23 22:37:17 +08001585 for (LinkAddress linkAddr : addrs) {
1586 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
1587 prefixes.add(new IpPrefix(linkAddr.getAddress(), RFC7421_PREFIX_LENGTH));
1588 }
1589 return prefixes;
1590 }
1591
1592 @NonNull
KH Shiff1400b2023-11-08 14:50:15 +00001593 private ArraySet<IpPrefix> getTetherableIpv6Prefixes(@NonNull LinkProperties lp) {
KH Shi3f738fc2023-05-23 22:37:17 +08001594 return getTetherableIpv6Prefixes(lp.getLinkAddresses());
1595 }
markchien74a4fa92019-09-09 20:50:49 +08001596}