blob: f275d4911e73373191c5bc59e12c93f25ddc50a7 [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;
Mark50eef832023-09-19 06:56:14 +0000242 public static final int CMD_SERVICE_FAILED_TO_START = BASE_IPSERVER + 14;
markchien74a4fa92019-09-09 20:50:49 +0800243
244 private final State mInitialState;
245 private final State mLocalHotspotState;
246 private final State mTetheredState;
247 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800248 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800249
250 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800251 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800252 @NonNull
253 private final BpfCoordinator mBpfCoordinator;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900254 // Contains null if the connectivity module is unsupported, as the routing coordinator is not
255 // available. Must use LateSdk because MessageUtils enumerates fields in this class, so it
256 // must be able to find all classes at runtime.
257 @NonNull
258 private final LateSdk<RoutingCoordinatorManager> mRoutingCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800259 private final Callback mCallback;
260 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800261 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800262
263 private final String mIfaceName;
264 private final int mInterfaceType;
265 private final LinkProperties mLinkProperties;
266 private final boolean mUsingLegacyDhcp;
markchienfb65dfe2022-02-25 23:14:58 +0800267 private final int mP2pLeasesSubnetPrefixLength;
markchien74a4fa92019-09-09 20:50:49 +0800268
269 private final Dependencies mDeps;
270
271 private int mLastError;
272 private int mServingMode;
273 private InterfaceSet mUpstreamIfaceSet; // may change over time
KH Shi701c3ca2023-08-16 13:19:33 +0000274 // mInterfaceParams can't be final now because IpServer will be created when receives
275 // WIFI_AP_STATE_CHANGED broadcasts or when it detects that the wifi interface has come up.
276 // In the latter case, the interface is not fully initialized and the MAC address might not
277 // be correct (it will be set with a randomized MAC address later).
278 // TODO: Consider create the IpServer only when tethering want to enable it, then we can
279 // make mInterfaceParams final.
markchien74a4fa92019-09-09 20:50:49 +0800280 private InterfaceParams mInterfaceParams;
281 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
282 // properties are those selected by the IPv6TetheringCoordinator and relayed
283 // to us. By comparison, mLinkProperties contains the addresses and directly
284 // connected routes that have been formed from these properties iff. we have
285 // succeeded in configuring them and are able to announce them within Router
286 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
287 private LinkProperties mLastIPv6LinkProperties;
288 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700289 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800290
291 // To be accessed only on the handler thread
292 private int mDhcpServerStartIndex = 0;
293 private IDhcpServer mDhcpServer;
294 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800295
296 private LinkAddress mStaticIpv4ServerAddr;
297 private LinkAddress mStaticIpv4ClientAddr;
298
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900299 @NonNull
300 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800301
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900302 private int mLastIPv6UpstreamIfindex = 0;
KH Shi68770342023-08-17 14:34:31 +0000303 private boolean mUpstreamSupportsBpf = false;
KH Shi3f738fc2023-05-23 22:37:17 +0800304 @NonNull
305 private Set<IpPrefix> mLastIPv6UpstreamPrefixes = Collections.emptySet();
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900306
307 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
308 public void accept(NeighborEvent e) {
309 sendMessage(CMD_NEIGHBOR_EVENT, e);
310 }
311 }
312
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900313 private final IpNeighborMonitor mIpNeighborMonitor;
314
markchienc9daba32020-02-12 00:19:21 +0800315 private LinkAddress mIpv4Address;
316
Wayne Ma6cd440f2022-03-14 18:04:33 +0800317 private final TetheringMetrics mTetheringMetrics;
Mark21502962022-12-21 06:58:23 +0000318 private final Handler mHandler;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800319
Hungming Chen5bc3af92020-05-12 19:15:24 +0800320 // TODO: Add a dependency object to pass the data members or variables from the tethering
321 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800322 public IpServer(
Mark21502962022-12-21 06:58:23 +0000323 String ifaceName, Handler handler, int interfaceType, SharedLog log,
Chalard Jean2fb66f12023-08-25 12:50:37 +0900324 INetd netd, @NonNull BpfCoordinator bpfCoordinator,
325 @Nullable LateSdk<RoutingCoordinatorManager> routingCoordinator, Callback callback,
markchienb961d3d2022-02-26 00:39:06 +0800326 TetheringConfiguration config, PrivateAddressCoordinator addressCoordinator,
Wayne Ma6cd440f2022-03-14 18:04:33 +0800327 TetheringMetrics tetheringMetrics, Dependencies deps) {
Mark21502962022-12-21 06:58:23 +0000328 super(ifaceName, USE_SYNC_SM ? null : handler.getLooper());
329 mHandler = handler;
markchien74a4fa92019-09-09 20:50:49 +0800330 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800331 mNetd = netd;
Chalard Jean2fb66f12023-08-25 12:50:37 +0900332 mBpfCoordinator = bpfCoordinator;
333 mRoutingCoordinator = routingCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800334 mCallback = callback;
335 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
336 mIfaceName = ifaceName;
337 mInterfaceType = interfaceType;
338 mLinkProperties = new LinkProperties();
markchienb961d3d2022-02-26 00:39:06 +0800339 mUsingLegacyDhcp = config.useLegacyDhcpServer();
markchienfb65dfe2022-02-25 23:14:58 +0800340 mP2pLeasesSubnetPrefixLength = config.getP2pLeasesSubnetPrefixLength();
markchienc9daba32020-02-12 00:19:21 +0800341 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800342 mDeps = deps;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800343 mTetheringMetrics = tetheringMetrics;
markchien74a4fa92019-09-09 20:50:49 +0800344 resetLinkProperties();
Mark74461fc2022-12-14 08:49:40 +0000345 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800346 mServingMode = STATE_AVAILABLE;
347
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900348 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
349 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800350
KH Shie4d549a2023-08-28 09:57:34 +0000351 // IP neighbor monitor monitors the neighbor events for adding/removing IPv6 downstream rule
352 // per client. If BPF offload is not supported, don't start listening for neighbor events.
353 if (mBpfCoordinator.isUsingBpfOffload() && !mIpNeighborMonitor.start()) {
Hungming Chen5bc3af92020-05-12 19:15:24 +0800354 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900355 }
356
markchien74a4fa92019-09-09 20:50:49 +0800357 mInitialState = new InitialState();
358 mLocalHotspotState = new LocalHotspotState();
359 mTetheredState = new TetheredState();
360 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800361 mWaitingForRestartState = new WaitingForRestartState();
Mark21502962022-12-21 06:58:23 +0000362 final ArrayList allStates = new ArrayList<StateInfo>();
363 allStates.add(new StateInfo(mInitialState, null));
364 allStates.add(new StateInfo(mLocalHotspotState, null));
365 allStates.add(new StateInfo(mTetheredState, null));
366 allStates.add(new StateInfo(mWaitingForRestartState, mTetheredState));
367 allStates.add(new StateInfo(mUnavailableState, null));
368 addAllStates(allStates);
369 }
markchien74a4fa92019-09-09 20:50:49 +0800370
Mark21502962022-12-21 06:58:23 +0000371 private Handler getHandler() {
372 return mHandler;
373 }
374
375 /** Start IpServer state machine. */
376 public void start() {
377 start(mInitialState);
markchien74a4fa92019-09-09 20:50:49 +0800378 }
379
380 /** Interface name which IpServer served.*/
381 public String interfaceName() {
382 return mIfaceName;
383 }
384
385 /**
markchien9b4d7572019-12-25 19:40:32 +0800386 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800387 */
388 public int interfaceType() {
389 return mInterfaceType;
390 }
391
392 /** Last error from this IpServer. */
393 public int lastError() {
394 return mLastError;
395 }
396
397 /** Serving mode is the current state of IpServer state machine. */
398 public int servingMode() {
399 return mServingMode;
400 }
401
402 /** The properties of the network link which IpServer is serving. */
403 public LinkProperties linkProperties() {
404 return new LinkProperties(mLinkProperties);
405 }
406
markchienc9daba32020-02-12 00:19:21 +0800407 /** The address which IpServer is using. */
408 public LinkAddress getAddress() {
409 return mIpv4Address;
410 }
411
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900412 /**
413 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
414 * thread.
415 */
416 public List<TetheredClient> getAllLeases() {
417 return Collections.unmodifiableList(mDhcpLeases);
418 }
419
Marka5424582022-12-01 13:46:32 +0000420 /** Enable this IpServer. IpServer state machine will be tethered or localHotspot state. */
421 public void enable(final int requestedState, final TetheringRequestParcel request) {
422 sendMessage(CMD_TETHER_REQUESTED, requestedState, 0, request);
423 }
424
markchien74a4fa92019-09-09 20:50:49 +0800425 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
426 public void stop() {
427 sendMessage(CMD_INTERFACE_DOWN);
428 }
429
430 /**
431 * Tethering is canceled. IpServer state machine will be available and wait for
432 * next tethering request.
433 */
434 public void unwanted() {
435 sendMessage(CMD_TETHER_UNREQUESTED);
436 }
437
438 /** Internals. */
439
Mark49649c92023-03-15 06:45:04 +0000440 private boolean startIPv4(int scope) {
441 return configureIPv4(true, scope);
markchien74a4fa92019-09-09 20:50:49 +0800442 }
443
444 /**
445 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
446 * handler.
447 *
448 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
449 * with different implementations of the callback, to differentiate handling of success/error in
450 * each call.
451 */
452 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
453 @Override
454 public void onStatusAvailable(int statusCode) {
455 getHandler().post(() -> callback(statusCode));
456 }
457
458 public abstract void callback(int statusCode);
459
460 @Override
461 public int getInterfaceVersion() {
462 return this.VERSION;
463 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900464
465 @Override
466 public String getInterfaceHash() {
467 return this.HASH;
468 }
markchien74a4fa92019-09-09 20:50:49 +0800469 }
470
471 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
472 private final int mStartIndex;
473
474 private DhcpServerCallbacksImpl(int startIndex) {
475 mStartIndex = startIndex;
476 }
477
478 @Override
479 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
480 getHandler().post(() -> {
481 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
482 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800483 // This start request is obsolete. Explicitly stop the DHCP server to shut
484 // down its thread. When the |server| binder token goes out of scope, the
485 // garbage collector will finalize it, which causes the network stack process
486 // garbage collector to collect the server itself.
487 try {
488 server.stop(null);
489 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800490 return;
491 }
492
493 if (statusCode != STATUS_SUCCESS) {
494 mLog.e("Error obtaining DHCP server: " + statusCode);
495 handleError();
496 return;
497 }
498
499 mDhcpServer = server;
500 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900501 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800502 @Override
503 public void callback(int startStatusCode) {
504 if (startStatusCode != STATUS_SUCCESS) {
505 mLog.e("Error starting DHCP server: " + startStatusCode);
506 handleError();
507 }
508 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900509 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800510 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800511 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800512 }
513 });
514 }
515
516 private void handleError() {
Mark74461fc2022-12-14 08:49:40 +0000517 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
Markbe99f862022-12-21 16:39:23 +0000518 if (USE_SYNC_SM) {
519 sendMessage(CMD_SERVICE_FAILED_TO_START, TETHER_ERROR_DHCPSERVER_ERROR);
520 } else {
521 sendMessageAtFrontOfQueueToAsyncSM(CMD_SERVICE_FAILED_TO_START,
522 TETHER_ERROR_DHCPSERVER_ERROR);
523 }
markchien74a4fa92019-09-09 20:50:49 +0800524 }
525 }
526
Xiao Ma4455d6b2020-04-09 10:13:44 +0900527 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900528 @Override
529 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
530 final ArrayList<TetheredClient> leases = new ArrayList<>();
531 for (DhcpLeaseParcelable lease : leaseParcelables) {
532 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900533 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
534 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
535 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900536
537 final MacAddress macAddress;
538 try {
539 macAddress = MacAddress.fromBytes(lease.hwAddr);
540 } catch (IllegalArgumentException e) {
541 Log.wtf(TAG, "Invalid address received from DhcpServer: "
542 + Arrays.toString(lease.hwAddr));
543 return;
544 }
545
546 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900547 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900548 leases.add(new TetheredClient(
549 macAddress,
550 Collections.singletonList(addressInfo),
551 mInterfaceType));
552 }
553
554 getHandler().post(() -> {
555 mDhcpLeases = leases;
556 mCallback.dhcpLeasesChanged();
557 });
558 }
559
560 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900561 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
562 Objects.requireNonNull(currentPrefix);
563 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900564 }
565
566 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900567 public int getInterfaceVersion() {
568 return this.VERSION;
569 }
570
571 @Override
572 public String getInterfaceHash() throws RemoteException {
573 return this.HASH;
574 }
575 }
576
Xiao Ma4455d6b2020-04-09 10:13:44 +0900577 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
578 Objects.requireNonNull(ipv4Address);
579 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
580 }
581
582 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
583 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
584 @Nullable Inet4Address clientAddr) {
585 final boolean changePrefixOnDecline =
586 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
markchienfb65dfe2022-02-25 23:14:58 +0800587 final int subnetPrefixLength = mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
588 ? mP2pLeasesSubnetPrefixLength : 0 /* default value */;
589
Xiao Ma4455d6b2020-04-09 10:13:44 +0900590 return new DhcpServingParamsParcelExt()
591 .setDefaultRouters(defaultRouter)
592 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
593 .setDnsServers(dnsServer)
594 .setServerAddr(serverAddr)
595 .setMetered(true)
596 .setSingleClientAddr(clientAddr)
markchienfb65dfe2022-02-25 23:14:58 +0800597 .setChangePrefixOnDecline(changePrefixOnDecline)
598 .setLeasesSubnetPrefixLength(subnetPrefixLength);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900599 // TODO: also advertise link MTU
600 }
601
markchien245352e2020-02-27 20:27:18 +0800602 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800603 if (mUsingLegacyDhcp) {
604 return true;
605 }
markchien245352e2020-02-27 20:27:18 +0800606
607 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800608 final Inet4Address clientAddr = clientLinkAddr == null ? null :
609 (Inet4Address) clientLinkAddr.getAddress();
610
Xiao Ma4455d6b2020-04-09 10:13:44 +0900611 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
612 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800613 mDhcpServerStartIndex++;
614 mDeps.makeDhcpServer(
615 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
616 return true;
617 }
618
619 private void stopDhcp() {
620 // Make all previous start requests obsolete so servers are not started later
621 mDhcpServerStartIndex++;
622
623 if (mDhcpServer != null) {
624 try {
625 mDhcpServer.stop(new OnHandlerStatusCallback() {
626 @Override
627 public void callback(int statusCode) {
628 if (statusCode != STATUS_SUCCESS) {
629 mLog.e("Error stopping DHCP server: " + statusCode);
Mark74461fc2022-12-14 08:49:40 +0000630 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800631 // Not much more we can do here
632 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900633 mDhcpLeases.clear();
634 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800635 }
636 });
637 mDhcpServer = null;
638 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900639 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800640 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800641 }
642 }
643 }
644
markchien245352e2020-02-27 20:27:18 +0800645 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
646 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800647 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800648 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800649 } else {
650 stopDhcp();
651 return true;
652 }
653 }
654
655 private void stopIPv4() {
Mark49649c92023-03-15 06:45:04 +0000656 configureIPv4(false /* enabled */, CONNECTIVITY_SCOPE_GLOBAL /* not used */);
markchien74a4fa92019-09-09 20:50:49 +0800657 // NOTE: All of configureIPv4() will be refactored out of existence
658 // into calls to InterfaceController, shared with startIPv4().
659 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800660 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800661 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800662 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800663 mStaticIpv4ServerAddr = null;
664 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800665 }
666
Mark49649c92023-03-15 06:45:04 +0000667 private boolean configureIPv4(boolean enabled, int scope) {
markchien74a4fa92019-09-09 20:50:49 +0800668 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
669
markchienc9daba32020-02-12 00:19:21 +0800670 if (enabled) {
Mark49649c92023-03-15 06:45:04 +0000671 mIpv4Address = requestIpv4Address(scope, true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800672 }
673
674 if (mIpv4Address == null) {
675 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800676 return false;
markchien74a4fa92019-09-09 20:50:49 +0800677 }
678
markchien69681d62021-11-15 23:58:05 +0800679 if (shouldNotConfigureBluetoothInterface()) {
680 // Interface was already configured elsewhere, only start DHCP.
markchienc9daba32020-02-12 00:19:21 +0800681 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
682 }
683
684 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
685
markchien12c5bb82020-01-07 14:43:17 +0800686 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800687 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900688 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200689 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
690 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900691 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800692 // It is unclear whether the Bluetooth or USB stacks will manage their own
693 // state.
694 setIfaceUp = null;
695 } else {
696 setIfaceUp = enabled;
697 }
698 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
699 mLog.e("Error configuring interface");
700 if (!enabled) stopDhcp();
701 return false;
702 }
markchien74a4fa92019-09-09 20:50:49 +0800703
markchien74a4fa92019-09-09 20:50:49 +0800704 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800705 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900706 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800707 } else {
markchien12c5bb82020-01-07 14:43:17 +0800708 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900709 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800710 }
markchien245352e2020-02-27 20:27:18 +0800711 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800712 }
713
markchien69681d62021-11-15 23:58:05 +0800714 private boolean shouldNotConfigureBluetoothInterface() {
715 // Before T, bluetooth tethering configures the interface elsewhere.
716 return (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) && !SdkLevel.isAtLeastT();
717 }
718
Mark49649c92023-03-15 06:45:04 +0000719 private LinkAddress requestIpv4Address(final int scope, final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800720 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800721
markchien69681d62021-11-15 23:58:05 +0800722 if (shouldNotConfigureBluetoothInterface()) return new LinkAddress(BLUETOOTH_IFACE_ADDR);
markchienc9daba32020-02-12 00:19:21 +0800723
Mark49649c92023-03-15 06:45:04 +0000724 return mPrivateAddressCoordinator.requestDownstreamAddress(this, scope, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900725 }
726
markchien74a4fa92019-09-09 20:50:49 +0800727 private boolean startIPv6() {
728 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
729 if (mInterfaceParams == null) {
730 mLog.e("Failed to find InterfaceParams");
731 stopIPv6();
732 return false;
733 }
734
735 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
736 if (!mRaDaemon.start()) {
737 stopIPv6();
738 return false;
739 }
740
markchien932df542021-08-12 13:56:43 +0800741 if (SdkLevel.isAtLeastS()) {
Tyler Wear90e40632020-03-13 11:38:38 -0700742 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
743 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
744 }
745
markchien74a4fa92019-09-09 20:50:49 +0800746 return true;
747 }
748
749 private void stopIPv6() {
750 mInterfaceParams = null;
751 setRaParams(null);
752
753 if (mRaDaemon != null) {
754 mRaDaemon.stop();
755 mRaDaemon = null;
756 }
Tyler Wear90e40632020-03-13 11:38:38 -0700757
758 if (mDadProxy != null) {
759 mDadProxy.stop();
760 mDadProxy = null;
761 }
markchien74a4fa92019-09-09 20:50:49 +0800762 }
763
764 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
765 // LinkProperties. These have extraneous data filtered out and only the
766 // necessary prefixes included (per its prefix distribution policy).
767 //
768 // TODO: Evaluate using a data structure than is more directly suited to
769 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800770 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800771 if (mRaDaemon == null) return;
772
773 // Avoid unnecessary work on spurious updates.
774 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
775 return;
776 }
777
778 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700779 String upstreamIface = null;
780 InterfaceParams upstreamIfaceParams = null;
KH Shi701c3ca2023-08-16 13:19:33 +0000781 int upstreamIfIndex = NO_UPSTREAM;
markchien74a4fa92019-09-09 20:50:49 +0800782
783 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700784 upstreamIface = v6only.getInterfaceName();
785 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
786 if (upstreamIfaceParams != null) {
787 upstreamIfIndex = upstreamIfaceParams.index;
788 }
markchien74a4fa92019-09-09 20:50:49 +0800789 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700790 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800791 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
792
markchiend63c4f32020-05-21 17:38:28 +0800793 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800794
KH Shi3f738fc2023-05-23 22:37:17 +0800795 params.prefixes = getTetherableIpv6Prefixes(v6only);
796 for (IpPrefix prefix : params.prefixes) {
markchien74a4fa92019-09-09 20:50:49 +0800797 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
798 if (dnsServer != null) {
799 params.dnses.add(dnsServer);
800 }
801 }
802 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900803
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900804 // Add upstream index to name mapping. See the comment of the interface mapping update in
805 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
806 // timing issue. It prevents that the IPv6 capability is updated later than
807 // CMD_TETHER_CONNECTION_CHANGED.
KH Shi701c3ca2023-08-16 13:19:33 +0000808 mBpfCoordinator.maybeAddUpstreamToLookupTable(upstreamIfIndex, upstreamIface);
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900809
markchien74a4fa92019-09-09 20:50:49 +0800810 // If v6only is null, we pass in null to setRaParams(), which handles
811 // deprecation of any existing RA data.
markchien74a4fa92019-09-09 20:50:49 +0800812 setRaParams(params);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900813
KH Shi68770342023-08-17 14:34:31 +0000814 // Not support BPF on virtual upstream interface
815 final boolean upstreamSupportsBpf = upstreamIface != null && !isVcnInterface(upstreamIface);
KH Shi3f738fc2023-05-23 22:37:17 +0800816 final Set<IpPrefix> upstreamPrefixes = params != null ? params.prefixes : Set.of();
817 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamPrefixes,
818 upstreamIfIndex, upstreamPrefixes, upstreamSupportsBpf);
KH Shi68770342023-08-17 14:34:31 +0000819 mLastIPv6LinkProperties = v6only;
Tyler Wear90e40632020-03-13 11:38:38 -0700820 mLastIPv6UpstreamIfindex = upstreamIfIndex;
KH Shi3f738fc2023-05-23 22:37:17 +0800821 mLastIPv6UpstreamPrefixes = upstreamPrefixes;
KH Shi68770342023-08-17 14:34:31 +0000822 mUpstreamSupportsBpf = upstreamSupportsBpf;
Tyler Wear90e40632020-03-13 11:38:38 -0700823 if (mDadProxy != null) {
824 mDadProxy.setUpstreamIface(upstreamIfaceParams);
825 }
markchien74a4fa92019-09-09 20:50:49 +0800826 }
827
Xiao Ma4455d6b2020-04-09 10:13:44 +0900828 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900829 final int removalFailures = NetdUtils.removeRoutesFromLocalNetwork(
Xiao Ma4455d6b2020-04-09 10:13:44 +0900830 mNetd, toBeRemoved);
831 if (removalFailures > 0) {
832 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
833 removalFailures));
834 }
835
836 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
837 }
838
Chalard Jean2fb66f12023-08-25 12:50:37 +0900839 private void addInterfaceToNetwork(final int netId, @NonNull final String ifaceName) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900840 try {
Chalard Jean2fb66f12023-08-25 12:50:37 +0900841 if (null != mRoutingCoordinator.value) {
842 // TODO : remove this call in favor of using the LocalNetworkConfiguration
843 // correctly, which will let ConnectivityService do it automatically.
844 mRoutingCoordinator.value.addInterfaceToNetwork(netId, ifaceName);
845 } else {
846 mNetd.networkAddInterface(netId, ifaceName);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900847 }
848 } catch (ServiceSpecificException | RemoteException e) {
849 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
Maciej Żenczykowski543d0d32023-10-28 02:10:52 +0000850 return;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900851 }
Chalard Jean2fb66f12023-08-25 12:50:37 +0900852 }
853
854 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
855 // It's safe to call addInterfaceToNetwork() even if
856 // the interface is already in the local_network.
857 addInterfaceToNetwork(INetd.LOCAL_NET_ID, mIfaceName);
858 try {
859 // Add routes from local network. Note that adding routes that
860 // already exist does not cause an error (EEXIST is silently ignored).
861 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
862 } catch (IllegalStateException e) {
863 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
864 return;
865 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900866
867 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
868 }
869
markchien74a4fa92019-09-09 20:50:49 +0800870 private void configureLocalIPv6Routes(
871 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
872 // [1] Remove the routes that are deprecated.
873 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900874 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800875 }
876
877 // [2] Add only the routes that have not previously been added.
878 if (newPrefixes != null && !newPrefixes.isEmpty()) {
879 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
880 if (mLastRaParams != null) {
881 addedPrefixes.removeAll(mLastRaParams.prefixes);
882 }
883
884 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900885 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800886 }
887 }
888 }
889
890 private void configureLocalIPv6Dns(
891 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
892 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
893 if (mNetd == null) {
894 if (newDnses != null) newDnses.clear();
895 mLog.e("No netd service instance available; not setting local IPv6 addresses");
896 return;
897 }
898
899 // [1] Remove deprecated local DNS IP addresses.
900 if (!deprecatedDnses.isEmpty()) {
901 for (Inet6Address dns : deprecatedDnses) {
902 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
903 mLog.e("Failed to remove local dns IP " + dns);
904 }
905
906 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
907 }
908 }
909
910 // [2] Add only the local DNS IP addresses that have not previously been added.
911 if (newDnses != null && !newDnses.isEmpty()) {
912 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
913 if (mLastRaParams != null) {
914 addedDnses.removeAll(mLastRaParams.dnses);
915 }
916
917 for (Inet6Address dns : addedDnses) {
918 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
919 mLog.e("Failed to add local dns IP " + dns);
920 newDnses.remove(dns);
921 }
922
923 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
924 }
925 }
926
927 try {
928 mNetd.tetherApplyDnsInterfaces();
929 } catch (ServiceSpecificException | RemoteException e) {
930 mLog.e("Failed to update local DNS caching server");
931 if (newDnses != null) newDnses.clear();
932 }
933 }
934
KH Shi701c3ca2023-08-16 13:19:33 +0000935 private int getInterfaceIndexForRule(int ifindex, boolean supportsBpf) {
936 return supportsBpf ? ifindex : NO_UPSTREAM;
937 }
938
KH Shi3f738fc2023-05-23 22:37:17 +0800939 // Handles updates to IPv6 forwarding rules if the upstream or its prefixes change.
940 private void updateIpv6ForwardingRules(int prevUpstreamIfindex,
941 @NonNull Set<IpPrefix> prevUpstreamPrefixes, int upstreamIfindex,
942 @NonNull Set<IpPrefix> upstreamPrefixes, boolean upstreamSupportsBpf) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900943 // If the upstream interface has changed, remove all rules and re-add them with the new
KH Shi701c3ca2023-08-16 13:19:33 +0000944 // upstream interface. If upstream is a virtual network, treated as no upstream.
KH Shi3f738fc2023-05-23 22:37:17 +0800945 if (prevUpstreamIfindex != upstreamIfindex
946 || !prevUpstreamPrefixes.equals(upstreamPrefixes)) {
KH Shi701c3ca2023-08-16 13:19:33 +0000947 mBpfCoordinator.updateAllIpv6Rules(this, this.mInterfaceParams,
KH Shi3f738fc2023-05-23 22:37:17 +0800948 getInterfaceIndexForRule(upstreamIfindex, upstreamSupportsBpf),
949 upstreamPrefixes);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900950 }
KH Shi701c3ca2023-08-16 13:19:33 +0000951 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900952
KH Shi701c3ca2023-08-16 13:19:33 +0000953 // Handles updates to IPv6 downstream rules if a neighbor event is received.
954 private void addOrRemoveIpv6Downstream(NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900955 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900956 if (e == null) return;
957 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
958 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
959 return;
960 }
961
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900962 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
KH Shi59ad35e2023-08-15 07:13:00 +0000963 // Do this here instead of in the Ipv6DownstreamRule constructor to ensure that we
964 // never add rules with a null MAC, only delete them.
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900965 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
KH Shi701c3ca2023-08-16 13:19:33 +0000966 Ipv6DownstreamRule rule = new Ipv6DownstreamRule(
967 getInterfaceIndexForRule(mLastIPv6UpstreamIfindex, mUpstreamSupportsBpf),
968 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900969 if (e.isValid()) {
KH Shie4d549a2023-08-28 09:57:34 +0000970 mBpfCoordinator.addIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900971 } else {
KH Shie4d549a2023-08-28 09:57:34 +0000972 mBpfCoordinator.removeIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900973 }
974 }
975
Hungming Chend71c06e2020-12-21 19:39:49 +0800976 // TODO: consider moving into BpfCoordinator.
977 private void updateClientInfoIpv4(NeighborEvent e) {
Hungming Chend71c06e2020-12-21 19:39:49 +0800978 if (e == null) return;
979 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
980 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
981 return;
982 }
983
984 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
985 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
986 // IpServer never add clients with a null MAC, only delete them.
987 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
988 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
989 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
990 if (e.isValid()) {
991 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
992 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +0800993 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
994 }
995 }
996
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900997 private void handleNeighborEvent(NeighborEvent e) {
998 if (mInterfaceParams != null
999 && mInterfaceParams.index == e.ifindex
1000 && mInterfaceParams.hasMacAddress) {
KH Shi701c3ca2023-08-16 13:19:33 +00001001 addOrRemoveIpv6Downstream(e);
Hungming Chend71c06e2020-12-21 19:39:49 +08001002 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001003 }
1004 }
1005
markchiend63c4f32020-05-21 17:38:28 +08001006 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001007 try {
1008 int upstreamHopLimit = Integer.parseUnsignedInt(
1009 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001010 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001011 // Cap the hop limit to 255.
1012 return (byte) Integer.min(upstreamHopLimit, 255);
1013 } catch (Exception e) {
1014 mLog.e("Failed to find upstream interface hop limit", e);
1015 }
1016 return RaParams.DEFAULT_HOPLIMIT;
1017 }
1018
1019 private void setRaParams(RaParams newParams) {
1020 if (mRaDaemon != null) {
1021 final RaParams deprecatedParams =
1022 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1023
1024 configureLocalIPv6Routes(deprecatedParams.prefixes,
1025 (newParams != null) ? newParams.prefixes : null);
1026
1027 configureLocalIPv6Dns(deprecatedParams.dnses,
1028 (newParams != null) ? newParams.dnses : null);
1029
1030 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1031 }
1032
1033 mLastRaParams = newParams;
1034 }
1035
markchien21021ef2021-06-01 10:58:04 +08001036 private void maybeLogMessage(State state, int what) {
1037 switch (what) {
1038 // Suppress some CMD_* to avoid log flooding.
1039 case CMD_IPV6_TETHER_UPDATE:
1040 case CMD_NEIGHBOR_EVENT:
1041 break;
1042 default:
1043 mLog.log(state.getName() + " got "
1044 + sMagicDecoderRing.get(what, Integer.toString(what)));
1045 }
markchien74a4fa92019-09-09 20:50:49 +08001046 }
1047
1048 private void sendInterfaceState(int newInterfaceState) {
1049 mServingMode = newInterfaceState;
1050 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1051 sendLinkProperties();
1052 }
1053
1054 private void sendLinkProperties() {
1055 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1056 }
1057
1058 private void resetLinkProperties() {
1059 mLinkProperties.clear();
1060 mLinkProperties.setInterfaceName(mIfaceName);
1061 }
1062
markchienf053e4b2020-03-16 21:49:48 +08001063 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001064 // Ignore static address configuration if they are invalid or null. In theory, static
1065 // addresses should not be invalid here because TetheringManager do not allow caller to
1066 // specify invalid static address configuration.
1067 if (request == null || request.localIPv4Address == null
1068 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1069 request.localIPv4Address, request.staticClientAddress)) {
1070 return;
1071 }
markchienf053e4b2020-03-16 21:49:48 +08001072
1073 mStaticIpv4ServerAddr = request.localIPv4Address;
1074 mStaticIpv4ClientAddr = request.staticClientAddress;
1075 }
1076
markchien74a4fa92019-09-09 20:50:49 +08001077 class InitialState extends State {
1078 @Override
1079 public void enter() {
1080 sendInterfaceState(STATE_AVAILABLE);
1081 }
1082
1083 @Override
1084 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001085 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001086 switch (message.what) {
1087 case CMD_TETHER_REQUESTED:
Mark74461fc2022-12-14 08:49:40 +00001088 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001089 switch (message.arg1) {
1090 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001091 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001092 transitionTo(mLocalHotspotState);
1093 break;
1094 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001095 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001096 transitionTo(mTetheredState);
1097 break;
1098 default:
1099 mLog.e("Invalid tethering interface serving state specified.");
1100 }
1101 break;
1102 case CMD_INTERFACE_DOWN:
1103 transitionTo(mUnavailableState);
1104 break;
markchien74a4fa92019-09-09 20:50:49 +08001105 default:
1106 return NOT_HANDLED;
1107 }
1108 return HANDLED;
1109 }
1110 }
1111
Hungming Chen46c30b12020-10-15 17:25:36 +08001112 private void startConntrackMonitoring() {
1113 mBpfCoordinator.startMonitoring(this);
1114 }
1115
1116 private void stopConntrackMonitoring() {
1117 mBpfCoordinator.stopMonitoring(this);
1118 }
1119
Mark3ec851e2023-05-19 08:50:38 +00001120 abstract class BaseServingState extends State {
1121 private final int mDesiredInterfaceState;
1122
1123 BaseServingState(int interfaceState) {
1124 mDesiredInterfaceState = interfaceState;
1125 }
1126
markchien74a4fa92019-09-09 20:50:49 +08001127 @Override
1128 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001129 startConntrackMonitoring();
1130
Mark3ec851e2023-05-19 08:50:38 +00001131 startServingInterface();
1132
1133 if (mLastError != TETHER_ERROR_NO_ERROR) {
Mark50eef832023-09-19 06:56:14 +00001134 // This will transition to InitialState right away, regardless of whether any
1135 // message is already waiting in the StateMachine queue (including maybe some
1136 // message to go to InitialState). InitialState will then process any pending
1137 // message (and generally ignores them). It is difficult to know for sure whether
1138 // this is correct in all cases, but this is equivalent to what IpServer was doing
1139 // in previous versions of the mainline module.
Markbe99f862022-12-21 16:39:23 +00001140 // TODO : remove sendMessageAtFrontOfQueueToAsyncSM after migrating to the Sync
1141 // StateMachine.
1142 if (USE_SYNC_SM) {
1143 sendSelfMessageToSyncSM(CMD_SERVICE_FAILED_TO_START, mLastError);
1144 } else {
1145 sendMessageAtFrontOfQueueToAsyncSM(CMD_SERVICE_FAILED_TO_START, mLastError);
1146 }
Mark3ec851e2023-05-19 08:50:38 +00001147 }
1148
1149 if (DBG) Log.d(TAG, getStateString(mDesiredInterfaceState) + " serve " + mIfaceName);
1150 sendInterfaceState(mDesiredInterfaceState);
1151 }
1152
Mark49649c92023-03-15 06:45:04 +00001153 private int getScope() {
1154 if (mDesiredInterfaceState == STATE_TETHERED) {
1155 return CONNECTIVITY_SCOPE_GLOBAL;
1156 }
1157
1158 return CONNECTIVITY_SCOPE_LOCAL;
1159 }
1160
Mark3ec851e2023-05-19 08:50:38 +00001161 private void startServingInterface() {
Mark49649c92023-03-15 06:45:04 +00001162 if (!startIPv4(getScope())) {
Mark74461fc2022-12-14 08:49:40 +00001163 mLastError = TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001164 return;
1165 }
1166
1167 try {
markchienc9daba32020-02-12 00:19:21 +08001168 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001169 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001170 mLog.e("Error Tethering", e);
Mark74461fc2022-12-14 08:49:40 +00001171 mLastError = TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001172 return;
1173 }
1174
1175 if (!startIPv6()) {
1176 mLog.e("Failed to startIPv6");
1177 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1178 return;
1179 }
1180 }
1181
1182 @Override
1183 public void exit() {
1184 // Note that at this point, we're leaving the tethered state. We can fail any
1185 // of these operations, but it doesn't really change that we have to try them
1186 // all in sequence.
1187 stopIPv6();
1188
1189 try {
markchien12c5bb82020-01-07 14:43:17 +08001190 NetdUtils.untetherInterface(mNetd, mIfaceName);
1191 } catch (RemoteException | ServiceSpecificException e) {
Mark74461fc2022-12-14 08:49:40 +00001192 mLastError = TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001193 mLog.e("Failed to untether interface: " + e);
1194 }
1195
1196 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001197 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001198
1199 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001200
1201 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1202 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001203 }
1204
1205 @Override
1206 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001207 switch (message.what) {
1208 case CMD_TETHER_UNREQUESTED:
1209 transitionTo(mInitialState);
1210 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1211 break;
1212 case CMD_INTERFACE_DOWN:
1213 transitionTo(mUnavailableState);
1214 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1215 break;
1216 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001217 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001218 sendLinkProperties();
1219 break;
1220 case CMD_IP_FORWARDING_ENABLE_ERROR:
1221 case CMD_IP_FORWARDING_DISABLE_ERROR:
1222 case CMD_START_TETHERING_ERROR:
1223 case CMD_STOP_TETHERING_ERROR:
1224 case CMD_SET_DNS_FORWARDERS_ERROR:
Mark74461fc2022-12-14 08:49:40 +00001225 mLastError = TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001226 transitionTo(mInitialState);
1227 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001228 case CMD_NEW_PREFIX_REQUEST:
1229 handleNewPrefixRequest((IpPrefix) message.obj);
1230 break;
markchienc9daba32020-02-12 00:19:21 +08001231 case CMD_NOTIFY_PREFIX_CONFLICT:
1232 mLog.i("restart tethering: " + mInterfaceType);
1233 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1234 transitionTo(mWaitingForRestartState);
1235 break;
Mark50eef832023-09-19 06:56:14 +00001236 case CMD_SERVICE_FAILED_TO_START:
1237 mLog.e("start serving fail, error: " + message.arg1);
1238 transitionTo(mInitialState);
markchien74a4fa92019-09-09 20:50:49 +08001239 default:
1240 return false;
1241 }
1242 return true;
1243 }
Mark3ec851e2023-05-19 08:50:38 +00001244
1245 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
1246 if (!currentPrefix.contains(mIpv4Address.getAddress())
1247 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
1248 Log.e(TAG, "Invalid prefix: " + currentPrefix);
1249 return;
1250 }
1251
1252 final LinkAddress deprecatedLinkAddress = mIpv4Address;
Mark49649c92023-03-15 06:45:04 +00001253 mIpv4Address = requestIpv4Address(getScope(), false);
Mark3ec851e2023-05-19 08:50:38 +00001254 if (mIpv4Address == null) {
1255 mLog.e("Fail to request a new downstream prefix");
1256 return;
1257 }
1258 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
1259
1260 // Add new IPv4 address on the interface.
1261 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1262 mLog.e("Failed to add new IP " + srvAddr);
1263 return;
1264 }
1265
1266 // Remove deprecated routes from local network.
1267 removeRoutesFromLocalNetwork(
1268 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1269 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1270
1271 // Add new routes to local network.
1272 addRoutesToLocalNetwork(
1273 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1274 mLinkProperties.addLinkAddress(mIpv4Address);
1275
1276 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1277 // listen on the interface configured with new IPv4 address, that results DNS validation
1278 // failure of downstream client even if appropriate routes have been configured.
1279 try {
1280 mNetd.tetherApplyDnsInterfaces();
1281 } catch (ServiceSpecificException | RemoteException e) {
1282 mLog.e("Failed to update local DNS caching server");
1283 return;
1284 }
1285 sendLinkProperties();
1286
1287 // Notify DHCP server that new prefix/route has been applied on IpServer.
1288 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1289 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1290 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1291 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1292 try {
1293 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1294 @Override
1295 public void callback(int statusCode) {
1296 if (statusCode != STATUS_SUCCESS) {
1297 mLog.e("Error updating DHCP serving params: " + statusCode);
1298 }
1299 }
1300 });
1301 } catch (RemoteException e) {
1302 mLog.e("Error updating DHCP serving params", e);
1303 }
1304 }
markchien74a4fa92019-09-09 20:50:49 +08001305 }
1306
1307 // Handling errors in BaseServingState.enter() by transitioning is
1308 // problematic because transitioning during a multi-state jump yields
1309 // a Log.wtf(). Ultimately, there should be only one ServingState,
1310 // and forwarding and NAT rules should be handled by a coordinating
1311 // functional element outside of IpServer.
1312 class LocalHotspotState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001313 LocalHotspotState() {
1314 super(STATE_LOCAL_ONLY);
markchien74a4fa92019-09-09 20:50:49 +08001315 }
1316
1317 @Override
1318 public boolean processMessage(Message message) {
1319 if (super.processMessage(message)) return true;
1320
markchien21021ef2021-06-01 10:58:04 +08001321 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001322 switch (message.what) {
1323 case CMD_TETHER_REQUESTED:
1324 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1325 break;
1326 case CMD_TETHER_CONNECTION_CHANGED:
1327 // Ignored in local hotspot state.
1328 break;
1329 default:
1330 return false;
1331 }
1332 return true;
1333 }
1334 }
1335
1336 // Handling errors in BaseServingState.enter() by transitioning is
1337 // problematic because transitioning during a multi-state jump yields
1338 // a Log.wtf(). Ultimately, there should be only one ServingState,
1339 // and forwarding and NAT rules should be handled by a coordinating
1340 // functional element outside of IpServer.
1341 class TetheredState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001342 TetheredState() {
1343 super(STATE_TETHERED);
markchien74a4fa92019-09-09 20:50:49 +08001344 }
1345
1346 @Override
1347 public void exit() {
1348 cleanupUpstream();
KH Shi701c3ca2023-08-16 13:19:33 +00001349 mBpfCoordinator.clearAllIpv6Rules(IpServer.this);
markchien74a4fa92019-09-09 20:50:49 +08001350 super.exit();
1351 }
1352
Hungming Chena6e78692021-02-08 17:15:35 +08001353 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1354 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1355 // and behaviour. While upstream is switching from offload supported interface to
1356 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1357 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1358 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1359 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1360 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1361 // in the state machine. Once there is any case out whish is not covered by previous cases,
1362 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001363 private void cleanupUpstream() {
1364 if (mUpstreamIfaceSet == null) return;
1365
1366 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1367 mUpstreamIfaceSet = null;
KH Shi701c3ca2023-08-16 13:19:33 +00001368 mBpfCoordinator.updateAllIpv6Rules(
KH Shi3f738fc2023-05-23 22:37:17 +08001369 IpServer.this, IpServer.this.mInterfaceParams, NO_UPSTREAM, Set.of());
markchien74a4fa92019-09-09 20:50:49 +08001370 }
1371
1372 private void cleanupUpstreamInterface(String upstreamIface) {
1373 // Note that we don't care about errors here.
1374 // Sometimes interfaces are gone before we get
1375 // to remove their rules, which generates errors.
1376 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001377 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
Maciej Żenczykowski543d0d32023-10-28 02:10:52 +00001378 try {
1379 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1380 } catch (RemoteException | ServiceSpecificException e) {
1381 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
1382 }
1383 try {
1384 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1385 } catch (RemoteException | ServiceSpecificException e) {
1386 mLog.e("Exception in disableNat: " + e.toString());
1387 }
markchien74a4fa92019-09-09 20:50:49 +08001388 }
1389
1390 @Override
1391 public boolean processMessage(Message message) {
1392 if (super.processMessage(message)) return true;
1393
markchien21021ef2021-06-01 10:58:04 +08001394 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001395 switch (message.what) {
1396 case CMD_TETHER_REQUESTED:
1397 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1398 break;
1399 case CMD_TETHER_CONNECTION_CHANGED:
1400 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1401 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1402 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1403 break;
1404 }
1405
1406 if (newUpstreamIfaceSet == null) {
1407 cleanupUpstream();
1408 break;
1409 }
1410
1411 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1412 cleanupUpstreamInterface(removed);
1413 }
1414
1415 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1416 // This makes the call to cleanupUpstream() in the error
1417 // path for any interface neatly cleanup all the interfaces.
1418 mUpstreamIfaceSet = newUpstreamIfaceSet;
1419
1420 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001421 // Add upstream index to name mapping for the tether stats usage in the
1422 // coordinator. Although this mapping could be added by both class
1423 // Tethering and IpServer, adding mapping from IpServer guarantees that
1424 // the mapping is added before adding forwarding rules. That is because
1425 // there are different state machines in both classes. It is hard to
1426 // guarantee the link property update order between multiple state machines.
1427 // Note that both IPv4 and IPv6 interface may be added because
1428 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1429 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1430 // capability may be updated later. In that case, IPv6 interface mapping is
1431 // updated in updateUpstreamIPv6LinkProperties.
1432 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1433 final InterfaceParams upstreamIfaceParams =
1434 mDeps.getInterfaceParams(ifname);
1435 if (upstreamIfaceParams != null) {
KH Shi701c3ca2023-08-16 13:19:33 +00001436 mBpfCoordinator.maybeAddUpstreamToLookupTable(
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001437 upstreamIfaceParams.index, ifname);
1438 }
1439 }
1440
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001441 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001442 try {
Maciej Żenczykowski543d0d32023-10-28 02:10:52 +00001443 mNetd.tetherAddForward(mIfaceName, ifname);
1444 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
markchien12c5bb82020-01-07 14:43:17 +08001445 } catch (RemoteException | ServiceSpecificException e) {
Maciej Żenczykowski543d0d32023-10-28 02:10:52 +00001446 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001447 cleanupUpstream();
Mark74461fc2022-12-14 08:49:40 +00001448 mLastError = TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001449 transitionTo(mInitialState);
1450 return true;
1451 }
1452 }
1453 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001454 case CMD_NEIGHBOR_EVENT:
1455 handleNeighborEvent((NeighborEvent) message.obj);
1456 break;
markchien74a4fa92019-09-09 20:50:49 +08001457 default:
1458 return false;
1459 }
1460 return true;
1461 }
1462
1463 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1464 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1465 if (mUpstreamIfaceSet != null && newIfaces != null) {
1466 return mUpstreamIfaceSet.equals(newIfaces);
1467 }
1468 return false;
1469 }
1470
1471 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1472 if (mUpstreamIfaceSet == null) return new HashSet<>();
1473
1474 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1475 removed.removeAll(newIfaces.ifnames);
1476 return removed;
1477 }
1478
1479 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1480 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1481 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1482 return added;
1483 }
1484 }
1485
1486 /**
1487 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001488 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001489 * specific state machine from its list of possible recipients of
1490 * tethering requests. The state machine itself will hang around until
1491 * the garbage collector finds it.
1492 */
1493 class UnavailableState extends State {
1494 @Override
1495 public void enter() {
KH Shi701c3ca2023-08-16 13:19:33 +00001496 // TODO: move mIpNeighborMonitor.stop() to TetheredState#exit, and trigger a neighbours
1497 // dump after starting mIpNeighborMonitor.
h.zhangd244bd02020-06-14 14:46:54 +08001498 mIpNeighborMonitor.stop();
Mark74461fc2022-12-14 08:49:40 +00001499 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001500 sendInterfaceState(STATE_UNAVAILABLE);
1501 }
1502 }
1503
markchienc9daba32020-02-12 00:19:21 +08001504 class WaitingForRestartState extends State {
1505 @Override
1506 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001507 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001508 switch (message.what) {
1509 case CMD_TETHER_UNREQUESTED:
1510 transitionTo(mInitialState);
1511 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1512 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1513 break;
1514 case CMD_INTERFACE_DOWN:
1515 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001516 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001517 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1518 break;
1519 default:
1520 return false;
1521 }
1522 return true;
1523 }
1524 }
1525
markchien74a4fa92019-09-09 20:50:49 +08001526 // Accumulate routes representing "prefixes to be assigned to the local
1527 // interface", for subsequent modification of local_network routing.
1528 private static ArrayList<RouteInfo> getLocalRoutesFor(
1529 String ifname, HashSet<IpPrefix> prefixes) {
1530 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1531 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001532 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001533 }
1534 return localRoutes;
1535 }
1536
1537 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1538 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1539 final byte[] dnsBytes = localPrefix.getRawAddress();
1540 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1541 try {
1542 return Inet6Address.getByAddress(null, dnsBytes, 0);
1543 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001544 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001545 return null;
1546 }
1547 }
1548
1549 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1550 final byte random = (byte) (new Random()).nextInt();
1551 for (int value : excluded) {
1552 if (random == value) return dflt;
1553 }
1554 return random;
1555 }
KH Shi3f738fc2023-05-23 22:37:17 +08001556
1557 /** Get IPv6 prefixes from LinkProperties */
1558 @NonNull
1559 @VisibleForTesting
1560 static HashSet<IpPrefix> getTetherableIpv6Prefixes(@NonNull Collection<LinkAddress> addrs) {
1561 final HashSet<IpPrefix> prefixes = new HashSet<>();
1562 for (LinkAddress linkAddr : addrs) {
1563 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
1564 prefixes.add(new IpPrefix(linkAddr.getAddress(), RFC7421_PREFIX_LENGTH));
1565 }
1566 return prefixes;
1567 }
1568
1569 @NonNull
1570 private HashSet<IpPrefix> getTetherableIpv6Prefixes(@NonNull LinkProperties lp) {
1571 return getTetherableIpv6Prefixes(lp.getLinkAddresses());
1572 }
markchien74a4fa92019-09-09 20:50:49 +08001573}