blob: 2a25a86f34c49f2fd1b2c53107204b541607c749 [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.Looper;
60import 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;
71import com.android.internal.util.StateMachine;
markchien932df542021-08-12 13:56:43 +080072import com.android.modules.utils.build.SdkLevel;
Patrick Rohr9f371f02022-03-04 15:14:27 +010073import com.android.net.module.util.InterfaceParams;
Chalard Jeanadcec9e2021-10-29 15:57:22 +090074import com.android.net.module.util.NetdUtils;
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;
markchien74a4fa92019-09-09 20:50:49 +080088
89import java.net.Inet4Address;
90import java.net.Inet6Address;
markchien74a4fa92019-09-09 20:50:49 +080091import java.net.UnknownHostException;
92import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090093import java.util.Arrays;
94import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080095import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090096import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080097import java.util.Objects;
98import java.util.Random;
99import java.util.Set;
100
101/**
102 * Provides the interface to IP-layer serving functionality for a given network
103 * interface, e.g. for tethering or "local-only hotspot" mode.
104 *
105 * @hide
106 */
107public class IpServer extends StateMachine {
108 public static final int STATE_UNAVAILABLE = 0;
109 public static final int STATE_AVAILABLE = 1;
110 public static final int STATE_TETHERED = 2;
111 public static final int STATE_LOCAL_ONLY = 3;
112
113 /** Get string name of |state|.*/
114 public static String getStateString(int state) {
115 switch (state) {
116 case STATE_UNAVAILABLE: return "UNAVAILABLE";
117 case STATE_AVAILABLE: return "AVAILABLE";
118 case STATE_TETHERED: return "TETHERED";
119 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
120 }
121 return "UNKNOWN: " + state;
122 }
123
124 private static final byte DOUG_ADAMS = (byte) 42;
125
markchien74a4fa92019-09-09 20:50:49 +0800126 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800127 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800128
129 // TODO: have this configurable
130 private static final int DHCP_LEASE_TIME_SECS = 3600;
131
KH Shi701c3ca2023-08-16 13:19:33 +0000132 private static final int NO_UPSTREAM = 0;
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900133 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
134
markchien74a4fa92019-09-09 20:50:49 +0800135 private static final String TAG = "IpServer";
136 private static final boolean DBG = false;
137 private static final boolean VDBG = false;
138 private static final Class[] sMessageClasses = {
139 IpServer.class
140 };
141 private static final SparseArray<String> sMagicDecoderRing =
142 MessageUtils.findMessageNames(sMessageClasses);
143
144 /** IpServer callback. */
145 public static class Callback {
146 /**
147 * Notify that |who| has changed its tethering state.
148 *
149 * @param who the calling instance of IpServer
150 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800151 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800152 */
markchien9d353822019-12-16 20:15:20 +0800153 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800154
155 /**
156 * Notify that |who| has new LinkProperties.
157 *
158 * @param who the calling instance of IpServer
159 * @param newLp the new LinkProperties to report
160 */
markchien9d353822019-12-16 20:15:20 +0800161 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900162
163 /**
164 * Notify that the DHCP leases changed in one of the IpServers.
165 */
166 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800167
168 /**
169 * Request Tethering change.
170 *
171 * @param tetheringType the downstream type of this IpServer.
172 * @param enabled enable or disable tethering.
173 */
174 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800175 }
176
177 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800178 public abstract static class Dependencies {
Tyler Wear90e40632020-03-13 11:38:38 -0700179 /**
180 * Create a DadProxy instance to be used by IpServer.
181 * To support multiple tethered interfaces concurrently DAD Proxy
182 * needs to be supported per IpServer instead of per upstream.
183 */
184 public DadProxy getDadProxy(Handler handler, InterfaceParams ifParams) {
185 return new DadProxy(handler, ifParams);
186 }
187
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900188 /** Create an IpNeighborMonitor to be used by this IpServer */
189 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
190 IpNeighborMonitor.NeighborEventConsumer consumer) {
191 return new IpNeighborMonitor(handler, log, consumer);
192 }
193
markchien74a4fa92019-09-09 20:50:49 +0800194 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
195 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
196 return new RouterAdvertisementDaemon(ifParams);
197 }
198
199 /** Get |ifName|'s interface information.*/
200 public InterfaceParams getInterfaceParams(String ifName) {
201 return InterfaceParams.getByName(ifName);
202 }
203
markchien9d353822019-12-16 20:15:20 +0800204 /** Create a DhcpServer instance to be used by IpServer. */
205 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
206 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800207 }
208
markchien74a4fa92019-09-09 20:50:49 +0800209 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800210 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800211 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800212 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800213 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800214 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800215 // notification from the {@link Tethering.TetherMainSM} that it had trouble enabling IP
216 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800217 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800218 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble disabling IP
219 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800220 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800221 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble starting
222 // tethering
markchien6cf0e552019-12-06 15:24:53 +0800223 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800224 // notification from the {@link Tethering.TetherMainSM} that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800225 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800226 // notification from the {@link Tethering.TetherMainSM} that it had trouble setting the DNS
227 // forwarders
markchien6cf0e552019-12-06 15:24:53 +0800228 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800229 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800230 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800231 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800232 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900233 // new neighbor cache entry on our interface
234 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900235 // request from DHCP server that it wants to have a new prefix
236 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800237 // request from PrivateAddressCoordinator to restart tethering.
238 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
markchien74a4fa92019-09-09 20:50:49 +0800239
240 private final State mInitialState;
241 private final State mLocalHotspotState;
242 private final State mTetheredState;
243 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800244 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800245
246 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800247 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800248 @NonNull
249 private final BpfCoordinator mBpfCoordinator;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900250 // Contains null if the connectivity module is unsupported, as the routing coordinator is not
251 // available. Must use LateSdk because MessageUtils enumerates fields in this class, so it
252 // must be able to find all classes at runtime.
253 @NonNull
254 private final LateSdk<RoutingCoordinatorManager> mRoutingCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800255 private final Callback mCallback;
256 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800257 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800258
259 private final String mIfaceName;
260 private final int mInterfaceType;
261 private final LinkProperties mLinkProperties;
262 private final boolean mUsingLegacyDhcp;
markchienfb65dfe2022-02-25 23:14:58 +0800263 private final int mP2pLeasesSubnetPrefixLength;
markchien74a4fa92019-09-09 20:50:49 +0800264
265 private final Dependencies mDeps;
266
267 private int mLastError;
268 private int mServingMode;
269 private InterfaceSet mUpstreamIfaceSet; // may change over time
KH Shi701c3ca2023-08-16 13:19:33 +0000270 // mInterfaceParams can't be final now because IpServer will be created when receives
271 // WIFI_AP_STATE_CHANGED broadcasts or when it detects that the wifi interface has come up.
272 // In the latter case, the interface is not fully initialized and the MAC address might not
273 // be correct (it will be set with a randomized MAC address later).
274 // TODO: Consider create the IpServer only when tethering want to enable it, then we can
275 // make mInterfaceParams final.
markchien74a4fa92019-09-09 20:50:49 +0800276 private InterfaceParams mInterfaceParams;
277 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
278 // properties are those selected by the IPv6TetheringCoordinator and relayed
279 // to us. By comparison, mLinkProperties contains the addresses and directly
280 // connected routes that have been formed from these properties iff. we have
281 // succeeded in configuring them and are able to announce them within Router
282 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
283 private LinkProperties mLastIPv6LinkProperties;
284 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700285 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800286
287 // To be accessed only on the handler thread
288 private int mDhcpServerStartIndex = 0;
289 private IDhcpServer mDhcpServer;
290 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800291
292 private LinkAddress mStaticIpv4ServerAddr;
293 private LinkAddress mStaticIpv4ClientAddr;
294
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900295 @NonNull
296 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800297
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900298 private int mLastIPv6UpstreamIfindex = 0;
KH Shi68770342023-08-17 14:34:31 +0000299 private boolean mUpstreamSupportsBpf = false;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900300
301 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
302 public void accept(NeighborEvent e) {
303 sendMessage(CMD_NEIGHBOR_EVENT, e);
304 }
305 }
306
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900307 private final IpNeighborMonitor mIpNeighborMonitor;
308
markchienc9daba32020-02-12 00:19:21 +0800309 private LinkAddress mIpv4Address;
310
Wayne Ma6cd440f2022-03-14 18:04:33 +0800311 private final TetheringMetrics mTetheringMetrics;
312
Hungming Chen5bc3af92020-05-12 19:15:24 +0800313 // TODO: Add a dependency object to pass the data members or variables from the tethering
314 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800315 public IpServer(
316 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Chalard Jean2fb66f12023-08-25 12:50:37 +0900317 INetd netd, @NonNull BpfCoordinator bpfCoordinator,
318 @Nullable LateSdk<RoutingCoordinatorManager> routingCoordinator, Callback callback,
markchienb961d3d2022-02-26 00:39:06 +0800319 TetheringConfiguration config, PrivateAddressCoordinator addressCoordinator,
Wayne Ma6cd440f2022-03-14 18:04:33 +0800320 TetheringMetrics tetheringMetrics, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800321 super(ifaceName, looper);
322 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800323 mNetd = netd;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900324 mBpfCoordinator = bpfCoordinator;
325 mRoutingCoordinator = routingCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800326 mCallback = callback;
327 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
328 mIfaceName = ifaceName;
329 mInterfaceType = interfaceType;
330 mLinkProperties = new LinkProperties();
markchienb961d3d2022-02-26 00:39:06 +0800331 mUsingLegacyDhcp = config.useLegacyDhcpServer();
markchienfb65dfe2022-02-25 23:14:58 +0800332 mP2pLeasesSubnetPrefixLength = config.getP2pLeasesSubnetPrefixLength();
markchienc9daba32020-02-12 00:19:21 +0800333 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800334 mDeps = deps;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800335 mTetheringMetrics = tetheringMetrics;
markchien74a4fa92019-09-09 20:50:49 +0800336 resetLinkProperties();
Mark74461fc2022-12-14 08:49:40 +0000337 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800338 mServingMode = STATE_AVAILABLE;
339
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900340 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
341 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800342
KH Shie4d549a2023-08-28 09:57:34 +0000343 // IP neighbor monitor monitors the neighbor events for adding/removing IPv6 downstream rule
344 // per client. If BPF offload is not supported, don't start listening for neighbor events.
345 if (mBpfCoordinator.isUsingBpfOffload() && !mIpNeighborMonitor.start()) {
Hungming Chen5bc3af92020-05-12 19:15:24 +0800346 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900347 }
348
markchien74a4fa92019-09-09 20:50:49 +0800349 mInitialState = new InitialState();
350 mLocalHotspotState = new LocalHotspotState();
351 mTetheredState = new TetheredState();
352 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800353 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800354 addState(mInitialState);
355 addState(mLocalHotspotState);
356 addState(mTetheredState);
markchienc9daba32020-02-12 00:19:21 +0800357 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800358 addState(mUnavailableState);
359
360 setInitialState(mInitialState);
361 }
362
363 /** Interface name which IpServer served.*/
364 public String interfaceName() {
365 return mIfaceName;
366 }
367
368 /**
markchien9b4d7572019-12-25 19:40:32 +0800369 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800370 */
371 public int interfaceType() {
372 return mInterfaceType;
373 }
374
375 /** Last error from this IpServer. */
376 public int lastError() {
377 return mLastError;
378 }
379
380 /** Serving mode is the current state of IpServer state machine. */
381 public int servingMode() {
382 return mServingMode;
383 }
384
385 /** The properties of the network link which IpServer is serving. */
386 public LinkProperties linkProperties() {
387 return new LinkProperties(mLinkProperties);
388 }
389
markchienc9daba32020-02-12 00:19:21 +0800390 /** The address which IpServer is using. */
391 public LinkAddress getAddress() {
392 return mIpv4Address;
393 }
394
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900395 /**
396 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
397 * thread.
398 */
399 public List<TetheredClient> getAllLeases() {
400 return Collections.unmodifiableList(mDhcpLeases);
401 }
402
Marka5424582022-12-01 13:46:32 +0000403 /** Enable this IpServer. IpServer state machine will be tethered or localHotspot state. */
404 public void enable(final int requestedState, final TetheringRequestParcel request) {
405 sendMessage(CMD_TETHER_REQUESTED, requestedState, 0, request);
406 }
407
markchien74a4fa92019-09-09 20:50:49 +0800408 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
409 public void stop() {
410 sendMessage(CMD_INTERFACE_DOWN);
411 }
412
413 /**
414 * Tethering is canceled. IpServer state machine will be available and wait for
415 * next tethering request.
416 */
417 public void unwanted() {
418 sendMessage(CMD_TETHER_UNREQUESTED);
419 }
420
421 /** Internals. */
422
Mark49649c92023-03-15 06:45:04 +0000423 private boolean startIPv4(int scope) {
424 return configureIPv4(true, scope);
markchien74a4fa92019-09-09 20:50:49 +0800425 }
426
427 /**
428 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
429 * handler.
430 *
431 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
432 * with different implementations of the callback, to differentiate handling of success/error in
433 * each call.
434 */
435 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
436 @Override
437 public void onStatusAvailable(int statusCode) {
438 getHandler().post(() -> callback(statusCode));
439 }
440
441 public abstract void callback(int statusCode);
442
443 @Override
444 public int getInterfaceVersion() {
445 return this.VERSION;
446 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900447
448 @Override
449 public String getInterfaceHash() {
450 return this.HASH;
451 }
markchien74a4fa92019-09-09 20:50:49 +0800452 }
453
454 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
455 private final int mStartIndex;
456
457 private DhcpServerCallbacksImpl(int startIndex) {
458 mStartIndex = startIndex;
459 }
460
461 @Override
462 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
463 getHandler().post(() -> {
464 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
465 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800466 // This start request is obsolete. Explicitly stop the DHCP server to shut
467 // down its thread. When the |server| binder token goes out of scope, the
468 // garbage collector will finalize it, which causes the network stack process
469 // garbage collector to collect the server itself.
470 try {
471 server.stop(null);
472 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800473 return;
474 }
475
476 if (statusCode != STATUS_SUCCESS) {
477 mLog.e("Error obtaining DHCP server: " + statusCode);
478 handleError();
479 return;
480 }
481
482 mDhcpServer = server;
483 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900484 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800485 @Override
486 public void callback(int startStatusCode) {
487 if (startStatusCode != STATUS_SUCCESS) {
488 mLog.e("Error starting DHCP server: " + startStatusCode);
489 handleError();
490 }
491 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900492 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800493 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800494 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800495 }
496 });
497 }
498
499 private void handleError() {
Mark74461fc2022-12-14 08:49:40 +0000500 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800501 transitionTo(mInitialState);
502 }
503 }
504
Xiao Ma4455d6b2020-04-09 10:13:44 +0900505 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900506 @Override
507 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
508 final ArrayList<TetheredClient> leases = new ArrayList<>();
509 for (DhcpLeaseParcelable lease : leaseParcelables) {
510 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900511 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
512 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
513 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900514
515 final MacAddress macAddress;
516 try {
517 macAddress = MacAddress.fromBytes(lease.hwAddr);
518 } catch (IllegalArgumentException e) {
519 Log.wtf(TAG, "Invalid address received from DhcpServer: "
520 + Arrays.toString(lease.hwAddr));
521 return;
522 }
523
524 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900525 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900526 leases.add(new TetheredClient(
527 macAddress,
528 Collections.singletonList(addressInfo),
529 mInterfaceType));
530 }
531
532 getHandler().post(() -> {
533 mDhcpLeases = leases;
534 mCallback.dhcpLeasesChanged();
535 });
536 }
537
538 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900539 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
540 Objects.requireNonNull(currentPrefix);
541 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900542 }
543
544 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900545 public int getInterfaceVersion() {
546 return this.VERSION;
547 }
548
549 @Override
550 public String getInterfaceHash() throws RemoteException {
551 return this.HASH;
552 }
553 }
554
Xiao Ma4455d6b2020-04-09 10:13:44 +0900555 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
556 Objects.requireNonNull(ipv4Address);
557 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
558 }
559
560 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
561 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
562 @Nullable Inet4Address clientAddr) {
563 final boolean changePrefixOnDecline =
564 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
markchienfb65dfe2022-02-25 23:14:58 +0800565 final int subnetPrefixLength = mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
566 ? mP2pLeasesSubnetPrefixLength : 0 /* default value */;
567
Xiao Ma4455d6b2020-04-09 10:13:44 +0900568 return new DhcpServingParamsParcelExt()
569 .setDefaultRouters(defaultRouter)
570 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
571 .setDnsServers(dnsServer)
572 .setServerAddr(serverAddr)
573 .setMetered(true)
574 .setSingleClientAddr(clientAddr)
markchienfb65dfe2022-02-25 23:14:58 +0800575 .setChangePrefixOnDecline(changePrefixOnDecline)
576 .setLeasesSubnetPrefixLength(subnetPrefixLength);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900577 // TODO: also advertise link MTU
578 }
579
markchien245352e2020-02-27 20:27:18 +0800580 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800581 if (mUsingLegacyDhcp) {
582 return true;
583 }
markchien245352e2020-02-27 20:27:18 +0800584
585 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800586 final Inet4Address clientAddr = clientLinkAddr == null ? null :
587 (Inet4Address) clientLinkAddr.getAddress();
588
Xiao Ma4455d6b2020-04-09 10:13:44 +0900589 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
590 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800591 mDhcpServerStartIndex++;
592 mDeps.makeDhcpServer(
593 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
594 return true;
595 }
596
597 private void stopDhcp() {
598 // Make all previous start requests obsolete so servers are not started later
599 mDhcpServerStartIndex++;
600
601 if (mDhcpServer != null) {
602 try {
603 mDhcpServer.stop(new OnHandlerStatusCallback() {
604 @Override
605 public void callback(int statusCode) {
606 if (statusCode != STATUS_SUCCESS) {
607 mLog.e("Error stopping DHCP server: " + statusCode);
Mark74461fc2022-12-14 08:49:40 +0000608 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800609 // Not much more we can do here
610 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900611 mDhcpLeases.clear();
612 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800613 }
614 });
615 mDhcpServer = null;
616 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900617 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800618 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800619 }
620 }
621 }
622
markchien245352e2020-02-27 20:27:18 +0800623 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
624 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800625 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800626 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800627 } else {
628 stopDhcp();
629 return true;
630 }
631 }
632
633 private void stopIPv4() {
Mark49649c92023-03-15 06:45:04 +0000634 configureIPv4(false /* enabled */, CONNECTIVITY_SCOPE_GLOBAL /* not used */);
markchien74a4fa92019-09-09 20:50:49 +0800635 // NOTE: All of configureIPv4() will be refactored out of existence
636 // into calls to InterfaceController, shared with startIPv4().
637 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800638 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800639 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800640 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800641 mStaticIpv4ServerAddr = null;
642 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800643 }
644
Mark49649c92023-03-15 06:45:04 +0000645 private boolean configureIPv4(boolean enabled, int scope) {
markchien74a4fa92019-09-09 20:50:49 +0800646 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
647
markchienc9daba32020-02-12 00:19:21 +0800648 if (enabled) {
Mark49649c92023-03-15 06:45:04 +0000649 mIpv4Address = requestIpv4Address(scope, true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800650 }
651
652 if (mIpv4Address == null) {
653 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800654 return false;
markchien74a4fa92019-09-09 20:50:49 +0800655 }
656
markchien69681d62021-11-15 23:58:05 +0800657 if (shouldNotConfigureBluetoothInterface()) {
658 // Interface was already configured elsewhere, only start DHCP.
markchienc9daba32020-02-12 00:19:21 +0800659 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
660 }
661
662 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
663
markchien12c5bb82020-01-07 14:43:17 +0800664 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800665 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900666 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200667 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
668 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900669 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800670 // It is unclear whether the Bluetooth or USB stacks will manage their own
671 // state.
672 setIfaceUp = null;
673 } else {
674 setIfaceUp = enabled;
675 }
676 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
677 mLog.e("Error configuring interface");
678 if (!enabled) stopDhcp();
679 return false;
680 }
markchien74a4fa92019-09-09 20:50:49 +0800681
markchien74a4fa92019-09-09 20:50:49 +0800682 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800683 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900684 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800685 } else {
markchien12c5bb82020-01-07 14:43:17 +0800686 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900687 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800688 }
markchien245352e2020-02-27 20:27:18 +0800689 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800690 }
691
markchien69681d62021-11-15 23:58:05 +0800692 private boolean shouldNotConfigureBluetoothInterface() {
693 // Before T, bluetooth tethering configures the interface elsewhere.
694 return (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) && !SdkLevel.isAtLeastT();
695 }
696
Mark49649c92023-03-15 06:45:04 +0000697 private LinkAddress requestIpv4Address(final int scope, final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800698 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800699
markchien69681d62021-11-15 23:58:05 +0800700 if (shouldNotConfigureBluetoothInterface()) return new LinkAddress(BLUETOOTH_IFACE_ADDR);
markchienc9daba32020-02-12 00:19:21 +0800701
Mark49649c92023-03-15 06:45:04 +0000702 return mPrivateAddressCoordinator.requestDownstreamAddress(this, scope, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900703 }
704
markchien74a4fa92019-09-09 20:50:49 +0800705 private boolean startIPv6() {
706 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
707 if (mInterfaceParams == null) {
708 mLog.e("Failed to find InterfaceParams");
709 stopIPv6();
710 return false;
711 }
712
713 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
714 if (!mRaDaemon.start()) {
715 stopIPv6();
716 return false;
717 }
718
markchien932df542021-08-12 13:56:43 +0800719 if (SdkLevel.isAtLeastS()) {
Tyler Wear90e40632020-03-13 11:38:38 -0700720 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
721 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
722 }
723
markchien74a4fa92019-09-09 20:50:49 +0800724 return true;
725 }
726
727 private void stopIPv6() {
728 mInterfaceParams = null;
729 setRaParams(null);
730
731 if (mRaDaemon != null) {
732 mRaDaemon.stop();
733 mRaDaemon = null;
734 }
Tyler Wear90e40632020-03-13 11:38:38 -0700735
736 if (mDadProxy != null) {
737 mDadProxy.stop();
738 mDadProxy = null;
739 }
markchien74a4fa92019-09-09 20:50:49 +0800740 }
741
742 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
743 // LinkProperties. These have extraneous data filtered out and only the
744 // necessary prefixes included (per its prefix distribution policy).
745 //
746 // TODO: Evaluate using a data structure than is more directly suited to
747 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800748 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800749 if (mRaDaemon == null) return;
750
751 // Avoid unnecessary work on spurious updates.
752 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
753 return;
754 }
755
756 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700757 String upstreamIface = null;
758 InterfaceParams upstreamIfaceParams = null;
KH Shi701c3ca2023-08-16 13:19:33 +0000759 int upstreamIfIndex = NO_UPSTREAM;
markchien74a4fa92019-09-09 20:50:49 +0800760
761 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700762 upstreamIface = v6only.getInterfaceName();
763 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
764 if (upstreamIfaceParams != null) {
765 upstreamIfIndex = upstreamIfaceParams.index;
766 }
markchien74a4fa92019-09-09 20:50:49 +0800767 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700768 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800769 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
770
markchiend63c4f32020-05-21 17:38:28 +0800771 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800772
773 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
774 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
775
776 final IpPrefix prefix = new IpPrefix(
777 linkAddr.getAddress(), linkAddr.getPrefixLength());
778 params.prefixes.add(prefix);
779
780 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
781 if (dnsServer != null) {
782 params.dnses.add(dnsServer);
783 }
784 }
785 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900786
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900787 // Add upstream index to name mapping. See the comment of the interface mapping update in
788 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
789 // timing issue. It prevents that the IPv6 capability is updated later than
790 // CMD_TETHER_CONNECTION_CHANGED.
KH Shi701c3ca2023-08-16 13:19:33 +0000791 mBpfCoordinator.maybeAddUpstreamToLookupTable(upstreamIfIndex, upstreamIface);
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900792
markchien74a4fa92019-09-09 20:50:49 +0800793 // If v6only is null, we pass in null to setRaParams(), which handles
794 // deprecation of any existing RA data.
markchien74a4fa92019-09-09 20:50:49 +0800795 setRaParams(params);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900796
KH Shi68770342023-08-17 14:34:31 +0000797 // Not support BPF on virtual upstream interface
798 final boolean upstreamSupportsBpf = upstreamIface != null && !isVcnInterface(upstreamIface);
KH Shi701c3ca2023-08-16 13:19:33 +0000799 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfIndex, upstreamSupportsBpf);
KH Shi68770342023-08-17 14:34:31 +0000800 mLastIPv6LinkProperties = v6only;
Tyler Wear90e40632020-03-13 11:38:38 -0700801 mLastIPv6UpstreamIfindex = upstreamIfIndex;
KH Shi68770342023-08-17 14:34:31 +0000802 mUpstreamSupportsBpf = upstreamSupportsBpf;
Tyler Wear90e40632020-03-13 11:38:38 -0700803 if (mDadProxy != null) {
804 mDadProxy.setUpstreamIface(upstreamIfaceParams);
805 }
markchien74a4fa92019-09-09 20:50:49 +0800806 }
807
Xiao Ma4455d6b2020-04-09 10:13:44 +0900808 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900809 final int removalFailures = NetdUtils.removeRoutesFromLocalNetwork(
Xiao Ma4455d6b2020-04-09 10:13:44 +0900810 mNetd, toBeRemoved);
811 if (removalFailures > 0) {
812 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
813 removalFailures));
814 }
815
816 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
817 }
818
Chalard Jean2fb66f12023-08-25 12:50:37 +0900819 private void addInterfaceToNetwork(final int netId, @NonNull final String ifaceName) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900820 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +0900821 if (null != mRoutingCoordinator.value) {
822 // TODO : remove this call in favor of using the LocalNetworkConfiguration
823 // correctly, which will let ConnectivityService do it automatically.
824 mRoutingCoordinator.value.addInterfaceToNetwork(netId, ifaceName);
825 } else {
826 mNetd.networkAddInterface(netId, ifaceName);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900827 }
828 } catch (ServiceSpecificException | RemoteException e) {
829 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
Chalard Jean55ccfe12023-10-06 18:31:08 +0900830 }
831 }
832
833 private void addInterfaceForward(@NonNull final String fromIface,
834 @NonNull final String toIface) throws ServiceSpecificException, RemoteException {
835 if (null != mRoutingCoordinator.value) {
836 mRoutingCoordinator.value.addInterfaceForward(fromIface, toIface);
837 } else {
838 mNetd.tetherAddForward(fromIface, toIface);
839 mNetd.ipfwdAddInterfaceForward(fromIface, toIface);
840 }
841 }
842
843 private void removeInterfaceForward(@NonNull final String fromIface,
844 @NonNull final String toIface) {
845 if (null != mRoutingCoordinator.value) {
846 try {
847 mRoutingCoordinator.value.removeInterfaceForward(fromIface, toIface);
848 } catch (ServiceSpecificException e) {
849 mLog.e("Exception in removeInterfaceForward", e);
850 }
851 } else {
852 try {
853 mNetd.ipfwdRemoveInterfaceForward(fromIface, toIface);
854 } catch (RemoteException | ServiceSpecificException e) {
855 mLog.e("Exception in ipfwdRemoveInterfaceForward", e);
856 }
857 try {
858 mNetd.tetherRemoveForward(fromIface, toIface);
859 } catch (RemoteException | ServiceSpecificException e) {
860 mLog.e("Exception in disableNat", e);
861 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900862 }
Chalard Jean2fb66f12023-08-25 12:50:37 +0900863 }
864
865 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
866 // It's safe to call addInterfaceToNetwork() even if
867 // the interface is already in the local_network.
868 addInterfaceToNetwork(INetd.LOCAL_NET_ID, mIfaceName);
869 try {
870 // Add routes from local network. Note that adding routes that
871 // already exist does not cause an error (EEXIST is silently ignored).
872 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
873 } catch (IllegalStateException e) {
874 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
875 return;
876 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900877
878 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
879 }
880
markchien74a4fa92019-09-09 20:50:49 +0800881 private void configureLocalIPv6Routes(
882 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
883 // [1] Remove the routes that are deprecated.
884 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900885 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800886 }
887
888 // [2] Add only the routes that have not previously been added.
889 if (newPrefixes != null && !newPrefixes.isEmpty()) {
890 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
891 if (mLastRaParams != null) {
892 addedPrefixes.removeAll(mLastRaParams.prefixes);
893 }
894
895 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900896 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800897 }
898 }
899 }
900
901 private void configureLocalIPv6Dns(
902 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
903 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
904 if (mNetd == null) {
905 if (newDnses != null) newDnses.clear();
906 mLog.e("No netd service instance available; not setting local IPv6 addresses");
907 return;
908 }
909
910 // [1] Remove deprecated local DNS IP addresses.
911 if (!deprecatedDnses.isEmpty()) {
912 for (Inet6Address dns : deprecatedDnses) {
913 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
914 mLog.e("Failed to remove local dns IP " + dns);
915 }
916
917 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
918 }
919 }
920
921 // [2] Add only the local DNS IP addresses that have not previously been added.
922 if (newDnses != null && !newDnses.isEmpty()) {
923 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
924 if (mLastRaParams != null) {
925 addedDnses.removeAll(mLastRaParams.dnses);
926 }
927
928 for (Inet6Address dns : addedDnses) {
929 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
930 mLog.e("Failed to add local dns IP " + dns);
931 newDnses.remove(dns);
932 }
933
934 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
935 }
936 }
937
938 try {
939 mNetd.tetherApplyDnsInterfaces();
940 } catch (ServiceSpecificException | RemoteException e) {
941 mLog.e("Failed to update local DNS caching server");
942 if (newDnses != null) newDnses.clear();
943 }
944 }
945
KH Shi701c3ca2023-08-16 13:19:33 +0000946 private int getInterfaceIndexForRule(int ifindex, boolean supportsBpf) {
947 return supportsBpf ? ifindex : NO_UPSTREAM;
948 }
949
950 // Handles updates to IPv6 forwarding rules if the upstream changes.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900951 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
KH Shi701c3ca2023-08-16 13:19:33 +0000952 boolean upstreamSupportsBpf) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900953 // If the upstream interface has changed, remove all rules and re-add them with the new
KH Shi701c3ca2023-08-16 13:19:33 +0000954 // upstream interface. If upstream is a virtual network, treated as no upstream.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900955 if (prevUpstreamIfindex != upstreamIfindex) {
KH Shi701c3ca2023-08-16 13:19:33 +0000956 mBpfCoordinator.updateAllIpv6Rules(this, this.mInterfaceParams,
957 getInterfaceIndexForRule(upstreamIfindex, upstreamSupportsBpf));
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900958 }
KH Shi701c3ca2023-08-16 13:19:33 +0000959 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900960
KH Shi701c3ca2023-08-16 13:19:33 +0000961 // Handles updates to IPv6 downstream rules if a neighbor event is received.
962 private void addOrRemoveIpv6Downstream(NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900963 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900964 if (e == null) return;
965 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
966 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
967 return;
968 }
969
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900970 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
KH Shi59ad35e2023-08-15 07:13:00 +0000971 // Do this here instead of in the Ipv6DownstreamRule constructor to ensure that we
972 // never add rules with a null MAC, only delete them.
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900973 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
KH Shi701c3ca2023-08-16 13:19:33 +0000974 Ipv6DownstreamRule rule = new Ipv6DownstreamRule(
975 getInterfaceIndexForRule(mLastIPv6UpstreamIfindex, mUpstreamSupportsBpf),
976 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900977 if (e.isValid()) {
KH Shie4d549a2023-08-28 09:57:34 +0000978 mBpfCoordinator.addIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900979 } else {
KH Shie4d549a2023-08-28 09:57:34 +0000980 mBpfCoordinator.removeIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900981 }
982 }
983
Hungming Chend71c06e2020-12-21 19:39:49 +0800984 // TODO: consider moving into BpfCoordinator.
985 private void updateClientInfoIpv4(NeighborEvent e) {
Hungming Chend71c06e2020-12-21 19:39:49 +0800986 if (e == null) return;
987 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
988 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
989 return;
990 }
991
992 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
993 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
994 // IpServer never add clients with a null MAC, only delete them.
995 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
996 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
997 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
998 if (e.isValid()) {
999 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
1000 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +08001001 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
1002 }
1003 }
1004
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001005 private void handleNeighborEvent(NeighborEvent e) {
1006 if (mInterfaceParams != null
1007 && mInterfaceParams.index == e.ifindex
1008 && mInterfaceParams.hasMacAddress) {
KH Shi701c3ca2023-08-16 13:19:33 +00001009 addOrRemoveIpv6Downstream(e);
Hungming Chend71c06e2020-12-21 19:39:49 +08001010 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001011 }
1012 }
1013
markchiend63c4f32020-05-21 17:38:28 +08001014 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001015 try {
1016 int upstreamHopLimit = Integer.parseUnsignedInt(
1017 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001018 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001019 // Cap the hop limit to 255.
1020 return (byte) Integer.min(upstreamHopLimit, 255);
1021 } catch (Exception e) {
1022 mLog.e("Failed to find upstream interface hop limit", e);
1023 }
1024 return RaParams.DEFAULT_HOPLIMIT;
1025 }
1026
1027 private void setRaParams(RaParams newParams) {
1028 if (mRaDaemon != null) {
1029 final RaParams deprecatedParams =
1030 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1031
1032 configureLocalIPv6Routes(deprecatedParams.prefixes,
1033 (newParams != null) ? newParams.prefixes : null);
1034
1035 configureLocalIPv6Dns(deprecatedParams.dnses,
1036 (newParams != null) ? newParams.dnses : null);
1037
1038 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1039 }
1040
1041 mLastRaParams = newParams;
1042 }
1043
markchien21021ef2021-06-01 10:58:04 +08001044 private void maybeLogMessage(State state, int what) {
1045 switch (what) {
1046 // Suppress some CMD_* to avoid log flooding.
1047 case CMD_IPV6_TETHER_UPDATE:
1048 case CMD_NEIGHBOR_EVENT:
1049 break;
1050 default:
1051 mLog.log(state.getName() + " got "
1052 + sMagicDecoderRing.get(what, Integer.toString(what)));
1053 }
markchien74a4fa92019-09-09 20:50:49 +08001054 }
1055
1056 private void sendInterfaceState(int newInterfaceState) {
1057 mServingMode = newInterfaceState;
1058 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1059 sendLinkProperties();
1060 }
1061
1062 private void sendLinkProperties() {
1063 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1064 }
1065
1066 private void resetLinkProperties() {
1067 mLinkProperties.clear();
1068 mLinkProperties.setInterfaceName(mIfaceName);
1069 }
1070
markchienf053e4b2020-03-16 21:49:48 +08001071 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001072 // Ignore static address configuration if they are invalid or null. In theory, static
1073 // addresses should not be invalid here because TetheringManager do not allow caller to
1074 // specify invalid static address configuration.
1075 if (request == null || request.localIPv4Address == null
1076 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1077 request.localIPv4Address, request.staticClientAddress)) {
1078 return;
1079 }
markchienf053e4b2020-03-16 21:49:48 +08001080
1081 mStaticIpv4ServerAddr = request.localIPv4Address;
1082 mStaticIpv4ClientAddr = request.staticClientAddress;
1083 }
1084
markchien74a4fa92019-09-09 20:50:49 +08001085 class InitialState extends State {
1086 @Override
1087 public void enter() {
1088 sendInterfaceState(STATE_AVAILABLE);
1089 }
1090
1091 @Override
1092 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001093 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001094 switch (message.what) {
1095 case CMD_TETHER_REQUESTED:
Mark74461fc2022-12-14 08:49:40 +00001096 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001097 switch (message.arg1) {
1098 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001099 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001100 transitionTo(mLocalHotspotState);
1101 break;
1102 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001103 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001104 transitionTo(mTetheredState);
1105 break;
1106 default:
1107 mLog.e("Invalid tethering interface serving state specified.");
1108 }
1109 break;
1110 case CMD_INTERFACE_DOWN:
1111 transitionTo(mUnavailableState);
1112 break;
markchien74a4fa92019-09-09 20:50:49 +08001113 default:
1114 return NOT_HANDLED;
1115 }
1116 return HANDLED;
1117 }
1118 }
1119
Hungming Chen46c30b12020-10-15 17:25:36 +08001120 private void startConntrackMonitoring() {
1121 mBpfCoordinator.startMonitoring(this);
1122 }
1123
1124 private void stopConntrackMonitoring() {
1125 mBpfCoordinator.stopMonitoring(this);
1126 }
1127
Mark3ec851e2023-05-19 08:50:38 +00001128 abstract class BaseServingState extends State {
1129 private final int mDesiredInterfaceState;
1130
1131 BaseServingState(int interfaceState) {
1132 mDesiredInterfaceState = interfaceState;
1133 }
1134
markchien74a4fa92019-09-09 20:50:49 +08001135 @Override
1136 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001137 startConntrackMonitoring();
1138
Mark3ec851e2023-05-19 08:50:38 +00001139 startServingInterface();
1140
1141 if (mLastError != TETHER_ERROR_NO_ERROR) {
1142 transitionTo(mInitialState);
1143 }
1144
1145 if (DBG) Log.d(TAG, getStateString(mDesiredInterfaceState) + " serve " + mIfaceName);
1146 sendInterfaceState(mDesiredInterfaceState);
1147 }
1148
Mark49649c92023-03-15 06:45:04 +00001149 private int getScope() {
1150 if (mDesiredInterfaceState == STATE_TETHERED) {
1151 return CONNECTIVITY_SCOPE_GLOBAL;
1152 }
1153
1154 return CONNECTIVITY_SCOPE_LOCAL;
1155 }
1156
Mark3ec851e2023-05-19 08:50:38 +00001157 private void startServingInterface() {
Mark49649c92023-03-15 06:45:04 +00001158 if (!startIPv4(getScope())) {
Mark74461fc2022-12-14 08:49:40 +00001159 mLastError = TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001160 return;
1161 }
1162
1163 try {
markchienc9daba32020-02-12 00:19:21 +08001164 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001165 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001166 mLog.e("Error Tethering", e);
Mark74461fc2022-12-14 08:49:40 +00001167 mLastError = TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001168 return;
1169 }
1170
1171 if (!startIPv6()) {
1172 mLog.e("Failed to startIPv6");
1173 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1174 return;
1175 }
1176 }
1177
1178 @Override
1179 public void exit() {
1180 // Note that at this point, we're leaving the tethered state. We can fail any
1181 // of these operations, but it doesn't really change that we have to try them
1182 // all in sequence.
1183 stopIPv6();
1184
1185 try {
markchien12c5bb82020-01-07 14:43:17 +08001186 NetdUtils.untetherInterface(mNetd, mIfaceName);
1187 } catch (RemoteException | ServiceSpecificException e) {
Mark74461fc2022-12-14 08:49:40 +00001188 mLastError = TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001189 mLog.e("Failed to untether interface: " + e);
1190 }
1191
1192 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001193 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001194
1195 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001196
1197 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1198 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001199 }
1200
1201 @Override
1202 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001203 switch (message.what) {
1204 case CMD_TETHER_UNREQUESTED:
1205 transitionTo(mInitialState);
1206 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1207 break;
1208 case CMD_INTERFACE_DOWN:
1209 transitionTo(mUnavailableState);
1210 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1211 break;
1212 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001213 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001214 sendLinkProperties();
1215 break;
1216 case CMD_IP_FORWARDING_ENABLE_ERROR:
1217 case CMD_IP_FORWARDING_DISABLE_ERROR:
1218 case CMD_START_TETHERING_ERROR:
1219 case CMD_STOP_TETHERING_ERROR:
1220 case CMD_SET_DNS_FORWARDERS_ERROR:
Mark74461fc2022-12-14 08:49:40 +00001221 mLastError = TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001222 transitionTo(mInitialState);
1223 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001224 case CMD_NEW_PREFIX_REQUEST:
1225 handleNewPrefixRequest((IpPrefix) message.obj);
1226 break;
markchienc9daba32020-02-12 00:19:21 +08001227 case CMD_NOTIFY_PREFIX_CONFLICT:
1228 mLog.i("restart tethering: " + mInterfaceType);
1229 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1230 transitionTo(mWaitingForRestartState);
1231 break;
markchien74a4fa92019-09-09 20:50:49 +08001232 default:
1233 return false;
1234 }
1235 return true;
1236 }
Mark3ec851e2023-05-19 08:50:38 +00001237
1238 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
1239 if (!currentPrefix.contains(mIpv4Address.getAddress())
1240 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
1241 Log.e(TAG, "Invalid prefix: " + currentPrefix);
1242 return;
1243 }
1244
1245 final LinkAddress deprecatedLinkAddress = mIpv4Address;
Mark49649c92023-03-15 06:45:04 +00001246 mIpv4Address = requestIpv4Address(getScope(), false);
Mark3ec851e2023-05-19 08:50:38 +00001247 if (mIpv4Address == null) {
1248 mLog.e("Fail to request a new downstream prefix");
1249 return;
1250 }
1251 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
1252
1253 // Add new IPv4 address on the interface.
1254 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1255 mLog.e("Failed to add new IP " + srvAddr);
1256 return;
1257 }
1258
1259 // Remove deprecated routes from local network.
1260 removeRoutesFromLocalNetwork(
1261 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1262 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1263
1264 // Add new routes to local network.
1265 addRoutesToLocalNetwork(
1266 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1267 mLinkProperties.addLinkAddress(mIpv4Address);
1268
1269 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1270 // listen on the interface configured with new IPv4 address, that results DNS validation
1271 // failure of downstream client even if appropriate routes have been configured.
1272 try {
1273 mNetd.tetherApplyDnsInterfaces();
1274 } catch (ServiceSpecificException | RemoteException e) {
1275 mLog.e("Failed to update local DNS caching server");
1276 return;
1277 }
1278 sendLinkProperties();
1279
1280 // Notify DHCP server that new prefix/route has been applied on IpServer.
1281 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1282 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1283 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1284 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1285 try {
1286 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1287 @Override
1288 public void callback(int statusCode) {
1289 if (statusCode != STATUS_SUCCESS) {
1290 mLog.e("Error updating DHCP serving params: " + statusCode);
1291 }
1292 }
1293 });
1294 } catch (RemoteException e) {
1295 mLog.e("Error updating DHCP serving params", e);
1296 }
1297 }
markchien74a4fa92019-09-09 20:50:49 +08001298 }
1299
1300 // Handling errors in BaseServingState.enter() by transitioning is
1301 // problematic because transitioning during a multi-state jump yields
1302 // a Log.wtf(). Ultimately, there should be only one ServingState,
1303 // and forwarding and NAT rules should be handled by a coordinating
1304 // functional element outside of IpServer.
1305 class LocalHotspotState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001306 LocalHotspotState() {
1307 super(STATE_LOCAL_ONLY);
markchien74a4fa92019-09-09 20:50:49 +08001308 }
1309
1310 @Override
1311 public boolean processMessage(Message message) {
1312 if (super.processMessage(message)) return true;
1313
markchien21021ef2021-06-01 10:58:04 +08001314 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001315 switch (message.what) {
1316 case CMD_TETHER_REQUESTED:
1317 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1318 break;
1319 case CMD_TETHER_CONNECTION_CHANGED:
1320 // Ignored in local hotspot state.
1321 break;
1322 default:
1323 return false;
1324 }
1325 return true;
1326 }
1327 }
1328
1329 // Handling errors in BaseServingState.enter() by transitioning is
1330 // problematic because transitioning during a multi-state jump yields
1331 // a Log.wtf(). Ultimately, there should be only one ServingState,
1332 // and forwarding and NAT rules should be handled by a coordinating
1333 // functional element outside of IpServer.
1334 class TetheredState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001335 TetheredState() {
1336 super(STATE_TETHERED);
markchien74a4fa92019-09-09 20:50:49 +08001337 }
1338
1339 @Override
1340 public void exit() {
1341 cleanupUpstream();
KH Shi701c3ca2023-08-16 13:19:33 +00001342 mBpfCoordinator.clearAllIpv6Rules(IpServer.this);
markchien74a4fa92019-09-09 20:50:49 +08001343 super.exit();
1344 }
1345
Hungming Chena6e78692021-02-08 17:15:35 +08001346 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1347 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1348 // and behaviour. While upstream is switching from offload supported interface to
1349 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1350 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1351 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1352 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1353 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1354 // in the state machine. Once there is any case out whish is not covered by previous cases,
1355 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001356 private void cleanupUpstream() {
1357 if (mUpstreamIfaceSet == null) return;
1358
1359 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1360 mUpstreamIfaceSet = null;
KH Shi701c3ca2023-08-16 13:19:33 +00001361 mBpfCoordinator.updateAllIpv6Rules(
1362 IpServer.this, IpServer.this.mInterfaceParams, NO_UPSTREAM);
markchien74a4fa92019-09-09 20:50:49 +08001363 }
1364
1365 private void cleanupUpstreamInterface(String upstreamIface) {
1366 // Note that we don't care about errors here.
1367 // Sometimes interfaces are gone before we get
1368 // to remove their rules, which generates errors.
1369 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001370 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
Chalard Jean55ccfe12023-10-06 18:31:08 +09001371 removeInterfaceForward(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001372 }
1373
1374 @Override
1375 public boolean processMessage(Message message) {
1376 if (super.processMessage(message)) return true;
1377
markchien21021ef2021-06-01 10:58:04 +08001378 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001379 switch (message.what) {
1380 case CMD_TETHER_REQUESTED:
1381 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1382 break;
1383 case CMD_TETHER_CONNECTION_CHANGED:
1384 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1385 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1386 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1387 break;
1388 }
1389
1390 if (newUpstreamIfaceSet == null) {
1391 cleanupUpstream();
1392 break;
1393 }
1394
1395 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1396 cleanupUpstreamInterface(removed);
1397 }
1398
1399 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1400 // This makes the call to cleanupUpstream() in the error
1401 // path for any interface neatly cleanup all the interfaces.
1402 mUpstreamIfaceSet = newUpstreamIfaceSet;
1403
1404 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001405 // Add upstream index to name mapping for the tether stats usage in the
1406 // coordinator. Although this mapping could be added by both class
1407 // Tethering and IpServer, adding mapping from IpServer guarantees that
1408 // the mapping is added before adding forwarding rules. That is because
1409 // there are different state machines in both classes. It is hard to
1410 // guarantee the link property update order between multiple state machines.
1411 // Note that both IPv4 and IPv6 interface may be added because
1412 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1413 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1414 // capability may be updated later. In that case, IPv6 interface mapping is
1415 // updated in updateUpstreamIPv6LinkProperties.
1416 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1417 final InterfaceParams upstreamIfaceParams =
1418 mDeps.getInterfaceParams(ifname);
1419 if (upstreamIfaceParams != null) {
KH Shi701c3ca2023-08-16 13:19:33 +00001420 mBpfCoordinator.maybeAddUpstreamToLookupTable(
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001421 upstreamIfaceParams.index, ifname);
1422 }
1423 }
1424
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001425 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001426 try {
Chalard Jean55ccfe12023-10-06 18:31:08 +09001427 addInterfaceForward(mIfaceName, ifname);
markchien12c5bb82020-01-07 14:43:17 +08001428 } catch (RemoteException | ServiceSpecificException e) {
Chalard Jean55ccfe12023-10-06 18:31:08 +09001429 mLog.e("Exception enabling iface forward", e);
markchien74a4fa92019-09-09 20:50:49 +08001430 cleanupUpstream();
Mark74461fc2022-12-14 08:49:40 +00001431 mLastError = TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001432 transitionTo(mInitialState);
1433 return true;
1434 }
1435 }
1436 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001437 case CMD_NEIGHBOR_EVENT:
1438 handleNeighborEvent((NeighborEvent) message.obj);
1439 break;
markchien74a4fa92019-09-09 20:50:49 +08001440 default:
1441 return false;
1442 }
1443 return true;
1444 }
1445
1446 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1447 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1448 if (mUpstreamIfaceSet != null && newIfaces != null) {
1449 return mUpstreamIfaceSet.equals(newIfaces);
1450 }
1451 return false;
1452 }
1453
1454 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1455 if (mUpstreamIfaceSet == null) return new HashSet<>();
1456
1457 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1458 removed.removeAll(newIfaces.ifnames);
1459 return removed;
1460 }
1461
1462 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1463 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1464 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1465 return added;
1466 }
1467 }
1468
1469 /**
1470 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001471 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001472 * specific state machine from its list of possible recipients of
1473 * tethering requests. The state machine itself will hang around until
1474 * the garbage collector finds it.
1475 */
1476 class UnavailableState extends State {
1477 @Override
1478 public void enter() {
KH Shi701c3ca2023-08-16 13:19:33 +00001479 // TODO: move mIpNeighborMonitor.stop() to TetheredState#exit, and trigger a neighbours
1480 // dump after starting mIpNeighborMonitor.
h.zhangd244bd02020-06-14 14:46:54 +08001481 mIpNeighborMonitor.stop();
Mark74461fc2022-12-14 08:49:40 +00001482 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001483 sendInterfaceState(STATE_UNAVAILABLE);
1484 }
1485 }
1486
markchienc9daba32020-02-12 00:19:21 +08001487 class WaitingForRestartState extends State {
1488 @Override
1489 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001490 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001491 switch (message.what) {
1492 case CMD_TETHER_UNREQUESTED:
1493 transitionTo(mInitialState);
1494 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1495 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1496 break;
1497 case CMD_INTERFACE_DOWN:
1498 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001499 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001500 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1501 break;
1502 default:
1503 return false;
1504 }
1505 return true;
1506 }
1507 }
1508
markchien74a4fa92019-09-09 20:50:49 +08001509 // Accumulate routes representing "prefixes to be assigned to the local
1510 // interface", for subsequent modification of local_network routing.
1511 private static ArrayList<RouteInfo> getLocalRoutesFor(
1512 String ifname, HashSet<IpPrefix> prefixes) {
1513 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1514 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001515 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001516 }
1517 return localRoutes;
1518 }
1519
1520 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1521 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1522 final byte[] dnsBytes = localPrefix.getRawAddress();
1523 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1524 try {
1525 return Inet6Address.getByAddress(null, dnsBytes, 0);
1526 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001527 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001528 return null;
1529 }
1530 }
1531
1532 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1533 final byte random = (byte) (new Random()).nextInt();
1534 for (int value : excluded) {
1535 if (random == value) return dflt;
1536 }
1537 return random;
1538 }
1539}