blob: 682cf59137d9e9092ab8e44613c48b0278dfd2d5 [file] [log] [blame]
markchien74a4fa92019-09-09 20:50:49 +08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net.ip;
18
markchien6cf0e552019-12-06 15:24:53 +080019import static android.net.RouteInfo.RTN_UNICAST;
Mark49649c92023-03-15 06:45:04 +000020import static android.net.TetheringManager.CONNECTIVITY_SCOPE_GLOBAL;
21import static android.net.TetheringManager.CONNECTIVITY_SCOPE_LOCAL;
Mark74461fc2022-12-14 08:49:40 +000022import static android.net.TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
23import static android.net.TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
24import static android.net.TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
25import static android.net.TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
26import static android.net.TetheringManager.TETHER_ERROR_NO_ERROR;
27import static android.net.TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
28import static android.net.TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien245352e2020-02-27 20:27:18 +080029import static android.net.TetheringManager.TetheringRequest.checkStaticAddressConfiguration;
markchien74a4fa92019-09-09 20:50:49 +080030import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
markchien74a4fa92019-09-09 20:50:49 +080031import static android.net.util.NetworkConstants.asByte;
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +090032import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080033
Chalard Jean78701642020-07-31 20:00:30 +090034import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH;
Xiao Ma1f993302023-08-09 18:55:49 +090035import static com.android.net.module.util.NetworkStackConstants.RFC7421_PREFIX_LENGTH;
Mark21502962022-12-21 06:58:23 +000036import static com.android.networkstack.tethering.TetheringConfiguration.USE_SYNC_SM;
markchien7dc1b4d2021-07-13 17:12:56 +080037import static com.android.networkstack.tethering.UpstreamNetworkState.isVcnInterface;
markchiend02f9af2021-11-04 11:26:03 +080038import static com.android.networkstack.tethering.util.PrefixUtils.asIpPrefix;
39import static com.android.networkstack.tethering.util.TetheringMessageBase.BASE_IPSERVER;
Chalard Jean78701642020-07-31 20:00:30 +090040
markchien74a4fa92019-09-09 20:50:49 +080041import android.net.INetd;
42import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080043import android.net.IpPrefix;
44import android.net.LinkAddress;
45import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090046import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080047import android.net.RouteInfo;
Chalard Jean2fb66f12023-08-25 12:50:37 +090048import android.net.RoutingCoordinatorManager;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090049import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080050import android.net.TetheringManager;
markchienf053e4b2020-03-16 21:49:48 +080051import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090052import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080053import android.net.dhcp.DhcpServerCallbacks;
54import android.net.dhcp.DhcpServingParamsParcel;
55import android.net.dhcp.DhcpServingParamsParcelExt;
Xiao Ma49889dd2020-04-03 17:01:33 +090056import android.net.dhcp.IDhcpEventCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080057import android.net.dhcp.IDhcpServer;
58import android.net.ip.RouterAdvertisementDaemon.RaParams;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090059import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080060import android.os.Message;
61import android.os.RemoteException;
62import android.os.ServiceSpecificException;
63import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080064import android.util.SparseArray;
65
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090066import androidx.annotation.NonNull;
Xiao Ma4455d6b2020-04-09 10:13:44 +090067import androidx.annotation.Nullable;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090068
KH Shi3f738fc2023-05-23 22:37:17 +080069import com.android.internal.annotations.VisibleForTesting;
markchien74a4fa92019-09-09 20:50:49 +080070import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080071import com.android.internal.util.State;
markchien932df542021-08-12 13:56:43 +080072import com.android.modules.utils.build.SdkLevel;
Patrick Rohr9f371f02022-03-04 15:14:27 +010073import com.android.net.module.util.InterfaceParams;
Chalard Jeanadcec9e2021-10-29 15:57:22 +090074import com.android.net.module.util.NetdUtils;
Chalard Jean2fb66f12023-08-25 12:50:37 +090075import com.android.net.module.util.SdkUtil.LateSdk;
Patrick Rohrb873e252022-06-16 16:38:43 -070076import com.android.net.module.util.SharedLog;
Xiao Mac81c0662022-06-17 14:58:03 +090077import com.android.net.module.util.ip.InterfaceController;
78import com.android.net.module.util.ip.IpNeighborMonitor;
79import com.android.net.module.util.ip.IpNeighborMonitor.NeighborEvent;
Hungming Chen68f1c2a2020-03-12 21:24:01 +080080import com.android.networkstack.tethering.BpfCoordinator;
Hungming Chend71c06e2020-12-21 19:39:49 +080081import com.android.networkstack.tethering.BpfCoordinator.ClientInfo;
KH Shi59ad35e2023-08-15 07:13:00 +000082import com.android.networkstack.tethering.BpfCoordinator.Ipv6DownstreamRule;
markchienc9daba32020-02-12 00:19:21 +080083import com.android.networkstack.tethering.PrivateAddressCoordinator;
markchienb961d3d2022-02-26 00:39:06 +080084import com.android.networkstack.tethering.TetheringConfiguration;
Wayne Ma6cd440f2022-03-14 18:04:33 +080085import com.android.networkstack.tethering.metrics.TetheringMetrics;
markchiend02f9af2021-11-04 11:26:03 +080086import com.android.networkstack.tethering.util.InterfaceSet;
87import com.android.networkstack.tethering.util.PrefixUtils;
Mark21502962022-12-21 06:58:23 +000088import com.android.networkstack.tethering.util.StateMachineShim;
89import com.android.networkstack.tethering.util.SyncStateMachine.StateInfo;
markchien74a4fa92019-09-09 20:50:49 +080090
91import java.net.Inet4Address;
92import java.net.Inet6Address;
markchien74a4fa92019-09-09 20:50:49 +080093import java.net.UnknownHostException;
94import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090095import java.util.Arrays;
KH Shi3f738fc2023-05-23 22:37:17 +080096import java.util.Collection;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090097import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080098import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090099import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +0800100import java.util.Objects;
101import java.util.Random;
102import java.util.Set;
103
104/**
105 * Provides the interface to IP-layer serving functionality for a given network
106 * interface, e.g. for tethering or "local-only hotspot" mode.
107 *
108 * @hide
109 */
Mark21502962022-12-21 06:58:23 +0000110public class IpServer extends StateMachineShim {
markchien74a4fa92019-09-09 20:50:49 +0800111 public static final int STATE_UNAVAILABLE = 0;
112 public static final int STATE_AVAILABLE = 1;
113 public static final int STATE_TETHERED = 2;
114 public static final int STATE_LOCAL_ONLY = 3;
115
116 /** Get string name of |state|.*/
117 public static String getStateString(int state) {
118 switch (state) {
119 case STATE_UNAVAILABLE: return "UNAVAILABLE";
120 case STATE_AVAILABLE: return "AVAILABLE";
121 case STATE_TETHERED: return "TETHERED";
122 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
123 }
124 return "UNKNOWN: " + state;
125 }
126
127 private static final byte DOUG_ADAMS = (byte) 42;
128
markchien74a4fa92019-09-09 20:50:49 +0800129 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800130 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800131
132 // TODO: have this configurable
133 private static final int DHCP_LEASE_TIME_SECS = 3600;
134
KH Shi701c3ca2023-08-16 13:19:33 +0000135 private static final int NO_UPSTREAM = 0;
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900136 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
137
markchien74a4fa92019-09-09 20:50:49 +0800138 private static final String TAG = "IpServer";
139 private static final boolean DBG = false;
140 private static final boolean VDBG = false;
141 private static final Class[] sMessageClasses = {
142 IpServer.class
143 };
144 private static final SparseArray<String> sMagicDecoderRing =
145 MessageUtils.findMessageNames(sMessageClasses);
146
147 /** IpServer callback. */
148 public static class Callback {
149 /**
150 * Notify that |who| has changed its tethering state.
151 *
152 * @param who the calling instance of IpServer
153 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800154 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800155 */
markchien9d353822019-12-16 20:15:20 +0800156 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800157
158 /**
159 * Notify that |who| has new LinkProperties.
160 *
161 * @param who the calling instance of IpServer
162 * @param newLp the new LinkProperties to report
163 */
markchien9d353822019-12-16 20:15:20 +0800164 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900165
166 /**
167 * Notify that the DHCP leases changed in one of the IpServers.
168 */
169 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800170
171 /**
172 * Request Tethering change.
173 *
174 * @param tetheringType the downstream type of this IpServer.
175 * @param enabled enable or disable tethering.
176 */
177 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800178 }
179
180 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800181 public abstract static class Dependencies {
Tyler Wear90e40632020-03-13 11:38:38 -0700182 /**
183 * Create a DadProxy instance to be used by IpServer.
184 * To support multiple tethered interfaces concurrently DAD Proxy
185 * needs to be supported per IpServer instead of per upstream.
186 */
187 public DadProxy getDadProxy(Handler handler, InterfaceParams ifParams) {
188 return new DadProxy(handler, ifParams);
189 }
190
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900191 /** Create an IpNeighborMonitor to be used by this IpServer */
192 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
193 IpNeighborMonitor.NeighborEventConsumer consumer) {
194 return new IpNeighborMonitor(handler, log, consumer);
195 }
196
markchien74a4fa92019-09-09 20:50:49 +0800197 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
198 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
199 return new RouterAdvertisementDaemon(ifParams);
200 }
201
202 /** Get |ifName|'s interface information.*/
203 public InterfaceParams getInterfaceParams(String ifName) {
204 return InterfaceParams.getByName(ifName);
205 }
206
markchien9d353822019-12-16 20:15:20 +0800207 /** Create a DhcpServer instance to be used by IpServer. */
208 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
209 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800210 }
211
markchien74a4fa92019-09-09 20:50:49 +0800212 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800213 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800214 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800215 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800216 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800217 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800218 // notification from the {@link Tethering.TetherMainSM} that it had trouble enabling IP
219 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800220 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800221 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble disabling IP
222 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800223 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800224 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble starting
225 // tethering
markchien6cf0e552019-12-06 15:24:53 +0800226 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800227 // notification from the {@link Tethering.TetherMainSM} that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800228 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800229 // notification from the {@link Tethering.TetherMainSM} that it had trouble setting the DNS
230 // forwarders
markchien6cf0e552019-12-06 15:24:53 +0800231 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800232 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800233 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800234 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800235 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900236 // new neighbor cache entry on our interface
237 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900238 // request from DHCP server that it wants to have a new prefix
239 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800240 // request from PrivateAddressCoordinator to restart tethering.
241 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
markchien74a4fa92019-09-09 20:50:49 +0800242
243 private final State mInitialState;
244 private final State mLocalHotspotState;
245 private final State mTetheredState;
246 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800247 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800248
249 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800250 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800251 @NonNull
252 private final BpfCoordinator mBpfCoordinator;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900253 // Contains null if the connectivity module is unsupported, as the routing coordinator is not
254 // available. Must use LateSdk because MessageUtils enumerates fields in this class, so it
255 // must be able to find all classes at runtime.
256 @NonNull
257 private final LateSdk<RoutingCoordinatorManager> mRoutingCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800258 private final Callback mCallback;
259 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800260 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800261
262 private final String mIfaceName;
263 private final int mInterfaceType;
264 private final LinkProperties mLinkProperties;
265 private final boolean mUsingLegacyDhcp;
markchienfb65dfe2022-02-25 23:14:58 +0800266 private final int mP2pLeasesSubnetPrefixLength;
markchien74a4fa92019-09-09 20:50:49 +0800267
268 private final Dependencies mDeps;
269
270 private int mLastError;
271 private int mServingMode;
272 private InterfaceSet mUpstreamIfaceSet; // may change over time
KH Shi701c3ca2023-08-16 13:19:33 +0000273 // mInterfaceParams can't be final now because IpServer will be created when receives
274 // WIFI_AP_STATE_CHANGED broadcasts or when it detects that the wifi interface has come up.
275 // In the latter case, the interface is not fully initialized and the MAC address might not
276 // be correct (it will be set with a randomized MAC address later).
277 // TODO: Consider create the IpServer only when tethering want to enable it, then we can
278 // make mInterfaceParams final.
markchien74a4fa92019-09-09 20:50:49 +0800279 private InterfaceParams mInterfaceParams;
280 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
281 // properties are those selected by the IPv6TetheringCoordinator and relayed
282 // to us. By comparison, mLinkProperties contains the addresses and directly
283 // connected routes that have been formed from these properties iff. we have
284 // succeeded in configuring them and are able to announce them within Router
285 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
286 private LinkProperties mLastIPv6LinkProperties;
287 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700288 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800289
290 // To be accessed only on the handler thread
291 private int mDhcpServerStartIndex = 0;
292 private IDhcpServer mDhcpServer;
293 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800294
295 private LinkAddress mStaticIpv4ServerAddr;
296 private LinkAddress mStaticIpv4ClientAddr;
297
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900298 @NonNull
299 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800300
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900301 private int mLastIPv6UpstreamIfindex = 0;
KH Shi68770342023-08-17 14:34:31 +0000302 private boolean mUpstreamSupportsBpf = false;
KH Shi3f738fc2023-05-23 22:37:17 +0800303 @NonNull
304 private Set<IpPrefix> mLastIPv6UpstreamPrefixes = Collections.emptySet();
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900305
306 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
307 public void accept(NeighborEvent e) {
308 sendMessage(CMD_NEIGHBOR_EVENT, e);
309 }
310 }
311
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900312 private final IpNeighborMonitor mIpNeighborMonitor;
313
markchienc9daba32020-02-12 00:19:21 +0800314 private LinkAddress mIpv4Address;
315
Wayne Ma6cd440f2022-03-14 18:04:33 +0800316 private final TetheringMetrics mTetheringMetrics;
Mark21502962022-12-21 06:58:23 +0000317 private final Handler mHandler;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800318
Hungming Chen5bc3af92020-05-12 19:15:24 +0800319 // TODO: Add a dependency object to pass the data members or variables from the tethering
320 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800321 public IpServer(
Mark21502962022-12-21 06:58:23 +0000322 String ifaceName, Handler handler, int interfaceType, SharedLog log,
Chalard Jean2fb66f12023-08-25 12:50:37 +0900323 INetd netd, @NonNull BpfCoordinator bpfCoordinator,
324 @Nullable LateSdk<RoutingCoordinatorManager> routingCoordinator, Callback callback,
markchienb961d3d2022-02-26 00:39:06 +0800325 TetheringConfiguration config, PrivateAddressCoordinator addressCoordinator,
Wayne Ma6cd440f2022-03-14 18:04:33 +0800326 TetheringMetrics tetheringMetrics, Dependencies deps) {
Mark21502962022-12-21 06:58:23 +0000327 super(ifaceName, USE_SYNC_SM ? null : handler.getLooper());
328 mHandler = handler;
markchien74a4fa92019-09-09 20:50:49 +0800329 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800330 mNetd = netd;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900331 mBpfCoordinator = bpfCoordinator;
332 mRoutingCoordinator = routingCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800333 mCallback = callback;
334 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
335 mIfaceName = ifaceName;
336 mInterfaceType = interfaceType;
337 mLinkProperties = new LinkProperties();
markchienb961d3d2022-02-26 00:39:06 +0800338 mUsingLegacyDhcp = config.useLegacyDhcpServer();
markchienfb65dfe2022-02-25 23:14:58 +0800339 mP2pLeasesSubnetPrefixLength = config.getP2pLeasesSubnetPrefixLength();
markchienc9daba32020-02-12 00:19:21 +0800340 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800341 mDeps = deps;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800342 mTetheringMetrics = tetheringMetrics;
markchien74a4fa92019-09-09 20:50:49 +0800343 resetLinkProperties();
Mark74461fc2022-12-14 08:49:40 +0000344 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800345 mServingMode = STATE_AVAILABLE;
346
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900347 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
348 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800349
KH Shie4d549a2023-08-28 09:57:34 +0000350 // IP neighbor monitor monitors the neighbor events for adding/removing IPv6 downstream rule
351 // per client. If BPF offload is not supported, don't start listening for neighbor events.
352 if (mBpfCoordinator.isUsingBpfOffload() && !mIpNeighborMonitor.start()) {
Hungming Chen5bc3af92020-05-12 19:15:24 +0800353 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900354 }
355
markchien74a4fa92019-09-09 20:50:49 +0800356 mInitialState = new InitialState();
357 mLocalHotspotState = new LocalHotspotState();
358 mTetheredState = new TetheredState();
359 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800360 mWaitingForRestartState = new WaitingForRestartState();
Mark21502962022-12-21 06:58:23 +0000361 final ArrayList allStates = new ArrayList<StateInfo>();
362 allStates.add(new StateInfo(mInitialState, null));
363 allStates.add(new StateInfo(mLocalHotspotState, null));
364 allStates.add(new StateInfo(mTetheredState, null));
365 allStates.add(new StateInfo(mWaitingForRestartState, mTetheredState));
366 allStates.add(new StateInfo(mUnavailableState, null));
367 addAllStates(allStates);
368 }
markchien74a4fa92019-09-09 20:50:49 +0800369
Mark21502962022-12-21 06:58:23 +0000370 private Handler getHandler() {
371 return mHandler;
372 }
373
374 /** Start IpServer state machine. */
375 public void start() {
376 start(mInitialState);
markchien74a4fa92019-09-09 20:50:49 +0800377 }
378
379 /** Interface name which IpServer served.*/
380 public String interfaceName() {
381 return mIfaceName;
382 }
383
384 /**
markchien9b4d7572019-12-25 19:40:32 +0800385 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800386 */
387 public int interfaceType() {
388 return mInterfaceType;
389 }
390
391 /** Last error from this IpServer. */
392 public int lastError() {
393 return mLastError;
394 }
395
396 /** Serving mode is the current state of IpServer state machine. */
397 public int servingMode() {
398 return mServingMode;
399 }
400
401 /** The properties of the network link which IpServer is serving. */
402 public LinkProperties linkProperties() {
403 return new LinkProperties(mLinkProperties);
404 }
405
markchienc9daba32020-02-12 00:19:21 +0800406 /** The address which IpServer is using. */
407 public LinkAddress getAddress() {
408 return mIpv4Address;
409 }
410
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900411 /**
412 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
413 * thread.
414 */
415 public List<TetheredClient> getAllLeases() {
416 return Collections.unmodifiableList(mDhcpLeases);
417 }
418
Marka5424582022-12-01 13:46:32 +0000419 /** Enable this IpServer. IpServer state machine will be tethered or localHotspot state. */
420 public void enable(final int requestedState, final TetheringRequestParcel request) {
421 sendMessage(CMD_TETHER_REQUESTED, requestedState, 0, request);
422 }
423
markchien74a4fa92019-09-09 20:50:49 +0800424 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
425 public void stop() {
426 sendMessage(CMD_INTERFACE_DOWN);
427 }
428
429 /**
430 * Tethering is canceled. IpServer state machine will be available and wait for
431 * next tethering request.
432 */
433 public void unwanted() {
434 sendMessage(CMD_TETHER_UNREQUESTED);
435 }
436
437 /** Internals. */
438
Mark49649c92023-03-15 06:45:04 +0000439 private boolean startIPv4(int scope) {
440 return configureIPv4(true, scope);
markchien74a4fa92019-09-09 20:50:49 +0800441 }
442
443 /**
444 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
445 * handler.
446 *
447 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
448 * with different implementations of the callback, to differentiate handling of success/error in
449 * each call.
450 */
451 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
452 @Override
453 public void onStatusAvailable(int statusCode) {
454 getHandler().post(() -> callback(statusCode));
455 }
456
457 public abstract void callback(int statusCode);
458
459 @Override
460 public int getInterfaceVersion() {
461 return this.VERSION;
462 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900463
464 @Override
465 public String getInterfaceHash() {
466 return this.HASH;
467 }
markchien74a4fa92019-09-09 20:50:49 +0800468 }
469
470 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
471 private final int mStartIndex;
472
473 private DhcpServerCallbacksImpl(int startIndex) {
474 mStartIndex = startIndex;
475 }
476
477 @Override
478 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
479 getHandler().post(() -> {
480 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
481 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800482 // This start request is obsolete. Explicitly stop the DHCP server to shut
483 // down its thread. When the |server| binder token goes out of scope, the
484 // garbage collector will finalize it, which causes the network stack process
485 // garbage collector to collect the server itself.
486 try {
487 server.stop(null);
488 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800489 return;
490 }
491
492 if (statusCode != STATUS_SUCCESS) {
493 mLog.e("Error obtaining DHCP server: " + statusCode);
494 handleError();
495 return;
496 }
497
498 mDhcpServer = server;
499 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900500 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800501 @Override
502 public void callback(int startStatusCode) {
503 if (startStatusCode != STATUS_SUCCESS) {
504 mLog.e("Error starting DHCP server: " + startStatusCode);
505 handleError();
506 }
507 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900508 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800509 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800510 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800511 }
512 });
513 }
514
515 private void handleError() {
Mark74461fc2022-12-14 08:49:40 +0000516 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800517 transitionTo(mInitialState);
518 }
519 }
520
Xiao Ma4455d6b2020-04-09 10:13:44 +0900521 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900522 @Override
523 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
524 final ArrayList<TetheredClient> leases = new ArrayList<>();
525 for (DhcpLeaseParcelable lease : leaseParcelables) {
526 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900527 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
528 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
529 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900530
531 final MacAddress macAddress;
532 try {
533 macAddress = MacAddress.fromBytes(lease.hwAddr);
534 } catch (IllegalArgumentException e) {
535 Log.wtf(TAG, "Invalid address received from DhcpServer: "
536 + Arrays.toString(lease.hwAddr));
537 return;
538 }
539
540 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900541 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900542 leases.add(new TetheredClient(
543 macAddress,
544 Collections.singletonList(addressInfo),
545 mInterfaceType));
546 }
547
548 getHandler().post(() -> {
549 mDhcpLeases = leases;
550 mCallback.dhcpLeasesChanged();
551 });
552 }
553
554 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900555 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
556 Objects.requireNonNull(currentPrefix);
557 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900558 }
559
560 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900561 public int getInterfaceVersion() {
562 return this.VERSION;
563 }
564
565 @Override
566 public String getInterfaceHash() throws RemoteException {
567 return this.HASH;
568 }
569 }
570
Xiao Ma4455d6b2020-04-09 10:13:44 +0900571 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
572 Objects.requireNonNull(ipv4Address);
573 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
574 }
575
576 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
577 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
578 @Nullable Inet4Address clientAddr) {
579 final boolean changePrefixOnDecline =
580 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
markchienfb65dfe2022-02-25 23:14:58 +0800581 final int subnetPrefixLength = mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
582 ? mP2pLeasesSubnetPrefixLength : 0 /* default value */;
583
Xiao Ma4455d6b2020-04-09 10:13:44 +0900584 return new DhcpServingParamsParcelExt()
585 .setDefaultRouters(defaultRouter)
586 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
587 .setDnsServers(dnsServer)
588 .setServerAddr(serverAddr)
589 .setMetered(true)
590 .setSingleClientAddr(clientAddr)
markchienfb65dfe2022-02-25 23:14:58 +0800591 .setChangePrefixOnDecline(changePrefixOnDecline)
592 .setLeasesSubnetPrefixLength(subnetPrefixLength);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900593 // TODO: also advertise link MTU
594 }
595
markchien245352e2020-02-27 20:27:18 +0800596 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800597 if (mUsingLegacyDhcp) {
598 return true;
599 }
markchien245352e2020-02-27 20:27:18 +0800600
601 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800602 final Inet4Address clientAddr = clientLinkAddr == null ? null :
603 (Inet4Address) clientLinkAddr.getAddress();
604
Xiao Ma4455d6b2020-04-09 10:13:44 +0900605 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
606 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800607 mDhcpServerStartIndex++;
608 mDeps.makeDhcpServer(
609 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
610 return true;
611 }
612
613 private void stopDhcp() {
614 // Make all previous start requests obsolete so servers are not started later
615 mDhcpServerStartIndex++;
616
617 if (mDhcpServer != null) {
618 try {
619 mDhcpServer.stop(new OnHandlerStatusCallback() {
620 @Override
621 public void callback(int statusCode) {
622 if (statusCode != STATUS_SUCCESS) {
623 mLog.e("Error stopping DHCP server: " + statusCode);
Mark74461fc2022-12-14 08:49:40 +0000624 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800625 // Not much more we can do here
626 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900627 mDhcpLeases.clear();
628 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800629 }
630 });
631 mDhcpServer = null;
632 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900633 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800634 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800635 }
636 }
637 }
638
markchien245352e2020-02-27 20:27:18 +0800639 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
640 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800641 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800642 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800643 } else {
644 stopDhcp();
645 return true;
646 }
647 }
648
649 private void stopIPv4() {
Mark49649c92023-03-15 06:45:04 +0000650 configureIPv4(false /* enabled */, CONNECTIVITY_SCOPE_GLOBAL /* not used */);
markchien74a4fa92019-09-09 20:50:49 +0800651 // NOTE: All of configureIPv4() will be refactored out of existence
652 // into calls to InterfaceController, shared with startIPv4().
653 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800654 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800655 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800656 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800657 mStaticIpv4ServerAddr = null;
658 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800659 }
660
Mark49649c92023-03-15 06:45:04 +0000661 private boolean configureIPv4(boolean enabled, int scope) {
markchien74a4fa92019-09-09 20:50:49 +0800662 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
663
markchienc9daba32020-02-12 00:19:21 +0800664 if (enabled) {
Mark49649c92023-03-15 06:45:04 +0000665 mIpv4Address = requestIpv4Address(scope, true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800666 }
667
668 if (mIpv4Address == null) {
669 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800670 return false;
markchien74a4fa92019-09-09 20:50:49 +0800671 }
672
markchien69681d62021-11-15 23:58:05 +0800673 if (shouldNotConfigureBluetoothInterface()) {
674 // Interface was already configured elsewhere, only start DHCP.
markchienc9daba32020-02-12 00:19:21 +0800675 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
676 }
677
678 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
679
markchien12c5bb82020-01-07 14:43:17 +0800680 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800681 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900682 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200683 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
684 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900685 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800686 // It is unclear whether the Bluetooth or USB stacks will manage their own
687 // state.
688 setIfaceUp = null;
689 } else {
690 setIfaceUp = enabled;
691 }
692 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
693 mLog.e("Error configuring interface");
694 if (!enabled) stopDhcp();
695 return false;
696 }
markchien74a4fa92019-09-09 20:50:49 +0800697
markchien74a4fa92019-09-09 20:50:49 +0800698 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800699 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900700 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800701 } else {
markchien12c5bb82020-01-07 14:43:17 +0800702 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900703 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800704 }
markchien245352e2020-02-27 20:27:18 +0800705 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800706 }
707
markchien69681d62021-11-15 23:58:05 +0800708 private boolean shouldNotConfigureBluetoothInterface() {
709 // Before T, bluetooth tethering configures the interface elsewhere.
710 return (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) && !SdkLevel.isAtLeastT();
711 }
712
Mark49649c92023-03-15 06:45:04 +0000713 private LinkAddress requestIpv4Address(final int scope, final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800714 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800715
markchien69681d62021-11-15 23:58:05 +0800716 if (shouldNotConfigureBluetoothInterface()) return new LinkAddress(BLUETOOTH_IFACE_ADDR);
markchienc9daba32020-02-12 00:19:21 +0800717
Mark49649c92023-03-15 06:45:04 +0000718 return mPrivateAddressCoordinator.requestDownstreamAddress(this, scope, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900719 }
720
markchien74a4fa92019-09-09 20:50:49 +0800721 private boolean startIPv6() {
722 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
723 if (mInterfaceParams == null) {
724 mLog.e("Failed to find InterfaceParams");
725 stopIPv6();
726 return false;
727 }
728
729 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
730 if (!mRaDaemon.start()) {
731 stopIPv6();
732 return false;
733 }
734
markchien932df542021-08-12 13:56:43 +0800735 if (SdkLevel.isAtLeastS()) {
Tyler Wear90e40632020-03-13 11:38:38 -0700736 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
737 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
738 }
739
markchien74a4fa92019-09-09 20:50:49 +0800740 return true;
741 }
742
743 private void stopIPv6() {
744 mInterfaceParams = null;
745 setRaParams(null);
746
747 if (mRaDaemon != null) {
748 mRaDaemon.stop();
749 mRaDaemon = null;
750 }
Tyler Wear90e40632020-03-13 11:38:38 -0700751
752 if (mDadProxy != null) {
753 mDadProxy.stop();
754 mDadProxy = null;
755 }
markchien74a4fa92019-09-09 20:50:49 +0800756 }
757
758 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
759 // LinkProperties. These have extraneous data filtered out and only the
760 // necessary prefixes included (per its prefix distribution policy).
761 //
762 // TODO: Evaluate using a data structure than is more directly suited to
763 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800764 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800765 if (mRaDaemon == null) return;
766
767 // Avoid unnecessary work on spurious updates.
768 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
769 return;
770 }
771
772 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700773 String upstreamIface = null;
774 InterfaceParams upstreamIfaceParams = null;
KH Shi701c3ca2023-08-16 13:19:33 +0000775 int upstreamIfIndex = NO_UPSTREAM;
markchien74a4fa92019-09-09 20:50:49 +0800776
777 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700778 upstreamIface = v6only.getInterfaceName();
779 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
780 if (upstreamIfaceParams != null) {
781 upstreamIfIndex = upstreamIfaceParams.index;
782 }
markchien74a4fa92019-09-09 20:50:49 +0800783 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700784 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800785 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
786
markchiend63c4f32020-05-21 17:38:28 +0800787 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800788
KH Shi3f738fc2023-05-23 22:37:17 +0800789 params.prefixes = getTetherableIpv6Prefixes(v6only);
790 for (IpPrefix prefix : params.prefixes) {
markchien74a4fa92019-09-09 20:50:49 +0800791 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
792 if (dnsServer != null) {
793 params.dnses.add(dnsServer);
794 }
795 }
796 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900797
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900798 // Add upstream index to name mapping. See the comment of the interface mapping update in
799 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
800 // timing issue. It prevents that the IPv6 capability is updated later than
801 // CMD_TETHER_CONNECTION_CHANGED.
KH Shi701c3ca2023-08-16 13:19:33 +0000802 mBpfCoordinator.maybeAddUpstreamToLookupTable(upstreamIfIndex, upstreamIface);
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900803
markchien74a4fa92019-09-09 20:50:49 +0800804 // If v6only is null, we pass in null to setRaParams(), which handles
805 // deprecation of any existing RA data.
markchien74a4fa92019-09-09 20:50:49 +0800806 setRaParams(params);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900807
KH Shi68770342023-08-17 14:34:31 +0000808 // Not support BPF on virtual upstream interface
809 final boolean upstreamSupportsBpf = upstreamIface != null && !isVcnInterface(upstreamIface);
KH Shi3f738fc2023-05-23 22:37:17 +0800810 final Set<IpPrefix> upstreamPrefixes = params != null ? params.prefixes : Set.of();
811 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamPrefixes,
812 upstreamIfIndex, upstreamPrefixes, upstreamSupportsBpf);
KH Shi68770342023-08-17 14:34:31 +0000813 mLastIPv6LinkProperties = v6only;
Tyler Wear90e40632020-03-13 11:38:38 -0700814 mLastIPv6UpstreamIfindex = upstreamIfIndex;
KH Shi3f738fc2023-05-23 22:37:17 +0800815 mLastIPv6UpstreamPrefixes = upstreamPrefixes;
KH Shi68770342023-08-17 14:34:31 +0000816 mUpstreamSupportsBpf = upstreamSupportsBpf;
Tyler Wear90e40632020-03-13 11:38:38 -0700817 if (mDadProxy != null) {
818 mDadProxy.setUpstreamIface(upstreamIfaceParams);
819 }
markchien74a4fa92019-09-09 20:50:49 +0800820 }
821
Xiao Ma4455d6b2020-04-09 10:13:44 +0900822 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900823 final int removalFailures = NetdUtils.removeRoutesFromLocalNetwork(
Xiao Ma4455d6b2020-04-09 10:13:44 +0900824 mNetd, toBeRemoved);
825 if (removalFailures > 0) {
826 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
827 removalFailures));
828 }
829
830 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
831 }
832
Chalard Jean2fb66f12023-08-25 12:50:37 +0900833 private void addInterfaceToNetwork(final int netId, @NonNull final String ifaceName) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900834 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +0900835 if (null != mRoutingCoordinator.value) {
836 // TODO : remove this call in favor of using the LocalNetworkConfiguration
837 // correctly, which will let ConnectivityService do it automatically.
838 mRoutingCoordinator.value.addInterfaceToNetwork(netId, ifaceName);
839 } else {
840 mNetd.networkAddInterface(netId, ifaceName);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900841 }
842 } catch (ServiceSpecificException | RemoteException e) {
843 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
Maciej Żenczykowski543d0d32023-10-28 02:10:52 +0000844 return;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900845 }
Chalard Jean2fb66f12023-08-25 12:50:37 +0900846 }
847
848 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
849 // It's safe to call addInterfaceToNetwork() even if
850 // the interface is already in the local_network.
851 addInterfaceToNetwork(INetd.LOCAL_NET_ID, mIfaceName);
852 try {
853 // Add routes from local network. Note that adding routes that
854 // already exist does not cause an error (EEXIST is silently ignored).
855 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
856 } catch (IllegalStateException e) {
857 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
858 return;
859 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900860
861 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
862 }
863
markchien74a4fa92019-09-09 20:50:49 +0800864 private void configureLocalIPv6Routes(
865 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
866 // [1] Remove the routes that are deprecated.
867 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900868 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800869 }
870
871 // [2] Add only the routes that have not previously been added.
872 if (newPrefixes != null && !newPrefixes.isEmpty()) {
873 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
874 if (mLastRaParams != null) {
875 addedPrefixes.removeAll(mLastRaParams.prefixes);
876 }
877
878 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900879 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800880 }
881 }
882 }
883
884 private void configureLocalIPv6Dns(
885 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
886 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
887 if (mNetd == null) {
888 if (newDnses != null) newDnses.clear();
889 mLog.e("No netd service instance available; not setting local IPv6 addresses");
890 return;
891 }
892
893 // [1] Remove deprecated local DNS IP addresses.
894 if (!deprecatedDnses.isEmpty()) {
895 for (Inet6Address dns : deprecatedDnses) {
896 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
897 mLog.e("Failed to remove local dns IP " + dns);
898 }
899
900 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
901 }
902 }
903
904 // [2] Add only the local DNS IP addresses that have not previously been added.
905 if (newDnses != null && !newDnses.isEmpty()) {
906 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
907 if (mLastRaParams != null) {
908 addedDnses.removeAll(mLastRaParams.dnses);
909 }
910
911 for (Inet6Address dns : addedDnses) {
912 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
913 mLog.e("Failed to add local dns IP " + dns);
914 newDnses.remove(dns);
915 }
916
917 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
918 }
919 }
920
921 try {
922 mNetd.tetherApplyDnsInterfaces();
923 } catch (ServiceSpecificException | RemoteException e) {
924 mLog.e("Failed to update local DNS caching server");
925 if (newDnses != null) newDnses.clear();
926 }
927 }
928
KH Shi701c3ca2023-08-16 13:19:33 +0000929 private int getInterfaceIndexForRule(int ifindex, boolean supportsBpf) {
930 return supportsBpf ? ifindex : NO_UPSTREAM;
931 }
932
KH Shi3f738fc2023-05-23 22:37:17 +0800933 // Handles updates to IPv6 forwarding rules if the upstream or its prefixes change.
934 private void updateIpv6ForwardingRules(int prevUpstreamIfindex,
935 @NonNull Set<IpPrefix> prevUpstreamPrefixes, int upstreamIfindex,
936 @NonNull Set<IpPrefix> upstreamPrefixes, boolean upstreamSupportsBpf) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900937 // If the upstream interface has changed, remove all rules and re-add them with the new
KH Shi701c3ca2023-08-16 13:19:33 +0000938 // upstream interface. If upstream is a virtual network, treated as no upstream.
KH Shi3f738fc2023-05-23 22:37:17 +0800939 if (prevUpstreamIfindex != upstreamIfindex
940 || !prevUpstreamPrefixes.equals(upstreamPrefixes)) {
KH Shi701c3ca2023-08-16 13:19:33 +0000941 mBpfCoordinator.updateAllIpv6Rules(this, this.mInterfaceParams,
KH Shi3f738fc2023-05-23 22:37:17 +0800942 getInterfaceIndexForRule(upstreamIfindex, upstreamSupportsBpf),
943 upstreamPrefixes);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900944 }
KH Shi701c3ca2023-08-16 13:19:33 +0000945 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900946
KH Shi701c3ca2023-08-16 13:19:33 +0000947 // Handles updates to IPv6 downstream rules if a neighbor event is received.
948 private void addOrRemoveIpv6Downstream(NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900949 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900950 if (e == null) return;
951 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
952 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
953 return;
954 }
955
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900956 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
KH Shi59ad35e2023-08-15 07:13:00 +0000957 // Do this here instead of in the Ipv6DownstreamRule constructor to ensure that we
958 // never add rules with a null MAC, only delete them.
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900959 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
KH Shi701c3ca2023-08-16 13:19:33 +0000960 Ipv6DownstreamRule rule = new Ipv6DownstreamRule(
961 getInterfaceIndexForRule(mLastIPv6UpstreamIfindex, mUpstreamSupportsBpf),
962 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900963 if (e.isValid()) {
KH Shie4d549a2023-08-28 09:57:34 +0000964 mBpfCoordinator.addIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900965 } else {
KH Shie4d549a2023-08-28 09:57:34 +0000966 mBpfCoordinator.removeIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900967 }
968 }
969
Hungming Chend71c06e2020-12-21 19:39:49 +0800970 // TODO: consider moving into BpfCoordinator.
971 private void updateClientInfoIpv4(NeighborEvent e) {
Hungming Chend71c06e2020-12-21 19:39:49 +0800972 if (e == null) return;
973 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
974 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
975 return;
976 }
977
978 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
979 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
980 // IpServer never add clients with a null MAC, only delete them.
981 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
982 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
983 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
984 if (e.isValid()) {
985 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
986 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +0800987 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
988 }
989 }
990
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900991 private void handleNeighborEvent(NeighborEvent e) {
992 if (mInterfaceParams != null
993 && mInterfaceParams.index == e.ifindex
994 && mInterfaceParams.hasMacAddress) {
KH Shi701c3ca2023-08-16 13:19:33 +0000995 addOrRemoveIpv6Downstream(e);
Hungming Chend71c06e2020-12-21 19:39:49 +0800996 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900997 }
998 }
999
markchiend63c4f32020-05-21 17:38:28 +08001000 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001001 try {
1002 int upstreamHopLimit = Integer.parseUnsignedInt(
1003 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001004 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001005 // Cap the hop limit to 255.
1006 return (byte) Integer.min(upstreamHopLimit, 255);
1007 } catch (Exception e) {
1008 mLog.e("Failed to find upstream interface hop limit", e);
1009 }
1010 return RaParams.DEFAULT_HOPLIMIT;
1011 }
1012
1013 private void setRaParams(RaParams newParams) {
1014 if (mRaDaemon != null) {
1015 final RaParams deprecatedParams =
1016 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1017
1018 configureLocalIPv6Routes(deprecatedParams.prefixes,
1019 (newParams != null) ? newParams.prefixes : null);
1020
1021 configureLocalIPv6Dns(deprecatedParams.dnses,
1022 (newParams != null) ? newParams.dnses : null);
1023
1024 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1025 }
1026
1027 mLastRaParams = newParams;
1028 }
1029
markchien21021ef2021-06-01 10:58:04 +08001030 private void maybeLogMessage(State state, int what) {
1031 switch (what) {
1032 // Suppress some CMD_* to avoid log flooding.
1033 case CMD_IPV6_TETHER_UPDATE:
1034 case CMD_NEIGHBOR_EVENT:
1035 break;
1036 default:
1037 mLog.log(state.getName() + " got "
1038 + sMagicDecoderRing.get(what, Integer.toString(what)));
1039 }
markchien74a4fa92019-09-09 20:50:49 +08001040 }
1041
1042 private void sendInterfaceState(int newInterfaceState) {
1043 mServingMode = newInterfaceState;
1044 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1045 sendLinkProperties();
1046 }
1047
1048 private void sendLinkProperties() {
1049 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1050 }
1051
1052 private void resetLinkProperties() {
1053 mLinkProperties.clear();
1054 mLinkProperties.setInterfaceName(mIfaceName);
1055 }
1056
markchienf053e4b2020-03-16 21:49:48 +08001057 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001058 // Ignore static address configuration if they are invalid or null. In theory, static
1059 // addresses should not be invalid here because TetheringManager do not allow caller to
1060 // specify invalid static address configuration.
1061 if (request == null || request.localIPv4Address == null
1062 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1063 request.localIPv4Address, request.staticClientAddress)) {
1064 return;
1065 }
markchienf053e4b2020-03-16 21:49:48 +08001066
1067 mStaticIpv4ServerAddr = request.localIPv4Address;
1068 mStaticIpv4ClientAddr = request.staticClientAddress;
1069 }
1070
markchien74a4fa92019-09-09 20:50:49 +08001071 class InitialState extends State {
1072 @Override
1073 public void enter() {
1074 sendInterfaceState(STATE_AVAILABLE);
1075 }
1076
1077 @Override
1078 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001079 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001080 switch (message.what) {
1081 case CMD_TETHER_REQUESTED:
Mark74461fc2022-12-14 08:49:40 +00001082 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001083 switch (message.arg1) {
1084 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001085 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001086 transitionTo(mLocalHotspotState);
1087 break;
1088 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001089 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001090 transitionTo(mTetheredState);
1091 break;
1092 default:
1093 mLog.e("Invalid tethering interface serving state specified.");
1094 }
1095 break;
1096 case CMD_INTERFACE_DOWN:
1097 transitionTo(mUnavailableState);
1098 break;
markchien74a4fa92019-09-09 20:50:49 +08001099 default:
1100 return NOT_HANDLED;
1101 }
1102 return HANDLED;
1103 }
1104 }
1105
Hungming Chen46c30b12020-10-15 17:25:36 +08001106 private void startConntrackMonitoring() {
1107 mBpfCoordinator.startMonitoring(this);
1108 }
1109
1110 private void stopConntrackMonitoring() {
1111 mBpfCoordinator.stopMonitoring(this);
1112 }
1113
Mark3ec851e2023-05-19 08:50:38 +00001114 abstract class BaseServingState extends State {
1115 private final int mDesiredInterfaceState;
1116
1117 BaseServingState(int interfaceState) {
1118 mDesiredInterfaceState = interfaceState;
1119 }
1120
markchien74a4fa92019-09-09 20:50:49 +08001121 @Override
1122 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001123 startConntrackMonitoring();
1124
Mark3ec851e2023-05-19 08:50:38 +00001125 startServingInterface();
1126
1127 if (mLastError != TETHER_ERROR_NO_ERROR) {
1128 transitionTo(mInitialState);
1129 }
1130
1131 if (DBG) Log.d(TAG, getStateString(mDesiredInterfaceState) + " serve " + mIfaceName);
1132 sendInterfaceState(mDesiredInterfaceState);
1133 }
1134
Mark49649c92023-03-15 06:45:04 +00001135 private int getScope() {
1136 if (mDesiredInterfaceState == STATE_TETHERED) {
1137 return CONNECTIVITY_SCOPE_GLOBAL;
1138 }
1139
1140 return CONNECTIVITY_SCOPE_LOCAL;
1141 }
1142
Mark3ec851e2023-05-19 08:50:38 +00001143 private void startServingInterface() {
Mark49649c92023-03-15 06:45:04 +00001144 if (!startIPv4(getScope())) {
Mark74461fc2022-12-14 08:49:40 +00001145 mLastError = TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001146 return;
1147 }
1148
1149 try {
markchienc9daba32020-02-12 00:19:21 +08001150 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001151 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001152 mLog.e("Error Tethering", e);
Mark74461fc2022-12-14 08:49:40 +00001153 mLastError = TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001154 return;
1155 }
1156
1157 if (!startIPv6()) {
1158 mLog.e("Failed to startIPv6");
1159 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1160 return;
1161 }
1162 }
1163
1164 @Override
1165 public void exit() {
1166 // Note that at this point, we're leaving the tethered state. We can fail any
1167 // of these operations, but it doesn't really change that we have to try them
1168 // all in sequence.
1169 stopIPv6();
1170
1171 try {
markchien12c5bb82020-01-07 14:43:17 +08001172 NetdUtils.untetherInterface(mNetd, mIfaceName);
1173 } catch (RemoteException | ServiceSpecificException e) {
Mark74461fc2022-12-14 08:49:40 +00001174 mLastError = TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001175 mLog.e("Failed to untether interface: " + e);
1176 }
1177
1178 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001179 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001180
1181 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001182
1183 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1184 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001185 }
1186
1187 @Override
1188 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001189 switch (message.what) {
1190 case CMD_TETHER_UNREQUESTED:
1191 transitionTo(mInitialState);
1192 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1193 break;
1194 case CMD_INTERFACE_DOWN:
1195 transitionTo(mUnavailableState);
1196 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1197 break;
1198 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001199 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001200 sendLinkProperties();
1201 break;
1202 case CMD_IP_FORWARDING_ENABLE_ERROR:
1203 case CMD_IP_FORWARDING_DISABLE_ERROR:
1204 case CMD_START_TETHERING_ERROR:
1205 case CMD_STOP_TETHERING_ERROR:
1206 case CMD_SET_DNS_FORWARDERS_ERROR:
Mark74461fc2022-12-14 08:49:40 +00001207 mLastError = TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001208 transitionTo(mInitialState);
1209 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001210 case CMD_NEW_PREFIX_REQUEST:
1211 handleNewPrefixRequest((IpPrefix) message.obj);
1212 break;
markchienc9daba32020-02-12 00:19:21 +08001213 case CMD_NOTIFY_PREFIX_CONFLICT:
1214 mLog.i("restart tethering: " + mInterfaceType);
1215 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1216 transitionTo(mWaitingForRestartState);
1217 break;
markchien74a4fa92019-09-09 20:50:49 +08001218 default:
1219 return false;
1220 }
1221 return true;
1222 }
Mark3ec851e2023-05-19 08:50:38 +00001223
1224 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
1225 if (!currentPrefix.contains(mIpv4Address.getAddress())
1226 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
1227 Log.e(TAG, "Invalid prefix: " + currentPrefix);
1228 return;
1229 }
1230
1231 final LinkAddress deprecatedLinkAddress = mIpv4Address;
Mark49649c92023-03-15 06:45:04 +00001232 mIpv4Address = requestIpv4Address(getScope(), false);
Mark3ec851e2023-05-19 08:50:38 +00001233 if (mIpv4Address == null) {
1234 mLog.e("Fail to request a new downstream prefix");
1235 return;
1236 }
1237 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
1238
1239 // Add new IPv4 address on the interface.
1240 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1241 mLog.e("Failed to add new IP " + srvAddr);
1242 return;
1243 }
1244
1245 // Remove deprecated routes from local network.
1246 removeRoutesFromLocalNetwork(
1247 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1248 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1249
1250 // Add new routes to local network.
1251 addRoutesToLocalNetwork(
1252 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1253 mLinkProperties.addLinkAddress(mIpv4Address);
1254
1255 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1256 // listen on the interface configured with new IPv4 address, that results DNS validation
1257 // failure of downstream client even if appropriate routes have been configured.
1258 try {
1259 mNetd.tetherApplyDnsInterfaces();
1260 } catch (ServiceSpecificException | RemoteException e) {
1261 mLog.e("Failed to update local DNS caching server");
1262 return;
1263 }
1264 sendLinkProperties();
1265
1266 // Notify DHCP server that new prefix/route has been applied on IpServer.
1267 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1268 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1269 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1270 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1271 try {
1272 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1273 @Override
1274 public void callback(int statusCode) {
1275 if (statusCode != STATUS_SUCCESS) {
1276 mLog.e("Error updating DHCP serving params: " + statusCode);
1277 }
1278 }
1279 });
1280 } catch (RemoteException e) {
1281 mLog.e("Error updating DHCP serving params", e);
1282 }
1283 }
markchien74a4fa92019-09-09 20:50:49 +08001284 }
1285
1286 // Handling errors in BaseServingState.enter() by transitioning is
1287 // problematic because transitioning during a multi-state jump yields
1288 // a Log.wtf(). Ultimately, there should be only one ServingState,
1289 // and forwarding and NAT rules should be handled by a coordinating
1290 // functional element outside of IpServer.
1291 class LocalHotspotState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001292 LocalHotspotState() {
1293 super(STATE_LOCAL_ONLY);
markchien74a4fa92019-09-09 20:50:49 +08001294 }
1295
1296 @Override
1297 public boolean processMessage(Message message) {
1298 if (super.processMessage(message)) return true;
1299
markchien21021ef2021-06-01 10:58:04 +08001300 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001301 switch (message.what) {
1302 case CMD_TETHER_REQUESTED:
1303 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1304 break;
1305 case CMD_TETHER_CONNECTION_CHANGED:
1306 // Ignored in local hotspot state.
1307 break;
1308 default:
1309 return false;
1310 }
1311 return true;
1312 }
1313 }
1314
1315 // Handling errors in BaseServingState.enter() by transitioning is
1316 // problematic because transitioning during a multi-state jump yields
1317 // a Log.wtf(). Ultimately, there should be only one ServingState,
1318 // and forwarding and NAT rules should be handled by a coordinating
1319 // functional element outside of IpServer.
1320 class TetheredState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001321 TetheredState() {
1322 super(STATE_TETHERED);
markchien74a4fa92019-09-09 20:50:49 +08001323 }
1324
1325 @Override
1326 public void exit() {
1327 cleanupUpstream();
KH Shi701c3ca2023-08-16 13:19:33 +00001328 mBpfCoordinator.clearAllIpv6Rules(IpServer.this);
markchien74a4fa92019-09-09 20:50:49 +08001329 super.exit();
1330 }
1331
Hungming Chena6e78692021-02-08 17:15:35 +08001332 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1333 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1334 // and behaviour. While upstream is switching from offload supported interface to
1335 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1336 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1337 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1338 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1339 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1340 // in the state machine. Once there is any case out whish is not covered by previous cases,
1341 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001342 private void cleanupUpstream() {
1343 if (mUpstreamIfaceSet == null) return;
1344
1345 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1346 mUpstreamIfaceSet = null;
KH Shi701c3ca2023-08-16 13:19:33 +00001347 mBpfCoordinator.updateAllIpv6Rules(
KH Shi3f738fc2023-05-23 22:37:17 +08001348 IpServer.this, IpServer.this.mInterfaceParams, NO_UPSTREAM, Set.of());
markchien74a4fa92019-09-09 20:50:49 +08001349 }
1350
1351 private void cleanupUpstreamInterface(String upstreamIface) {
1352 // Note that we don't care about errors here.
1353 // Sometimes interfaces are gone before we get
1354 // to remove their rules, which generates errors.
1355 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001356 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
Maciej Żenczykowski543d0d32023-10-28 02:10:52 +00001357 try {
1358 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1359 } catch (RemoteException | ServiceSpecificException e) {
1360 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
1361 }
1362 try {
1363 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1364 } catch (RemoteException | ServiceSpecificException e) {
1365 mLog.e("Exception in disableNat: " + e.toString());
1366 }
markchien74a4fa92019-09-09 20:50:49 +08001367 }
1368
1369 @Override
1370 public boolean processMessage(Message message) {
1371 if (super.processMessage(message)) return true;
1372
markchien21021ef2021-06-01 10:58:04 +08001373 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001374 switch (message.what) {
1375 case CMD_TETHER_REQUESTED:
1376 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1377 break;
1378 case CMD_TETHER_CONNECTION_CHANGED:
1379 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1380 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1381 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1382 break;
1383 }
1384
1385 if (newUpstreamIfaceSet == null) {
1386 cleanupUpstream();
1387 break;
1388 }
1389
1390 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1391 cleanupUpstreamInterface(removed);
1392 }
1393
1394 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1395 // This makes the call to cleanupUpstream() in the error
1396 // path for any interface neatly cleanup all the interfaces.
1397 mUpstreamIfaceSet = newUpstreamIfaceSet;
1398
1399 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001400 // Add upstream index to name mapping for the tether stats usage in the
1401 // coordinator. Although this mapping could be added by both class
1402 // Tethering and IpServer, adding mapping from IpServer guarantees that
1403 // the mapping is added before adding forwarding rules. That is because
1404 // there are different state machines in both classes. It is hard to
1405 // guarantee the link property update order between multiple state machines.
1406 // Note that both IPv4 and IPv6 interface may be added because
1407 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1408 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1409 // capability may be updated later. In that case, IPv6 interface mapping is
1410 // updated in updateUpstreamIPv6LinkProperties.
1411 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1412 final InterfaceParams upstreamIfaceParams =
1413 mDeps.getInterfaceParams(ifname);
1414 if (upstreamIfaceParams != null) {
KH Shi701c3ca2023-08-16 13:19:33 +00001415 mBpfCoordinator.maybeAddUpstreamToLookupTable(
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001416 upstreamIfaceParams.index, ifname);
1417 }
1418 }
1419
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001420 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001421 try {
Maciej Żenczykowski543d0d32023-10-28 02:10:52 +00001422 mNetd.tetherAddForward(mIfaceName, ifname);
1423 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
markchien12c5bb82020-01-07 14:43:17 +08001424 } catch (RemoteException | ServiceSpecificException e) {
Maciej Żenczykowski543d0d32023-10-28 02:10:52 +00001425 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001426 cleanupUpstream();
Mark74461fc2022-12-14 08:49:40 +00001427 mLastError = TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001428 transitionTo(mInitialState);
1429 return true;
1430 }
1431 }
1432 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001433 case CMD_NEIGHBOR_EVENT:
1434 handleNeighborEvent((NeighborEvent) message.obj);
1435 break;
markchien74a4fa92019-09-09 20:50:49 +08001436 default:
1437 return false;
1438 }
1439 return true;
1440 }
1441
1442 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1443 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1444 if (mUpstreamIfaceSet != null && newIfaces != null) {
1445 return mUpstreamIfaceSet.equals(newIfaces);
1446 }
1447 return false;
1448 }
1449
1450 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1451 if (mUpstreamIfaceSet == null) return new HashSet<>();
1452
1453 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1454 removed.removeAll(newIfaces.ifnames);
1455 return removed;
1456 }
1457
1458 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1459 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1460 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1461 return added;
1462 }
1463 }
1464
1465 /**
1466 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001467 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001468 * specific state machine from its list of possible recipients of
1469 * tethering requests. The state machine itself will hang around until
1470 * the garbage collector finds it.
1471 */
1472 class UnavailableState extends State {
1473 @Override
1474 public void enter() {
KH Shi701c3ca2023-08-16 13:19:33 +00001475 // TODO: move mIpNeighborMonitor.stop() to TetheredState#exit, and trigger a neighbours
1476 // dump after starting mIpNeighborMonitor.
h.zhangd244bd02020-06-14 14:46:54 +08001477 mIpNeighborMonitor.stop();
Mark74461fc2022-12-14 08:49:40 +00001478 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001479 sendInterfaceState(STATE_UNAVAILABLE);
1480 }
1481 }
1482
markchienc9daba32020-02-12 00:19:21 +08001483 class WaitingForRestartState extends State {
1484 @Override
1485 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001486 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001487 switch (message.what) {
1488 case CMD_TETHER_UNREQUESTED:
1489 transitionTo(mInitialState);
1490 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1491 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1492 break;
1493 case CMD_INTERFACE_DOWN:
1494 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001495 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001496 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1497 break;
1498 default:
1499 return false;
1500 }
1501 return true;
1502 }
1503 }
1504
markchien74a4fa92019-09-09 20:50:49 +08001505 // Accumulate routes representing "prefixes to be assigned to the local
1506 // interface", for subsequent modification of local_network routing.
1507 private static ArrayList<RouteInfo> getLocalRoutesFor(
1508 String ifname, HashSet<IpPrefix> prefixes) {
1509 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1510 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001511 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001512 }
1513 return localRoutes;
1514 }
1515
1516 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1517 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1518 final byte[] dnsBytes = localPrefix.getRawAddress();
1519 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1520 try {
1521 return Inet6Address.getByAddress(null, dnsBytes, 0);
1522 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001523 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001524 return null;
1525 }
1526 }
1527
1528 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1529 final byte random = (byte) (new Random()).nextInt();
1530 for (int value : excluded) {
1531 if (random == value) return dflt;
1532 }
1533 return random;
1534 }
KH Shi3f738fc2023-05-23 22:37:17 +08001535
1536 /** Get IPv6 prefixes from LinkProperties */
1537 @NonNull
1538 @VisibleForTesting
1539 static HashSet<IpPrefix> getTetherableIpv6Prefixes(@NonNull Collection<LinkAddress> addrs) {
1540 final HashSet<IpPrefix> prefixes = new HashSet<>();
1541 for (LinkAddress linkAddr : addrs) {
1542 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
1543 prefixes.add(new IpPrefix(linkAddr.getAddress(), RFC7421_PREFIX_LENGTH));
1544 }
1545 return prefixes;
1546 }
1547
1548 @NonNull
1549 private HashSet<IpPrefix> getTetherableIpv6Prefixes(@NonNull LinkProperties lp) {
1550 return getTetherableIpv6Prefixes(lp.getLinkAddresses());
1551 }
markchien74a4fa92019-09-09 20:50:49 +08001552}