blob: 246e5bcce2419b2a469f80176554ba264ab37dc0 [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);
830 return;
831 }
Chalard Jean2fb66f12023-08-25 12:50:37 +0900832 }
833
834 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
835 // It's safe to call addInterfaceToNetwork() even if
836 // the interface is already in the local_network.
837 addInterfaceToNetwork(INetd.LOCAL_NET_ID, mIfaceName);
838 try {
839 // Add routes from local network. Note that adding routes that
840 // already exist does not cause an error (EEXIST is silently ignored).
841 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
842 } catch (IllegalStateException e) {
843 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
844 return;
845 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900846
847 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
848 }
849
markchien74a4fa92019-09-09 20:50:49 +0800850 private void configureLocalIPv6Routes(
851 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
852 // [1] Remove the routes that are deprecated.
853 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900854 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800855 }
856
857 // [2] Add only the routes that have not previously been added.
858 if (newPrefixes != null && !newPrefixes.isEmpty()) {
859 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
860 if (mLastRaParams != null) {
861 addedPrefixes.removeAll(mLastRaParams.prefixes);
862 }
863
864 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900865 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800866 }
867 }
868 }
869
870 private void configureLocalIPv6Dns(
871 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
872 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
873 if (mNetd == null) {
874 if (newDnses != null) newDnses.clear();
875 mLog.e("No netd service instance available; not setting local IPv6 addresses");
876 return;
877 }
878
879 // [1] Remove deprecated local DNS IP addresses.
880 if (!deprecatedDnses.isEmpty()) {
881 for (Inet6Address dns : deprecatedDnses) {
882 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
883 mLog.e("Failed to remove local dns IP " + dns);
884 }
885
886 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
887 }
888 }
889
890 // [2] Add only the local DNS IP addresses that have not previously been added.
891 if (newDnses != null && !newDnses.isEmpty()) {
892 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
893 if (mLastRaParams != null) {
894 addedDnses.removeAll(mLastRaParams.dnses);
895 }
896
897 for (Inet6Address dns : addedDnses) {
898 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
899 mLog.e("Failed to add local dns IP " + dns);
900 newDnses.remove(dns);
901 }
902
903 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
904 }
905 }
906
907 try {
908 mNetd.tetherApplyDnsInterfaces();
909 } catch (ServiceSpecificException | RemoteException e) {
910 mLog.e("Failed to update local DNS caching server");
911 if (newDnses != null) newDnses.clear();
912 }
913 }
914
KH Shi701c3ca2023-08-16 13:19:33 +0000915 private int getInterfaceIndexForRule(int ifindex, boolean supportsBpf) {
916 return supportsBpf ? ifindex : NO_UPSTREAM;
917 }
918
919 // Handles updates to IPv6 forwarding rules if the upstream changes.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900920 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
KH Shi701c3ca2023-08-16 13:19:33 +0000921 boolean upstreamSupportsBpf) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900922 // If the upstream interface has changed, remove all rules and re-add them with the new
KH Shi701c3ca2023-08-16 13:19:33 +0000923 // upstream interface. If upstream is a virtual network, treated as no upstream.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900924 if (prevUpstreamIfindex != upstreamIfindex) {
KH Shi701c3ca2023-08-16 13:19:33 +0000925 mBpfCoordinator.updateAllIpv6Rules(this, this.mInterfaceParams,
926 getInterfaceIndexForRule(upstreamIfindex, upstreamSupportsBpf));
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900927 }
KH Shi701c3ca2023-08-16 13:19:33 +0000928 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900929
KH Shi701c3ca2023-08-16 13:19:33 +0000930 // Handles updates to IPv6 downstream rules if a neighbor event is received.
931 private void addOrRemoveIpv6Downstream(NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900932 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900933 if (e == null) return;
934 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
935 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
936 return;
937 }
938
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900939 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
KH Shi59ad35e2023-08-15 07:13:00 +0000940 // Do this here instead of in the Ipv6DownstreamRule constructor to ensure that we
941 // never add rules with a null MAC, only delete them.
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900942 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
KH Shi701c3ca2023-08-16 13:19:33 +0000943 Ipv6DownstreamRule rule = new Ipv6DownstreamRule(
944 getInterfaceIndexForRule(mLastIPv6UpstreamIfindex, mUpstreamSupportsBpf),
945 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900946 if (e.isValid()) {
KH Shie4d549a2023-08-28 09:57:34 +0000947 mBpfCoordinator.addIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900948 } else {
KH Shie4d549a2023-08-28 09:57:34 +0000949 mBpfCoordinator.removeIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900950 }
951 }
952
Hungming Chend71c06e2020-12-21 19:39:49 +0800953 // TODO: consider moving into BpfCoordinator.
954 private void updateClientInfoIpv4(NeighborEvent e) {
Hungming Chend71c06e2020-12-21 19:39:49 +0800955 if (e == null) return;
956 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
957 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
958 return;
959 }
960
961 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
962 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
963 // IpServer never add clients with a null MAC, only delete them.
964 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
965 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
966 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
967 if (e.isValid()) {
968 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
969 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +0800970 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
971 }
972 }
973
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900974 private void handleNeighborEvent(NeighborEvent e) {
975 if (mInterfaceParams != null
976 && mInterfaceParams.index == e.ifindex
977 && mInterfaceParams.hasMacAddress) {
KH Shi701c3ca2023-08-16 13:19:33 +0000978 addOrRemoveIpv6Downstream(e);
Hungming Chend71c06e2020-12-21 19:39:49 +0800979 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900980 }
981 }
982
markchiend63c4f32020-05-21 17:38:28 +0800983 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +0800984 try {
985 int upstreamHopLimit = Integer.parseUnsignedInt(
986 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +0800987 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +0800988 // Cap the hop limit to 255.
989 return (byte) Integer.min(upstreamHopLimit, 255);
990 } catch (Exception e) {
991 mLog.e("Failed to find upstream interface hop limit", e);
992 }
993 return RaParams.DEFAULT_HOPLIMIT;
994 }
995
996 private void setRaParams(RaParams newParams) {
997 if (mRaDaemon != null) {
998 final RaParams deprecatedParams =
999 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1000
1001 configureLocalIPv6Routes(deprecatedParams.prefixes,
1002 (newParams != null) ? newParams.prefixes : null);
1003
1004 configureLocalIPv6Dns(deprecatedParams.dnses,
1005 (newParams != null) ? newParams.dnses : null);
1006
1007 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1008 }
1009
1010 mLastRaParams = newParams;
1011 }
1012
markchien21021ef2021-06-01 10:58:04 +08001013 private void maybeLogMessage(State state, int what) {
1014 switch (what) {
1015 // Suppress some CMD_* to avoid log flooding.
1016 case CMD_IPV6_TETHER_UPDATE:
1017 case CMD_NEIGHBOR_EVENT:
1018 break;
1019 default:
1020 mLog.log(state.getName() + " got "
1021 + sMagicDecoderRing.get(what, Integer.toString(what)));
1022 }
markchien74a4fa92019-09-09 20:50:49 +08001023 }
1024
1025 private void sendInterfaceState(int newInterfaceState) {
1026 mServingMode = newInterfaceState;
1027 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1028 sendLinkProperties();
1029 }
1030
1031 private void sendLinkProperties() {
1032 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1033 }
1034
1035 private void resetLinkProperties() {
1036 mLinkProperties.clear();
1037 mLinkProperties.setInterfaceName(mIfaceName);
1038 }
1039
markchienf053e4b2020-03-16 21:49:48 +08001040 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001041 // Ignore static address configuration if they are invalid or null. In theory, static
1042 // addresses should not be invalid here because TetheringManager do not allow caller to
1043 // specify invalid static address configuration.
1044 if (request == null || request.localIPv4Address == null
1045 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1046 request.localIPv4Address, request.staticClientAddress)) {
1047 return;
1048 }
markchienf053e4b2020-03-16 21:49:48 +08001049
1050 mStaticIpv4ServerAddr = request.localIPv4Address;
1051 mStaticIpv4ClientAddr = request.staticClientAddress;
1052 }
1053
markchien74a4fa92019-09-09 20:50:49 +08001054 class InitialState extends State {
1055 @Override
1056 public void enter() {
1057 sendInterfaceState(STATE_AVAILABLE);
1058 }
1059
1060 @Override
1061 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001062 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001063 switch (message.what) {
1064 case CMD_TETHER_REQUESTED:
Mark74461fc2022-12-14 08:49:40 +00001065 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001066 switch (message.arg1) {
1067 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001068 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001069 transitionTo(mLocalHotspotState);
1070 break;
1071 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001072 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001073 transitionTo(mTetheredState);
1074 break;
1075 default:
1076 mLog.e("Invalid tethering interface serving state specified.");
1077 }
1078 break;
1079 case CMD_INTERFACE_DOWN:
1080 transitionTo(mUnavailableState);
1081 break;
markchien74a4fa92019-09-09 20:50:49 +08001082 default:
1083 return NOT_HANDLED;
1084 }
1085 return HANDLED;
1086 }
1087 }
1088
Hungming Chen46c30b12020-10-15 17:25:36 +08001089 private void startConntrackMonitoring() {
1090 mBpfCoordinator.startMonitoring(this);
1091 }
1092
1093 private void stopConntrackMonitoring() {
1094 mBpfCoordinator.stopMonitoring(this);
1095 }
1096
Mark3ec851e2023-05-19 08:50:38 +00001097 abstract class BaseServingState extends State {
1098 private final int mDesiredInterfaceState;
1099
1100 BaseServingState(int interfaceState) {
1101 mDesiredInterfaceState = interfaceState;
1102 }
1103
markchien74a4fa92019-09-09 20:50:49 +08001104 @Override
1105 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001106 startConntrackMonitoring();
1107
Mark3ec851e2023-05-19 08:50:38 +00001108 startServingInterface();
1109
1110 if (mLastError != TETHER_ERROR_NO_ERROR) {
1111 transitionTo(mInitialState);
1112 }
1113
1114 if (DBG) Log.d(TAG, getStateString(mDesiredInterfaceState) + " serve " + mIfaceName);
1115 sendInterfaceState(mDesiredInterfaceState);
1116 }
1117
Mark49649c92023-03-15 06:45:04 +00001118 private int getScope() {
1119 if (mDesiredInterfaceState == STATE_TETHERED) {
1120 return CONNECTIVITY_SCOPE_GLOBAL;
1121 }
1122
1123 return CONNECTIVITY_SCOPE_LOCAL;
1124 }
1125
Mark3ec851e2023-05-19 08:50:38 +00001126 private void startServingInterface() {
Mark49649c92023-03-15 06:45:04 +00001127 if (!startIPv4(getScope())) {
Mark74461fc2022-12-14 08:49:40 +00001128 mLastError = TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001129 return;
1130 }
1131
1132 try {
markchienc9daba32020-02-12 00:19:21 +08001133 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001134 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001135 mLog.e("Error Tethering", e);
Mark74461fc2022-12-14 08:49:40 +00001136 mLastError = TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001137 return;
1138 }
1139
1140 if (!startIPv6()) {
1141 mLog.e("Failed to startIPv6");
1142 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1143 return;
1144 }
1145 }
1146
1147 @Override
1148 public void exit() {
1149 // Note that at this point, we're leaving the tethered state. We can fail any
1150 // of these operations, but it doesn't really change that we have to try them
1151 // all in sequence.
1152 stopIPv6();
1153
1154 try {
markchien12c5bb82020-01-07 14:43:17 +08001155 NetdUtils.untetherInterface(mNetd, mIfaceName);
1156 } catch (RemoteException | ServiceSpecificException e) {
Mark74461fc2022-12-14 08:49:40 +00001157 mLastError = TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001158 mLog.e("Failed to untether interface: " + e);
1159 }
1160
1161 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001162 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001163
1164 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001165
1166 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1167 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001168 }
1169
1170 @Override
1171 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001172 switch (message.what) {
1173 case CMD_TETHER_UNREQUESTED:
1174 transitionTo(mInitialState);
1175 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1176 break;
1177 case CMD_INTERFACE_DOWN:
1178 transitionTo(mUnavailableState);
1179 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1180 break;
1181 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001182 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001183 sendLinkProperties();
1184 break;
1185 case CMD_IP_FORWARDING_ENABLE_ERROR:
1186 case CMD_IP_FORWARDING_DISABLE_ERROR:
1187 case CMD_START_TETHERING_ERROR:
1188 case CMD_STOP_TETHERING_ERROR:
1189 case CMD_SET_DNS_FORWARDERS_ERROR:
Mark74461fc2022-12-14 08:49:40 +00001190 mLastError = TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001191 transitionTo(mInitialState);
1192 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001193 case CMD_NEW_PREFIX_REQUEST:
1194 handleNewPrefixRequest((IpPrefix) message.obj);
1195 break;
markchienc9daba32020-02-12 00:19:21 +08001196 case CMD_NOTIFY_PREFIX_CONFLICT:
1197 mLog.i("restart tethering: " + mInterfaceType);
1198 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1199 transitionTo(mWaitingForRestartState);
1200 break;
markchien74a4fa92019-09-09 20:50:49 +08001201 default:
1202 return false;
1203 }
1204 return true;
1205 }
Mark3ec851e2023-05-19 08:50:38 +00001206
1207 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
1208 if (!currentPrefix.contains(mIpv4Address.getAddress())
1209 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
1210 Log.e(TAG, "Invalid prefix: " + currentPrefix);
1211 return;
1212 }
1213
1214 final LinkAddress deprecatedLinkAddress = mIpv4Address;
Mark49649c92023-03-15 06:45:04 +00001215 mIpv4Address = requestIpv4Address(getScope(), false);
Mark3ec851e2023-05-19 08:50:38 +00001216 if (mIpv4Address == null) {
1217 mLog.e("Fail to request a new downstream prefix");
1218 return;
1219 }
1220 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
1221
1222 // Add new IPv4 address on the interface.
1223 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1224 mLog.e("Failed to add new IP " + srvAddr);
1225 return;
1226 }
1227
1228 // Remove deprecated routes from local network.
1229 removeRoutesFromLocalNetwork(
1230 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1231 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1232
1233 // Add new routes to local network.
1234 addRoutesToLocalNetwork(
1235 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1236 mLinkProperties.addLinkAddress(mIpv4Address);
1237
1238 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1239 // listen on the interface configured with new IPv4 address, that results DNS validation
1240 // failure of downstream client even if appropriate routes have been configured.
1241 try {
1242 mNetd.tetherApplyDnsInterfaces();
1243 } catch (ServiceSpecificException | RemoteException e) {
1244 mLog.e("Failed to update local DNS caching server");
1245 return;
1246 }
1247 sendLinkProperties();
1248
1249 // Notify DHCP server that new prefix/route has been applied on IpServer.
1250 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1251 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1252 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1253 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1254 try {
1255 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1256 @Override
1257 public void callback(int statusCode) {
1258 if (statusCode != STATUS_SUCCESS) {
1259 mLog.e("Error updating DHCP serving params: " + statusCode);
1260 }
1261 }
1262 });
1263 } catch (RemoteException e) {
1264 mLog.e("Error updating DHCP serving params", e);
1265 }
1266 }
markchien74a4fa92019-09-09 20:50:49 +08001267 }
1268
1269 // Handling errors in BaseServingState.enter() by transitioning is
1270 // problematic because transitioning during a multi-state jump yields
1271 // a Log.wtf(). Ultimately, there should be only one ServingState,
1272 // and forwarding and NAT rules should be handled by a coordinating
1273 // functional element outside of IpServer.
1274 class LocalHotspotState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001275 LocalHotspotState() {
1276 super(STATE_LOCAL_ONLY);
markchien74a4fa92019-09-09 20:50:49 +08001277 }
1278
1279 @Override
1280 public boolean processMessage(Message message) {
1281 if (super.processMessage(message)) return true;
1282
markchien21021ef2021-06-01 10:58:04 +08001283 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001284 switch (message.what) {
1285 case CMD_TETHER_REQUESTED:
1286 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1287 break;
1288 case CMD_TETHER_CONNECTION_CHANGED:
1289 // Ignored in local hotspot state.
1290 break;
1291 default:
1292 return false;
1293 }
1294 return true;
1295 }
1296 }
1297
1298 // Handling errors in BaseServingState.enter() by transitioning is
1299 // problematic because transitioning during a multi-state jump yields
1300 // a Log.wtf(). Ultimately, there should be only one ServingState,
1301 // and forwarding and NAT rules should be handled by a coordinating
1302 // functional element outside of IpServer.
1303 class TetheredState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001304 TetheredState() {
1305 super(STATE_TETHERED);
markchien74a4fa92019-09-09 20:50:49 +08001306 }
1307
1308 @Override
1309 public void exit() {
1310 cleanupUpstream();
KH Shi701c3ca2023-08-16 13:19:33 +00001311 mBpfCoordinator.clearAllIpv6Rules(IpServer.this);
markchien74a4fa92019-09-09 20:50:49 +08001312 super.exit();
1313 }
1314
Hungming Chena6e78692021-02-08 17:15:35 +08001315 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1316 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1317 // and behaviour. While upstream is switching from offload supported interface to
1318 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1319 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1320 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1321 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1322 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1323 // in the state machine. Once there is any case out whish is not covered by previous cases,
1324 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001325 private void cleanupUpstream() {
1326 if (mUpstreamIfaceSet == null) return;
1327
1328 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1329 mUpstreamIfaceSet = null;
KH Shi701c3ca2023-08-16 13:19:33 +00001330 mBpfCoordinator.updateAllIpv6Rules(
1331 IpServer.this, IpServer.this.mInterfaceParams, NO_UPSTREAM);
markchien74a4fa92019-09-09 20:50:49 +08001332 }
1333
1334 private void cleanupUpstreamInterface(String upstreamIface) {
1335 // Note that we don't care about errors here.
1336 // Sometimes interfaces are gone before we get
1337 // to remove their rules, which generates errors.
1338 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001339 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001340 try {
markchien12c5bb82020-01-07 14:43:17 +08001341 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1342 } catch (RemoteException | ServiceSpecificException e) {
1343 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001344 }
1345 try {
markchien12c5bb82020-01-07 14:43:17 +08001346 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1347 } catch (RemoteException | ServiceSpecificException e) {
1348 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001349 }
1350 }
1351
1352 @Override
1353 public boolean processMessage(Message message) {
1354 if (super.processMessage(message)) return true;
1355
markchien21021ef2021-06-01 10:58:04 +08001356 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001357 switch (message.what) {
1358 case CMD_TETHER_REQUESTED:
1359 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1360 break;
1361 case CMD_TETHER_CONNECTION_CHANGED:
1362 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1363 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1364 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1365 break;
1366 }
1367
1368 if (newUpstreamIfaceSet == null) {
1369 cleanupUpstream();
1370 break;
1371 }
1372
1373 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1374 cleanupUpstreamInterface(removed);
1375 }
1376
1377 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1378 // This makes the call to cleanupUpstream() in the error
1379 // path for any interface neatly cleanup all the interfaces.
1380 mUpstreamIfaceSet = newUpstreamIfaceSet;
1381
1382 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001383 // Add upstream index to name mapping for the tether stats usage in the
1384 // coordinator. Although this mapping could be added by both class
1385 // Tethering and IpServer, adding mapping from IpServer guarantees that
1386 // the mapping is added before adding forwarding rules. That is because
1387 // there are different state machines in both classes. It is hard to
1388 // guarantee the link property update order between multiple state machines.
1389 // Note that both IPv4 and IPv6 interface may be added because
1390 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1391 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1392 // capability may be updated later. In that case, IPv6 interface mapping is
1393 // updated in updateUpstreamIPv6LinkProperties.
1394 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1395 final InterfaceParams upstreamIfaceParams =
1396 mDeps.getInterfaceParams(ifname);
1397 if (upstreamIfaceParams != null) {
KH Shi701c3ca2023-08-16 13:19:33 +00001398 mBpfCoordinator.maybeAddUpstreamToLookupTable(
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001399 upstreamIfaceParams.index, ifname);
1400 }
1401 }
1402
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001403 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001404 try {
markchien12c5bb82020-01-07 14:43:17 +08001405 mNetd.tetherAddForward(mIfaceName, ifname);
1406 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1407 } catch (RemoteException | ServiceSpecificException e) {
1408 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001409 cleanupUpstream();
Mark74461fc2022-12-14 08:49:40 +00001410 mLastError = TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001411 transitionTo(mInitialState);
1412 return true;
1413 }
1414 }
1415 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001416 case CMD_NEIGHBOR_EVENT:
1417 handleNeighborEvent((NeighborEvent) message.obj);
1418 break;
markchien74a4fa92019-09-09 20:50:49 +08001419 default:
1420 return false;
1421 }
1422 return true;
1423 }
1424
1425 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1426 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1427 if (mUpstreamIfaceSet != null && newIfaces != null) {
1428 return mUpstreamIfaceSet.equals(newIfaces);
1429 }
1430 return false;
1431 }
1432
1433 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1434 if (mUpstreamIfaceSet == null) return new HashSet<>();
1435
1436 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1437 removed.removeAll(newIfaces.ifnames);
1438 return removed;
1439 }
1440
1441 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1442 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1443 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1444 return added;
1445 }
1446 }
1447
1448 /**
1449 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001450 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001451 * specific state machine from its list of possible recipients of
1452 * tethering requests. The state machine itself will hang around until
1453 * the garbage collector finds it.
1454 */
1455 class UnavailableState extends State {
1456 @Override
1457 public void enter() {
KH Shi701c3ca2023-08-16 13:19:33 +00001458 // TODO: move mIpNeighborMonitor.stop() to TetheredState#exit, and trigger a neighbours
1459 // dump after starting mIpNeighborMonitor.
h.zhangd244bd02020-06-14 14:46:54 +08001460 mIpNeighborMonitor.stop();
Mark74461fc2022-12-14 08:49:40 +00001461 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001462 sendInterfaceState(STATE_UNAVAILABLE);
1463 }
1464 }
1465
markchienc9daba32020-02-12 00:19:21 +08001466 class WaitingForRestartState extends State {
1467 @Override
1468 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001469 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001470 switch (message.what) {
1471 case CMD_TETHER_UNREQUESTED:
1472 transitionTo(mInitialState);
1473 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1474 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1475 break;
1476 case CMD_INTERFACE_DOWN:
1477 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001478 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001479 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1480 break;
1481 default:
1482 return false;
1483 }
1484 return true;
1485 }
1486 }
1487
markchien74a4fa92019-09-09 20:50:49 +08001488 // Accumulate routes representing "prefixes to be assigned to the local
1489 // interface", for subsequent modification of local_network routing.
1490 private static ArrayList<RouteInfo> getLocalRoutesFor(
1491 String ifname, HashSet<IpPrefix> prefixes) {
1492 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1493 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001494 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001495 }
1496 return localRoutes;
1497 }
1498
1499 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1500 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1501 final byte[] dnsBytes = localPrefix.getRawAddress();
1502 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1503 try {
1504 return Inet6Address.getByAddress(null, dnsBytes, 0);
1505 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001506 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001507 return null;
1508 }
1509 }
1510
1511 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1512 final byte random = (byte) (new Random()).nextInt();
1513 for (int value : excluded) {
1514 if (random == value) return dflt;
1515 }
1516 return random;
1517 }
1518}