blob: e030902637966630f9c4f08573153338abdfb053 [file] [log] [blame]
markchien74a4fa92019-09-09 20:50:49 +08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net.ip;
18
markchien6cf0e552019-12-06 15:24:53 +080019import static android.net.RouteInfo.RTN_UNICAST;
Mark49649c92023-03-15 06:45:04 +000020import static android.net.TetheringManager.CONNECTIVITY_SCOPE_GLOBAL;
21import static android.net.TetheringManager.CONNECTIVITY_SCOPE_LOCAL;
Mark74461fc2022-12-14 08:49:40 +000022import static android.net.TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
23import static android.net.TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
24import static android.net.TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
25import static android.net.TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
26import static android.net.TetheringManager.TETHER_ERROR_NO_ERROR;
27import static android.net.TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
28import static android.net.TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien245352e2020-02-27 20:27:18 +080029import static android.net.TetheringManager.TetheringRequest.checkStaticAddressConfiguration;
markchien74a4fa92019-09-09 20:50:49 +080030import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
markchien74a4fa92019-09-09 20:50:49 +080031import static android.net.util.NetworkConstants.asByte;
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +090032import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080033
Chalard Jean78701642020-07-31 20:00:30 +090034import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH;
Xiao Ma1f993302023-08-09 18:55:49 +090035import static com.android.net.module.util.NetworkStackConstants.RFC7421_PREFIX_LENGTH;
markchien7dc1b4d2021-07-13 17:12:56 +080036import static com.android.networkstack.tethering.UpstreamNetworkState.isVcnInterface;
markchiend02f9af2021-11-04 11:26:03 +080037import static com.android.networkstack.tethering.util.PrefixUtils.asIpPrefix;
38import static com.android.networkstack.tethering.util.TetheringMessageBase.BASE_IPSERVER;
Chalard Jean78701642020-07-31 20:00:30 +090039
markchien74a4fa92019-09-09 20:50:49 +080040import android.net.INetd;
41import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080042import android.net.IpPrefix;
43import android.net.LinkAddress;
44import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090045import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080046import android.net.RouteInfo;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090047import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080048import android.net.TetheringManager;
markchienf053e4b2020-03-16 21:49:48 +080049import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090050import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080051import android.net.dhcp.DhcpServerCallbacks;
52import android.net.dhcp.DhcpServingParamsParcel;
53import android.net.dhcp.DhcpServingParamsParcelExt;
Xiao Ma49889dd2020-04-03 17:01:33 +090054import android.net.dhcp.IDhcpEventCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080055import android.net.dhcp.IDhcpServer;
56import android.net.ip.RouterAdvertisementDaemon.RaParams;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090057import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080058import android.os.Looper;
59import android.os.Message;
60import android.os.RemoteException;
61import android.os.ServiceSpecificException;
62import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080063import android.util.SparseArray;
64
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090065import androidx.annotation.NonNull;
Xiao Ma4455d6b2020-04-09 10:13:44 +090066import androidx.annotation.Nullable;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090067
markchien74a4fa92019-09-09 20:50:49 +080068import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080069import com.android.internal.util.State;
70import com.android.internal.util.StateMachine;
markchien932df542021-08-12 13:56:43 +080071import com.android.modules.utils.build.SdkLevel;
Patrick Rohr9f371f02022-03-04 15:14:27 +010072import com.android.net.module.util.InterfaceParams;
Chalard Jeanadcec9e2021-10-29 15:57:22 +090073import com.android.net.module.util.NetdUtils;
Patrick Rohrb873e252022-06-16 16:38:43 -070074import com.android.net.module.util.SharedLog;
Xiao Mac81c0662022-06-17 14:58:03 +090075import com.android.net.module.util.ip.InterfaceController;
76import com.android.net.module.util.ip.IpNeighborMonitor;
77import com.android.net.module.util.ip.IpNeighborMonitor.NeighborEvent;
Hungming Chen68f1c2a2020-03-12 21:24:01 +080078import com.android.networkstack.tethering.BpfCoordinator;
Hungming Chend71c06e2020-12-21 19:39:49 +080079import com.android.networkstack.tethering.BpfCoordinator.ClientInfo;
KH Shi59ad35e2023-08-15 07:13:00 +000080import com.android.networkstack.tethering.BpfCoordinator.Ipv6DownstreamRule;
markchienc9daba32020-02-12 00:19:21 +080081import com.android.networkstack.tethering.PrivateAddressCoordinator;
markchienb961d3d2022-02-26 00:39:06 +080082import com.android.networkstack.tethering.TetheringConfiguration;
Wayne Ma6cd440f2022-03-14 18:04:33 +080083import com.android.networkstack.tethering.metrics.TetheringMetrics;
markchiend02f9af2021-11-04 11:26:03 +080084import com.android.networkstack.tethering.util.InterfaceSet;
85import com.android.networkstack.tethering.util.PrefixUtils;
markchien74a4fa92019-09-09 20:50:49 +080086
87import java.net.Inet4Address;
88import java.net.Inet6Address;
markchien74a4fa92019-09-09 20:50:49 +080089import java.net.UnknownHostException;
90import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090091import java.util.Arrays;
92import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080093import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090094import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080095import java.util.Objects;
96import java.util.Random;
97import java.util.Set;
98
99/**
100 * Provides the interface to IP-layer serving functionality for a given network
101 * interface, e.g. for tethering or "local-only hotspot" mode.
102 *
103 * @hide
104 */
105public class IpServer extends StateMachine {
106 public static final int STATE_UNAVAILABLE = 0;
107 public static final int STATE_AVAILABLE = 1;
108 public static final int STATE_TETHERED = 2;
109 public static final int STATE_LOCAL_ONLY = 3;
110
111 /** Get string name of |state|.*/
112 public static String getStateString(int state) {
113 switch (state) {
114 case STATE_UNAVAILABLE: return "UNAVAILABLE";
115 case STATE_AVAILABLE: return "AVAILABLE";
116 case STATE_TETHERED: return "TETHERED";
117 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
118 }
119 return "UNKNOWN: " + state;
120 }
121
122 private static final byte DOUG_ADAMS = (byte) 42;
123
markchien74a4fa92019-09-09 20:50:49 +0800124 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800125 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800126
127 // TODO: have this configurable
128 private static final int DHCP_LEASE_TIME_SECS = 3600;
129
KH Shi701c3ca2023-08-16 13:19:33 +0000130 private static final int NO_UPSTREAM = 0;
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900131 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
132
markchien74a4fa92019-09-09 20:50:49 +0800133 private static final String TAG = "IpServer";
134 private static final boolean DBG = false;
135 private static final boolean VDBG = false;
136 private static final Class[] sMessageClasses = {
137 IpServer.class
138 };
139 private static final SparseArray<String> sMagicDecoderRing =
140 MessageUtils.findMessageNames(sMessageClasses);
141
142 /** IpServer callback. */
143 public static class Callback {
144 /**
145 * Notify that |who| has changed its tethering state.
146 *
147 * @param who the calling instance of IpServer
148 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800149 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800150 */
markchien9d353822019-12-16 20:15:20 +0800151 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800152
153 /**
154 * Notify that |who| has new LinkProperties.
155 *
156 * @param who the calling instance of IpServer
157 * @param newLp the new LinkProperties to report
158 */
markchien9d353822019-12-16 20:15:20 +0800159 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900160
161 /**
162 * Notify that the DHCP leases changed in one of the IpServers.
163 */
164 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800165
166 /**
167 * Request Tethering change.
168 *
169 * @param tetheringType the downstream type of this IpServer.
170 * @param enabled enable or disable tethering.
171 */
172 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800173 }
174
175 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800176 public abstract static class Dependencies {
Tyler Wear90e40632020-03-13 11:38:38 -0700177 /**
178 * Create a DadProxy instance to be used by IpServer.
179 * To support multiple tethered interfaces concurrently DAD Proxy
180 * needs to be supported per IpServer instead of per upstream.
181 */
182 public DadProxy getDadProxy(Handler handler, InterfaceParams ifParams) {
183 return new DadProxy(handler, ifParams);
184 }
185
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900186 /** Create an IpNeighborMonitor to be used by this IpServer */
187 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
188 IpNeighborMonitor.NeighborEventConsumer consumer) {
189 return new IpNeighborMonitor(handler, log, consumer);
190 }
191
markchien74a4fa92019-09-09 20:50:49 +0800192 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
193 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
194 return new RouterAdvertisementDaemon(ifParams);
195 }
196
197 /** Get |ifName|'s interface information.*/
198 public InterfaceParams getInterfaceParams(String ifName) {
199 return InterfaceParams.getByName(ifName);
200 }
201
markchien9d353822019-12-16 20:15:20 +0800202 /** Create a DhcpServer instance to be used by IpServer. */
203 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
204 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800205 }
206
markchien74a4fa92019-09-09 20:50:49 +0800207 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800208 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800209 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800210 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800211 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800212 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800213 // notification from the {@link Tethering.TetherMainSM} that it had trouble enabling IP
214 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800215 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800216 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble disabling IP
217 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800218 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800219 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble starting
220 // tethering
markchien6cf0e552019-12-06 15:24:53 +0800221 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800222 // notification from the {@link Tethering.TetherMainSM} that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800223 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800224 // notification from the {@link Tethering.TetherMainSM} that it had trouble setting the DNS
225 // forwarders
markchien6cf0e552019-12-06 15:24:53 +0800226 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800227 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800228 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800229 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800230 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900231 // new neighbor cache entry on our interface
232 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900233 // request from DHCP server that it wants to have a new prefix
234 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800235 // request from PrivateAddressCoordinator to restart tethering.
236 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
markchien74a4fa92019-09-09 20:50:49 +0800237
238 private final State mInitialState;
239 private final State mLocalHotspotState;
240 private final State mTetheredState;
241 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800242 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800243
244 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800245 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800246 @NonNull
247 private final BpfCoordinator mBpfCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800248 private final Callback mCallback;
249 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800250 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800251
252 private final String mIfaceName;
253 private final int mInterfaceType;
254 private final LinkProperties mLinkProperties;
255 private final boolean mUsingLegacyDhcp;
markchienfb65dfe2022-02-25 23:14:58 +0800256 private final int mP2pLeasesSubnetPrefixLength;
markchien74a4fa92019-09-09 20:50:49 +0800257
258 private final Dependencies mDeps;
259
260 private int mLastError;
261 private int mServingMode;
262 private InterfaceSet mUpstreamIfaceSet; // may change over time
KH Shi701c3ca2023-08-16 13:19:33 +0000263 // mInterfaceParams can't be final now because IpServer will be created when receives
264 // WIFI_AP_STATE_CHANGED broadcasts or when it detects that the wifi interface has come up.
265 // In the latter case, the interface is not fully initialized and the MAC address might not
266 // be correct (it will be set with a randomized MAC address later).
267 // TODO: Consider create the IpServer only when tethering want to enable it, then we can
268 // make mInterfaceParams final.
markchien74a4fa92019-09-09 20:50:49 +0800269 private InterfaceParams mInterfaceParams;
270 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
271 // properties are those selected by the IPv6TetheringCoordinator and relayed
272 // to us. By comparison, mLinkProperties contains the addresses and directly
273 // connected routes that have been formed from these properties iff. we have
274 // succeeded in configuring them and are able to announce them within Router
275 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
276 private LinkProperties mLastIPv6LinkProperties;
277 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700278 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800279
280 // To be accessed only on the handler thread
281 private int mDhcpServerStartIndex = 0;
282 private IDhcpServer mDhcpServer;
283 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800284
285 private LinkAddress mStaticIpv4ServerAddr;
286 private LinkAddress mStaticIpv4ClientAddr;
287
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900288 @NonNull
289 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800290
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900291 private int mLastIPv6UpstreamIfindex = 0;
KH Shi68770342023-08-17 14:34:31 +0000292 private boolean mUpstreamSupportsBpf = false;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900293
294 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
295 public void accept(NeighborEvent e) {
296 sendMessage(CMD_NEIGHBOR_EVENT, e);
297 }
298 }
299
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900300 private final IpNeighborMonitor mIpNeighborMonitor;
301
markchienc9daba32020-02-12 00:19:21 +0800302 private LinkAddress mIpv4Address;
303
Wayne Ma6cd440f2022-03-14 18:04:33 +0800304 private final TetheringMetrics mTetheringMetrics;
305
Hungming Chen5bc3af92020-05-12 19:15:24 +0800306 // TODO: Add a dependency object to pass the data members or variables from the tethering
307 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800308 public IpServer(
309 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800310 INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
markchienb961d3d2022-02-26 00:39:06 +0800311 TetheringConfiguration config, PrivateAddressCoordinator addressCoordinator,
Wayne Ma6cd440f2022-03-14 18:04:33 +0800312 TetheringMetrics tetheringMetrics, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800313 super(ifaceName, looper);
314 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800315 mNetd = netd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800316 mBpfCoordinator = coordinator;
markchien74a4fa92019-09-09 20:50:49 +0800317 mCallback = callback;
318 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
319 mIfaceName = ifaceName;
320 mInterfaceType = interfaceType;
321 mLinkProperties = new LinkProperties();
markchienb961d3d2022-02-26 00:39:06 +0800322 mUsingLegacyDhcp = config.useLegacyDhcpServer();
markchienfb65dfe2022-02-25 23:14:58 +0800323 mP2pLeasesSubnetPrefixLength = config.getP2pLeasesSubnetPrefixLength();
markchienc9daba32020-02-12 00:19:21 +0800324 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800325 mDeps = deps;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800326 mTetheringMetrics = tetheringMetrics;
markchien74a4fa92019-09-09 20:50:49 +0800327 resetLinkProperties();
Mark74461fc2022-12-14 08:49:40 +0000328 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800329 mServingMode = STATE_AVAILABLE;
330
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900331 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
332 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800333
KH Shie4d549a2023-08-28 09:57:34 +0000334 // IP neighbor monitor monitors the neighbor events for adding/removing IPv6 downstream rule
335 // per client. If BPF offload is not supported, don't start listening for neighbor events.
336 if (mBpfCoordinator.isUsingBpfOffload() && !mIpNeighborMonitor.start()) {
Hungming Chen5bc3af92020-05-12 19:15:24 +0800337 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900338 }
339
markchien74a4fa92019-09-09 20:50:49 +0800340 mInitialState = new InitialState();
341 mLocalHotspotState = new LocalHotspotState();
342 mTetheredState = new TetheredState();
343 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800344 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800345 addState(mInitialState);
346 addState(mLocalHotspotState);
347 addState(mTetheredState);
markchienc9daba32020-02-12 00:19:21 +0800348 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800349 addState(mUnavailableState);
350
351 setInitialState(mInitialState);
352 }
353
354 /** Interface name which IpServer served.*/
355 public String interfaceName() {
356 return mIfaceName;
357 }
358
359 /**
markchien9b4d7572019-12-25 19:40:32 +0800360 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800361 */
362 public int interfaceType() {
363 return mInterfaceType;
364 }
365
366 /** Last error from this IpServer. */
367 public int lastError() {
368 return mLastError;
369 }
370
371 /** Serving mode is the current state of IpServer state machine. */
372 public int servingMode() {
373 return mServingMode;
374 }
375
376 /** The properties of the network link which IpServer is serving. */
377 public LinkProperties linkProperties() {
378 return new LinkProperties(mLinkProperties);
379 }
380
markchienc9daba32020-02-12 00:19:21 +0800381 /** The address which IpServer is using. */
382 public LinkAddress getAddress() {
383 return mIpv4Address;
384 }
385
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900386 /**
387 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
388 * thread.
389 */
390 public List<TetheredClient> getAllLeases() {
391 return Collections.unmodifiableList(mDhcpLeases);
392 }
393
Marka5424582022-12-01 13:46:32 +0000394 /** Enable this IpServer. IpServer state machine will be tethered or localHotspot state. */
395 public void enable(final int requestedState, final TetheringRequestParcel request) {
396 sendMessage(CMD_TETHER_REQUESTED, requestedState, 0, request);
397 }
398
markchien74a4fa92019-09-09 20:50:49 +0800399 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
400 public void stop() {
401 sendMessage(CMD_INTERFACE_DOWN);
402 }
403
404 /**
405 * Tethering is canceled. IpServer state machine will be available and wait for
406 * next tethering request.
407 */
408 public void unwanted() {
409 sendMessage(CMD_TETHER_UNREQUESTED);
410 }
411
412 /** Internals. */
413
Mark49649c92023-03-15 06:45:04 +0000414 private boolean startIPv4(int scope) {
415 return configureIPv4(true, scope);
markchien74a4fa92019-09-09 20:50:49 +0800416 }
417
418 /**
419 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
420 * handler.
421 *
422 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
423 * with different implementations of the callback, to differentiate handling of success/error in
424 * each call.
425 */
426 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
427 @Override
428 public void onStatusAvailable(int statusCode) {
429 getHandler().post(() -> callback(statusCode));
430 }
431
432 public abstract void callback(int statusCode);
433
434 @Override
435 public int getInterfaceVersion() {
436 return this.VERSION;
437 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900438
439 @Override
440 public String getInterfaceHash() {
441 return this.HASH;
442 }
markchien74a4fa92019-09-09 20:50:49 +0800443 }
444
445 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
446 private final int mStartIndex;
447
448 private DhcpServerCallbacksImpl(int startIndex) {
449 mStartIndex = startIndex;
450 }
451
452 @Override
453 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
454 getHandler().post(() -> {
455 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
456 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800457 // This start request is obsolete. Explicitly stop the DHCP server to shut
458 // down its thread. When the |server| binder token goes out of scope, the
459 // garbage collector will finalize it, which causes the network stack process
460 // garbage collector to collect the server itself.
461 try {
462 server.stop(null);
463 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800464 return;
465 }
466
467 if (statusCode != STATUS_SUCCESS) {
468 mLog.e("Error obtaining DHCP server: " + statusCode);
469 handleError();
470 return;
471 }
472
473 mDhcpServer = server;
474 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900475 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800476 @Override
477 public void callback(int startStatusCode) {
478 if (startStatusCode != STATUS_SUCCESS) {
479 mLog.e("Error starting DHCP server: " + startStatusCode);
480 handleError();
481 }
482 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900483 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800484 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800485 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800486 }
487 });
488 }
489
490 private void handleError() {
Mark74461fc2022-12-14 08:49:40 +0000491 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800492 transitionTo(mInitialState);
493 }
494 }
495
Xiao Ma4455d6b2020-04-09 10:13:44 +0900496 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900497 @Override
498 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
499 final ArrayList<TetheredClient> leases = new ArrayList<>();
500 for (DhcpLeaseParcelable lease : leaseParcelables) {
501 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900502 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
503 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
504 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900505
506 final MacAddress macAddress;
507 try {
508 macAddress = MacAddress.fromBytes(lease.hwAddr);
509 } catch (IllegalArgumentException e) {
510 Log.wtf(TAG, "Invalid address received from DhcpServer: "
511 + Arrays.toString(lease.hwAddr));
512 return;
513 }
514
515 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900516 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900517 leases.add(new TetheredClient(
518 macAddress,
519 Collections.singletonList(addressInfo),
520 mInterfaceType));
521 }
522
523 getHandler().post(() -> {
524 mDhcpLeases = leases;
525 mCallback.dhcpLeasesChanged();
526 });
527 }
528
529 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900530 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
531 Objects.requireNonNull(currentPrefix);
532 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900533 }
534
535 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900536 public int getInterfaceVersion() {
537 return this.VERSION;
538 }
539
540 @Override
541 public String getInterfaceHash() throws RemoteException {
542 return this.HASH;
543 }
544 }
545
Xiao Ma4455d6b2020-04-09 10:13:44 +0900546 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
547 Objects.requireNonNull(ipv4Address);
548 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
549 }
550
551 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
552 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
553 @Nullable Inet4Address clientAddr) {
554 final boolean changePrefixOnDecline =
555 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
markchienfb65dfe2022-02-25 23:14:58 +0800556 final int subnetPrefixLength = mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
557 ? mP2pLeasesSubnetPrefixLength : 0 /* default value */;
558
Xiao Ma4455d6b2020-04-09 10:13:44 +0900559 return new DhcpServingParamsParcelExt()
560 .setDefaultRouters(defaultRouter)
561 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
562 .setDnsServers(dnsServer)
563 .setServerAddr(serverAddr)
564 .setMetered(true)
565 .setSingleClientAddr(clientAddr)
markchienfb65dfe2022-02-25 23:14:58 +0800566 .setChangePrefixOnDecline(changePrefixOnDecline)
567 .setLeasesSubnetPrefixLength(subnetPrefixLength);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900568 // TODO: also advertise link MTU
569 }
570
markchien245352e2020-02-27 20:27:18 +0800571 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800572 if (mUsingLegacyDhcp) {
573 return true;
574 }
markchien245352e2020-02-27 20:27:18 +0800575
576 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800577 final Inet4Address clientAddr = clientLinkAddr == null ? null :
578 (Inet4Address) clientLinkAddr.getAddress();
579
Xiao Ma4455d6b2020-04-09 10:13:44 +0900580 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
581 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800582 mDhcpServerStartIndex++;
583 mDeps.makeDhcpServer(
584 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
585 return true;
586 }
587
588 private void stopDhcp() {
589 // Make all previous start requests obsolete so servers are not started later
590 mDhcpServerStartIndex++;
591
592 if (mDhcpServer != null) {
593 try {
594 mDhcpServer.stop(new OnHandlerStatusCallback() {
595 @Override
596 public void callback(int statusCode) {
597 if (statusCode != STATUS_SUCCESS) {
598 mLog.e("Error stopping DHCP server: " + statusCode);
Mark74461fc2022-12-14 08:49:40 +0000599 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800600 // Not much more we can do here
601 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900602 mDhcpLeases.clear();
603 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800604 }
605 });
606 mDhcpServer = null;
607 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900608 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800609 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800610 }
611 }
612 }
613
markchien245352e2020-02-27 20:27:18 +0800614 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
615 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800616 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800617 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800618 } else {
619 stopDhcp();
620 return true;
621 }
622 }
623
624 private void stopIPv4() {
Mark49649c92023-03-15 06:45:04 +0000625 configureIPv4(false /* enabled */, CONNECTIVITY_SCOPE_GLOBAL /* not used */);
markchien74a4fa92019-09-09 20:50:49 +0800626 // NOTE: All of configureIPv4() will be refactored out of existence
627 // into calls to InterfaceController, shared with startIPv4().
628 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800629 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800630 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800631 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800632 mStaticIpv4ServerAddr = null;
633 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800634 }
635
Mark49649c92023-03-15 06:45:04 +0000636 private boolean configureIPv4(boolean enabled, int scope) {
markchien74a4fa92019-09-09 20:50:49 +0800637 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
638
markchienc9daba32020-02-12 00:19:21 +0800639 if (enabled) {
Mark49649c92023-03-15 06:45:04 +0000640 mIpv4Address = requestIpv4Address(scope, true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800641 }
642
643 if (mIpv4Address == null) {
644 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800645 return false;
markchien74a4fa92019-09-09 20:50:49 +0800646 }
647
markchien69681d62021-11-15 23:58:05 +0800648 if (shouldNotConfigureBluetoothInterface()) {
649 // Interface was already configured elsewhere, only start DHCP.
markchienc9daba32020-02-12 00:19:21 +0800650 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
651 }
652
653 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
654
markchien12c5bb82020-01-07 14:43:17 +0800655 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800656 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900657 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200658 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
659 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900660 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800661 // It is unclear whether the Bluetooth or USB stacks will manage their own
662 // state.
663 setIfaceUp = null;
664 } else {
665 setIfaceUp = enabled;
666 }
667 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
668 mLog.e("Error configuring interface");
669 if (!enabled) stopDhcp();
670 return false;
671 }
markchien74a4fa92019-09-09 20:50:49 +0800672
markchien74a4fa92019-09-09 20:50:49 +0800673 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800674 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900675 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800676 } else {
markchien12c5bb82020-01-07 14:43:17 +0800677 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900678 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800679 }
markchien245352e2020-02-27 20:27:18 +0800680 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800681 }
682
markchien69681d62021-11-15 23:58:05 +0800683 private boolean shouldNotConfigureBluetoothInterface() {
684 // Before T, bluetooth tethering configures the interface elsewhere.
685 return (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) && !SdkLevel.isAtLeastT();
686 }
687
Mark49649c92023-03-15 06:45:04 +0000688 private LinkAddress requestIpv4Address(final int scope, final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800689 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800690
markchien69681d62021-11-15 23:58:05 +0800691 if (shouldNotConfigureBluetoothInterface()) return new LinkAddress(BLUETOOTH_IFACE_ADDR);
markchienc9daba32020-02-12 00:19:21 +0800692
Mark49649c92023-03-15 06:45:04 +0000693 return mPrivateAddressCoordinator.requestDownstreamAddress(this, scope, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900694 }
695
markchien74a4fa92019-09-09 20:50:49 +0800696 private boolean startIPv6() {
697 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
698 if (mInterfaceParams == null) {
699 mLog.e("Failed to find InterfaceParams");
700 stopIPv6();
701 return false;
702 }
703
704 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
705 if (!mRaDaemon.start()) {
706 stopIPv6();
707 return false;
708 }
709
markchien932df542021-08-12 13:56:43 +0800710 if (SdkLevel.isAtLeastS()) {
Tyler Wear90e40632020-03-13 11:38:38 -0700711 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
712 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
713 }
714
markchien74a4fa92019-09-09 20:50:49 +0800715 return true;
716 }
717
718 private void stopIPv6() {
719 mInterfaceParams = null;
720 setRaParams(null);
721
722 if (mRaDaemon != null) {
723 mRaDaemon.stop();
724 mRaDaemon = null;
725 }
Tyler Wear90e40632020-03-13 11:38:38 -0700726
727 if (mDadProxy != null) {
728 mDadProxy.stop();
729 mDadProxy = null;
730 }
markchien74a4fa92019-09-09 20:50:49 +0800731 }
732
733 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
734 // LinkProperties. These have extraneous data filtered out and only the
735 // necessary prefixes included (per its prefix distribution policy).
736 //
737 // TODO: Evaluate using a data structure than is more directly suited to
738 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800739 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800740 if (mRaDaemon == null) return;
741
742 // Avoid unnecessary work on spurious updates.
743 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
744 return;
745 }
746
747 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700748 String upstreamIface = null;
749 InterfaceParams upstreamIfaceParams = null;
KH Shi701c3ca2023-08-16 13:19:33 +0000750 int upstreamIfIndex = NO_UPSTREAM;
markchien74a4fa92019-09-09 20:50:49 +0800751
752 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700753 upstreamIface = v6only.getInterfaceName();
754 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
755 if (upstreamIfaceParams != null) {
756 upstreamIfIndex = upstreamIfaceParams.index;
757 }
markchien74a4fa92019-09-09 20:50:49 +0800758 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700759 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800760 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
761
markchiend63c4f32020-05-21 17:38:28 +0800762 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800763
764 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
765 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
766
767 final IpPrefix prefix = new IpPrefix(
768 linkAddr.getAddress(), linkAddr.getPrefixLength());
769 params.prefixes.add(prefix);
770
771 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
772 if (dnsServer != null) {
773 params.dnses.add(dnsServer);
774 }
775 }
776 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900777
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900778 // Add upstream index to name mapping. See the comment of the interface mapping update in
779 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
780 // timing issue. It prevents that the IPv6 capability is updated later than
781 // CMD_TETHER_CONNECTION_CHANGED.
KH Shi701c3ca2023-08-16 13:19:33 +0000782 mBpfCoordinator.maybeAddUpstreamToLookupTable(upstreamIfIndex, upstreamIface);
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900783
markchien74a4fa92019-09-09 20:50:49 +0800784 // If v6only is null, we pass in null to setRaParams(), which handles
785 // deprecation of any existing RA data.
markchien74a4fa92019-09-09 20:50:49 +0800786 setRaParams(params);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900787
KH Shi68770342023-08-17 14:34:31 +0000788 // Not support BPF on virtual upstream interface
789 final boolean upstreamSupportsBpf = upstreamIface != null && !isVcnInterface(upstreamIface);
KH Shi701c3ca2023-08-16 13:19:33 +0000790 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfIndex, upstreamSupportsBpf);
KH Shi68770342023-08-17 14:34:31 +0000791 mLastIPv6LinkProperties = v6only;
Tyler Wear90e40632020-03-13 11:38:38 -0700792 mLastIPv6UpstreamIfindex = upstreamIfIndex;
KH Shi68770342023-08-17 14:34:31 +0000793 mUpstreamSupportsBpf = upstreamSupportsBpf;
Tyler Wear90e40632020-03-13 11:38:38 -0700794 if (mDadProxy != null) {
795 mDadProxy.setUpstreamIface(upstreamIfaceParams);
796 }
markchien74a4fa92019-09-09 20:50:49 +0800797 }
798
Xiao Ma4455d6b2020-04-09 10:13:44 +0900799 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900800 final int removalFailures = NetdUtils.removeRoutesFromLocalNetwork(
Xiao Ma4455d6b2020-04-09 10:13:44 +0900801 mNetd, toBeRemoved);
802 if (removalFailures > 0) {
803 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
804 removalFailures));
805 }
806
807 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
808 }
809
810 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
811 try {
812 // It's safe to call networkAddInterface() even if
813 // the interface is already in the local_network.
814 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
815 try {
816 // Add routes from local network. Note that adding routes that
817 // already exist does not cause an error (EEXIST is silently ignored).
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900818 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900819 } catch (IllegalStateException e) {
820 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
821 return;
822 }
823 } catch (ServiceSpecificException | RemoteException e) {
824 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
825 return;
826 }
827
828 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
829 }
830
markchien74a4fa92019-09-09 20:50:49 +0800831 private void configureLocalIPv6Routes(
832 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
833 // [1] Remove the routes that are deprecated.
834 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900835 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800836 }
837
838 // [2] Add only the routes that have not previously been added.
839 if (newPrefixes != null && !newPrefixes.isEmpty()) {
840 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
841 if (mLastRaParams != null) {
842 addedPrefixes.removeAll(mLastRaParams.prefixes);
843 }
844
845 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900846 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800847 }
848 }
849 }
850
851 private void configureLocalIPv6Dns(
852 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
853 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
854 if (mNetd == null) {
855 if (newDnses != null) newDnses.clear();
856 mLog.e("No netd service instance available; not setting local IPv6 addresses");
857 return;
858 }
859
860 // [1] Remove deprecated local DNS IP addresses.
861 if (!deprecatedDnses.isEmpty()) {
862 for (Inet6Address dns : deprecatedDnses) {
863 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
864 mLog.e("Failed to remove local dns IP " + dns);
865 }
866
867 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
868 }
869 }
870
871 // [2] Add only the local DNS IP addresses that have not previously been added.
872 if (newDnses != null && !newDnses.isEmpty()) {
873 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
874 if (mLastRaParams != null) {
875 addedDnses.removeAll(mLastRaParams.dnses);
876 }
877
878 for (Inet6Address dns : addedDnses) {
879 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
880 mLog.e("Failed to add local dns IP " + dns);
881 newDnses.remove(dns);
882 }
883
884 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
885 }
886 }
887
888 try {
889 mNetd.tetherApplyDnsInterfaces();
890 } catch (ServiceSpecificException | RemoteException e) {
891 mLog.e("Failed to update local DNS caching server");
892 if (newDnses != null) newDnses.clear();
893 }
894 }
895
KH Shi701c3ca2023-08-16 13:19:33 +0000896 private int getInterfaceIndexForRule(int ifindex, boolean supportsBpf) {
897 return supportsBpf ? ifindex : NO_UPSTREAM;
898 }
899
900 // Handles updates to IPv6 forwarding rules if the upstream changes.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900901 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
KH Shi701c3ca2023-08-16 13:19:33 +0000902 boolean upstreamSupportsBpf) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900903 // If the upstream interface has changed, remove all rules and re-add them with the new
KH Shi701c3ca2023-08-16 13:19:33 +0000904 // upstream interface. If upstream is a virtual network, treated as no upstream.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900905 if (prevUpstreamIfindex != upstreamIfindex) {
KH Shi701c3ca2023-08-16 13:19:33 +0000906 mBpfCoordinator.updateAllIpv6Rules(this, this.mInterfaceParams,
907 getInterfaceIndexForRule(upstreamIfindex, upstreamSupportsBpf));
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900908 }
KH Shi701c3ca2023-08-16 13:19:33 +0000909 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900910
KH Shi701c3ca2023-08-16 13:19:33 +0000911 // Handles updates to IPv6 downstream rules if a neighbor event is received.
912 private void addOrRemoveIpv6Downstream(NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900913 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900914 if (e == null) return;
915 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
916 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
917 return;
918 }
919
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900920 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
KH Shi59ad35e2023-08-15 07:13:00 +0000921 // Do this here instead of in the Ipv6DownstreamRule constructor to ensure that we
922 // never add rules with a null MAC, only delete them.
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900923 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
KH Shi701c3ca2023-08-16 13:19:33 +0000924 Ipv6DownstreamRule rule = new Ipv6DownstreamRule(
925 getInterfaceIndexForRule(mLastIPv6UpstreamIfindex, mUpstreamSupportsBpf),
926 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900927 if (e.isValid()) {
KH Shie4d549a2023-08-28 09:57:34 +0000928 mBpfCoordinator.addIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900929 } else {
KH Shie4d549a2023-08-28 09:57:34 +0000930 mBpfCoordinator.removeIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900931 }
932 }
933
Hungming Chend71c06e2020-12-21 19:39:49 +0800934 // TODO: consider moving into BpfCoordinator.
935 private void updateClientInfoIpv4(NeighborEvent e) {
Hungming Chend71c06e2020-12-21 19:39:49 +0800936 if (e == null) return;
937 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
938 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
939 return;
940 }
941
942 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
943 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
944 // IpServer never add clients with a null MAC, only delete them.
945 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
946 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
947 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
948 if (e.isValid()) {
949 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
950 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +0800951 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
952 }
953 }
954
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900955 private void handleNeighborEvent(NeighborEvent e) {
956 if (mInterfaceParams != null
957 && mInterfaceParams.index == e.ifindex
958 && mInterfaceParams.hasMacAddress) {
KH Shi701c3ca2023-08-16 13:19:33 +0000959 addOrRemoveIpv6Downstream(e);
Hungming Chend71c06e2020-12-21 19:39:49 +0800960 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900961 }
962 }
963
markchiend63c4f32020-05-21 17:38:28 +0800964 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +0800965 try {
966 int upstreamHopLimit = Integer.parseUnsignedInt(
967 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +0800968 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +0800969 // Cap the hop limit to 255.
970 return (byte) Integer.min(upstreamHopLimit, 255);
971 } catch (Exception e) {
972 mLog.e("Failed to find upstream interface hop limit", e);
973 }
974 return RaParams.DEFAULT_HOPLIMIT;
975 }
976
977 private void setRaParams(RaParams newParams) {
978 if (mRaDaemon != null) {
979 final RaParams deprecatedParams =
980 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
981
982 configureLocalIPv6Routes(deprecatedParams.prefixes,
983 (newParams != null) ? newParams.prefixes : null);
984
985 configureLocalIPv6Dns(deprecatedParams.dnses,
986 (newParams != null) ? newParams.dnses : null);
987
988 mRaDaemon.buildNewRa(deprecatedParams, newParams);
989 }
990
991 mLastRaParams = newParams;
992 }
993
markchien21021ef2021-06-01 10:58:04 +0800994 private void maybeLogMessage(State state, int what) {
995 switch (what) {
996 // Suppress some CMD_* to avoid log flooding.
997 case CMD_IPV6_TETHER_UPDATE:
998 case CMD_NEIGHBOR_EVENT:
999 break;
1000 default:
1001 mLog.log(state.getName() + " got "
1002 + sMagicDecoderRing.get(what, Integer.toString(what)));
1003 }
markchien74a4fa92019-09-09 20:50:49 +08001004 }
1005
1006 private void sendInterfaceState(int newInterfaceState) {
1007 mServingMode = newInterfaceState;
1008 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1009 sendLinkProperties();
1010 }
1011
1012 private void sendLinkProperties() {
1013 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1014 }
1015
1016 private void resetLinkProperties() {
1017 mLinkProperties.clear();
1018 mLinkProperties.setInterfaceName(mIfaceName);
1019 }
1020
markchienf053e4b2020-03-16 21:49:48 +08001021 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001022 // Ignore static address configuration if they are invalid or null. In theory, static
1023 // addresses should not be invalid here because TetheringManager do not allow caller to
1024 // specify invalid static address configuration.
1025 if (request == null || request.localIPv4Address == null
1026 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1027 request.localIPv4Address, request.staticClientAddress)) {
1028 return;
1029 }
markchienf053e4b2020-03-16 21:49:48 +08001030
1031 mStaticIpv4ServerAddr = request.localIPv4Address;
1032 mStaticIpv4ClientAddr = request.staticClientAddress;
1033 }
1034
markchien74a4fa92019-09-09 20:50:49 +08001035 class InitialState extends State {
1036 @Override
1037 public void enter() {
1038 sendInterfaceState(STATE_AVAILABLE);
1039 }
1040
1041 @Override
1042 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001043 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001044 switch (message.what) {
1045 case CMD_TETHER_REQUESTED:
Mark74461fc2022-12-14 08:49:40 +00001046 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001047 switch (message.arg1) {
1048 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001049 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001050 transitionTo(mLocalHotspotState);
1051 break;
1052 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001053 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001054 transitionTo(mTetheredState);
1055 break;
1056 default:
1057 mLog.e("Invalid tethering interface serving state specified.");
1058 }
1059 break;
1060 case CMD_INTERFACE_DOWN:
1061 transitionTo(mUnavailableState);
1062 break;
markchien74a4fa92019-09-09 20:50:49 +08001063 default:
1064 return NOT_HANDLED;
1065 }
1066 return HANDLED;
1067 }
1068 }
1069
Hungming Chen46c30b12020-10-15 17:25:36 +08001070 private void startConntrackMonitoring() {
1071 mBpfCoordinator.startMonitoring(this);
1072 }
1073
1074 private void stopConntrackMonitoring() {
1075 mBpfCoordinator.stopMonitoring(this);
1076 }
1077
Mark3ec851e2023-05-19 08:50:38 +00001078 abstract class BaseServingState extends State {
1079 private final int mDesiredInterfaceState;
1080
1081 BaseServingState(int interfaceState) {
1082 mDesiredInterfaceState = interfaceState;
1083 }
1084
markchien74a4fa92019-09-09 20:50:49 +08001085 @Override
1086 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001087 startConntrackMonitoring();
1088
Mark3ec851e2023-05-19 08:50:38 +00001089 startServingInterface();
1090
1091 if (mLastError != TETHER_ERROR_NO_ERROR) {
1092 transitionTo(mInitialState);
1093 }
1094
1095 if (DBG) Log.d(TAG, getStateString(mDesiredInterfaceState) + " serve " + mIfaceName);
1096 sendInterfaceState(mDesiredInterfaceState);
1097 }
1098
Mark49649c92023-03-15 06:45:04 +00001099 private int getScope() {
1100 if (mDesiredInterfaceState == STATE_TETHERED) {
1101 return CONNECTIVITY_SCOPE_GLOBAL;
1102 }
1103
1104 return CONNECTIVITY_SCOPE_LOCAL;
1105 }
1106
Mark3ec851e2023-05-19 08:50:38 +00001107 private void startServingInterface() {
Mark49649c92023-03-15 06:45:04 +00001108 if (!startIPv4(getScope())) {
Mark74461fc2022-12-14 08:49:40 +00001109 mLastError = TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001110 return;
1111 }
1112
1113 try {
markchienc9daba32020-02-12 00:19:21 +08001114 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001115 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001116 mLog.e("Error Tethering", e);
Mark74461fc2022-12-14 08:49:40 +00001117 mLastError = TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001118 return;
1119 }
1120
1121 if (!startIPv6()) {
1122 mLog.e("Failed to startIPv6");
1123 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1124 return;
1125 }
1126 }
1127
1128 @Override
1129 public void exit() {
1130 // Note that at this point, we're leaving the tethered state. We can fail any
1131 // of these operations, but it doesn't really change that we have to try them
1132 // all in sequence.
1133 stopIPv6();
1134
1135 try {
markchien12c5bb82020-01-07 14:43:17 +08001136 NetdUtils.untetherInterface(mNetd, mIfaceName);
1137 } catch (RemoteException | ServiceSpecificException e) {
Mark74461fc2022-12-14 08:49:40 +00001138 mLastError = TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001139 mLog.e("Failed to untether interface: " + e);
1140 }
1141
1142 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001143 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001144
1145 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001146
1147 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1148 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001149 }
1150
1151 @Override
1152 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001153 switch (message.what) {
1154 case CMD_TETHER_UNREQUESTED:
1155 transitionTo(mInitialState);
1156 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1157 break;
1158 case CMD_INTERFACE_DOWN:
1159 transitionTo(mUnavailableState);
1160 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1161 break;
1162 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001163 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001164 sendLinkProperties();
1165 break;
1166 case CMD_IP_FORWARDING_ENABLE_ERROR:
1167 case CMD_IP_FORWARDING_DISABLE_ERROR:
1168 case CMD_START_TETHERING_ERROR:
1169 case CMD_STOP_TETHERING_ERROR:
1170 case CMD_SET_DNS_FORWARDERS_ERROR:
Mark74461fc2022-12-14 08:49:40 +00001171 mLastError = TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001172 transitionTo(mInitialState);
1173 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001174 case CMD_NEW_PREFIX_REQUEST:
1175 handleNewPrefixRequest((IpPrefix) message.obj);
1176 break;
markchienc9daba32020-02-12 00:19:21 +08001177 case CMD_NOTIFY_PREFIX_CONFLICT:
1178 mLog.i("restart tethering: " + mInterfaceType);
1179 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1180 transitionTo(mWaitingForRestartState);
1181 break;
markchien74a4fa92019-09-09 20:50:49 +08001182 default:
1183 return false;
1184 }
1185 return true;
1186 }
Mark3ec851e2023-05-19 08:50:38 +00001187
1188 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
1189 if (!currentPrefix.contains(mIpv4Address.getAddress())
1190 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
1191 Log.e(TAG, "Invalid prefix: " + currentPrefix);
1192 return;
1193 }
1194
1195 final LinkAddress deprecatedLinkAddress = mIpv4Address;
Mark49649c92023-03-15 06:45:04 +00001196 mIpv4Address = requestIpv4Address(getScope(), false);
Mark3ec851e2023-05-19 08:50:38 +00001197 if (mIpv4Address == null) {
1198 mLog.e("Fail to request a new downstream prefix");
1199 return;
1200 }
1201 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
1202
1203 // Add new IPv4 address on the interface.
1204 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1205 mLog.e("Failed to add new IP " + srvAddr);
1206 return;
1207 }
1208
1209 // Remove deprecated routes from local network.
1210 removeRoutesFromLocalNetwork(
1211 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1212 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1213
1214 // Add new routes to local network.
1215 addRoutesToLocalNetwork(
1216 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1217 mLinkProperties.addLinkAddress(mIpv4Address);
1218
1219 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1220 // listen on the interface configured with new IPv4 address, that results DNS validation
1221 // failure of downstream client even if appropriate routes have been configured.
1222 try {
1223 mNetd.tetherApplyDnsInterfaces();
1224 } catch (ServiceSpecificException | RemoteException e) {
1225 mLog.e("Failed to update local DNS caching server");
1226 return;
1227 }
1228 sendLinkProperties();
1229
1230 // Notify DHCP server that new prefix/route has been applied on IpServer.
1231 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1232 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1233 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1234 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1235 try {
1236 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1237 @Override
1238 public void callback(int statusCode) {
1239 if (statusCode != STATUS_SUCCESS) {
1240 mLog.e("Error updating DHCP serving params: " + statusCode);
1241 }
1242 }
1243 });
1244 } catch (RemoteException e) {
1245 mLog.e("Error updating DHCP serving params", e);
1246 }
1247 }
markchien74a4fa92019-09-09 20:50:49 +08001248 }
1249
1250 // Handling errors in BaseServingState.enter() by transitioning is
1251 // problematic because transitioning during a multi-state jump yields
1252 // a Log.wtf(). Ultimately, there should be only one ServingState,
1253 // and forwarding and NAT rules should be handled by a coordinating
1254 // functional element outside of IpServer.
1255 class LocalHotspotState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001256 LocalHotspotState() {
1257 super(STATE_LOCAL_ONLY);
markchien74a4fa92019-09-09 20:50:49 +08001258 }
1259
1260 @Override
1261 public boolean processMessage(Message message) {
1262 if (super.processMessage(message)) return true;
1263
markchien21021ef2021-06-01 10:58:04 +08001264 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001265 switch (message.what) {
1266 case CMD_TETHER_REQUESTED:
1267 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1268 break;
1269 case CMD_TETHER_CONNECTION_CHANGED:
1270 // Ignored in local hotspot state.
1271 break;
1272 default:
1273 return false;
1274 }
1275 return true;
1276 }
1277 }
1278
1279 // Handling errors in BaseServingState.enter() by transitioning is
1280 // problematic because transitioning during a multi-state jump yields
1281 // a Log.wtf(). Ultimately, there should be only one ServingState,
1282 // and forwarding and NAT rules should be handled by a coordinating
1283 // functional element outside of IpServer.
1284 class TetheredState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001285 TetheredState() {
1286 super(STATE_TETHERED);
markchien74a4fa92019-09-09 20:50:49 +08001287 }
1288
1289 @Override
1290 public void exit() {
1291 cleanupUpstream();
KH Shi701c3ca2023-08-16 13:19:33 +00001292 mBpfCoordinator.clearAllIpv6Rules(IpServer.this);
markchien74a4fa92019-09-09 20:50:49 +08001293 super.exit();
1294 }
1295
Hungming Chena6e78692021-02-08 17:15:35 +08001296 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1297 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1298 // and behaviour. While upstream is switching from offload supported interface to
1299 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1300 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1301 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1302 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1303 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1304 // in the state machine. Once there is any case out whish is not covered by previous cases,
1305 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001306 private void cleanupUpstream() {
1307 if (mUpstreamIfaceSet == null) return;
1308
1309 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1310 mUpstreamIfaceSet = null;
KH Shi701c3ca2023-08-16 13:19:33 +00001311 mBpfCoordinator.updateAllIpv6Rules(
1312 IpServer.this, IpServer.this.mInterfaceParams, NO_UPSTREAM);
markchien74a4fa92019-09-09 20:50:49 +08001313 }
1314
1315 private void cleanupUpstreamInterface(String upstreamIface) {
1316 // Note that we don't care about errors here.
1317 // Sometimes interfaces are gone before we get
1318 // to remove their rules, which generates errors.
1319 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001320 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001321 try {
markchien12c5bb82020-01-07 14:43:17 +08001322 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1323 } catch (RemoteException | ServiceSpecificException e) {
1324 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001325 }
1326 try {
markchien12c5bb82020-01-07 14:43:17 +08001327 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1328 } catch (RemoteException | ServiceSpecificException e) {
1329 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001330 }
1331 }
1332
1333 @Override
1334 public boolean processMessage(Message message) {
1335 if (super.processMessage(message)) return true;
1336
markchien21021ef2021-06-01 10:58:04 +08001337 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001338 switch (message.what) {
1339 case CMD_TETHER_REQUESTED:
1340 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1341 break;
1342 case CMD_TETHER_CONNECTION_CHANGED:
1343 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1344 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1345 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1346 break;
1347 }
1348
1349 if (newUpstreamIfaceSet == null) {
1350 cleanupUpstream();
1351 break;
1352 }
1353
1354 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1355 cleanupUpstreamInterface(removed);
1356 }
1357
1358 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1359 // This makes the call to cleanupUpstream() in the error
1360 // path for any interface neatly cleanup all the interfaces.
1361 mUpstreamIfaceSet = newUpstreamIfaceSet;
1362
1363 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001364 // Add upstream index to name mapping for the tether stats usage in the
1365 // coordinator. Although this mapping could be added by both class
1366 // Tethering and IpServer, adding mapping from IpServer guarantees that
1367 // the mapping is added before adding forwarding rules. That is because
1368 // there are different state machines in both classes. It is hard to
1369 // guarantee the link property update order between multiple state machines.
1370 // Note that both IPv4 and IPv6 interface may be added because
1371 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1372 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1373 // capability may be updated later. In that case, IPv6 interface mapping is
1374 // updated in updateUpstreamIPv6LinkProperties.
1375 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1376 final InterfaceParams upstreamIfaceParams =
1377 mDeps.getInterfaceParams(ifname);
1378 if (upstreamIfaceParams != null) {
KH Shi701c3ca2023-08-16 13:19:33 +00001379 mBpfCoordinator.maybeAddUpstreamToLookupTable(
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001380 upstreamIfaceParams.index, ifname);
1381 }
1382 }
1383
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001384 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001385 try {
markchien12c5bb82020-01-07 14:43:17 +08001386 mNetd.tetherAddForward(mIfaceName, ifname);
1387 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1388 } catch (RemoteException | ServiceSpecificException e) {
1389 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001390 cleanupUpstream();
Mark74461fc2022-12-14 08:49:40 +00001391 mLastError = TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001392 transitionTo(mInitialState);
1393 return true;
1394 }
1395 }
1396 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001397 case CMD_NEIGHBOR_EVENT:
1398 handleNeighborEvent((NeighborEvent) message.obj);
1399 break;
markchien74a4fa92019-09-09 20:50:49 +08001400 default:
1401 return false;
1402 }
1403 return true;
1404 }
1405
1406 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1407 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1408 if (mUpstreamIfaceSet != null && newIfaces != null) {
1409 return mUpstreamIfaceSet.equals(newIfaces);
1410 }
1411 return false;
1412 }
1413
1414 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1415 if (mUpstreamIfaceSet == null) return new HashSet<>();
1416
1417 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1418 removed.removeAll(newIfaces.ifnames);
1419 return removed;
1420 }
1421
1422 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1423 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1424 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1425 return added;
1426 }
1427 }
1428
1429 /**
1430 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001431 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001432 * specific state machine from its list of possible recipients of
1433 * tethering requests. The state machine itself will hang around until
1434 * the garbage collector finds it.
1435 */
1436 class UnavailableState extends State {
1437 @Override
1438 public void enter() {
KH Shi701c3ca2023-08-16 13:19:33 +00001439 // TODO: move mIpNeighborMonitor.stop() to TetheredState#exit, and trigger a neighbours
1440 // dump after starting mIpNeighborMonitor.
h.zhangd244bd02020-06-14 14:46:54 +08001441 mIpNeighborMonitor.stop();
Mark74461fc2022-12-14 08:49:40 +00001442 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001443 sendInterfaceState(STATE_UNAVAILABLE);
1444 }
1445 }
1446
markchienc9daba32020-02-12 00:19:21 +08001447 class WaitingForRestartState extends State {
1448 @Override
1449 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001450 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001451 switch (message.what) {
1452 case CMD_TETHER_UNREQUESTED:
1453 transitionTo(mInitialState);
1454 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1455 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1456 break;
1457 case CMD_INTERFACE_DOWN:
1458 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001459 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001460 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1461 break;
1462 default:
1463 return false;
1464 }
1465 return true;
1466 }
1467 }
1468
markchien74a4fa92019-09-09 20:50:49 +08001469 // Accumulate routes representing "prefixes to be assigned to the local
1470 // interface", for subsequent modification of local_network routing.
1471 private static ArrayList<RouteInfo> getLocalRoutesFor(
1472 String ifname, HashSet<IpPrefix> prefixes) {
1473 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1474 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001475 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001476 }
1477 return localRoutes;
1478 }
1479
1480 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1481 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1482 final byte[] dnsBytes = localPrefix.getRawAddress();
1483 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1484 try {
1485 return Inet6Address.getByAddress(null, dnsBytes, 0);
1486 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001487 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001488 return null;
1489 }
1490 }
1491
1492 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1493 final byte random = (byte) (new Random()).nextInt();
1494 for (int value : excluded) {
1495 if (random == value) return dflt;
1496 }
1497 return random;
1498 }
1499}