blob: 9d0f6b4b84e7e142e35a8d51d354f851c6afb679 [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;
Mark74461fc2022-12-14 08:49:40 +000020import static android.net.TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
21import static android.net.TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
22import static android.net.TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
23import static android.net.TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
24import static android.net.TetheringManager.TETHER_ERROR_NO_ERROR;
25import static android.net.TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
26import static android.net.TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien245352e2020-02-27 20:27:18 +080027import static android.net.TetheringManager.TetheringRequest.checkStaticAddressConfiguration;
markchien74a4fa92019-09-09 20:50:49 +080028import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
markchien74a4fa92019-09-09 20:50:49 +080029import static android.net.util.NetworkConstants.RFC7421_PREFIX_LENGTH;
30import static android.net.util.NetworkConstants.asByte;
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +090031import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080032
Chalard Jean78701642020-07-31 20:00:30 +090033import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH;
markchien7dc1b4d2021-07-13 17:12:56 +080034import static com.android.networkstack.tethering.UpstreamNetworkState.isVcnInterface;
markchiend02f9af2021-11-04 11:26:03 +080035import static com.android.networkstack.tethering.util.PrefixUtils.asIpPrefix;
36import static com.android.networkstack.tethering.util.TetheringMessageBase.BASE_IPSERVER;
Chalard Jean78701642020-07-31 20:00:30 +090037
markchien74a4fa92019-09-09 20:50:49 +080038import android.net.INetd;
39import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080040import android.net.IpPrefix;
41import android.net.LinkAddress;
42import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090043import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080044import android.net.RouteInfo;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090045import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080046import android.net.TetheringManager;
markchienf053e4b2020-03-16 21:49:48 +080047import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090048import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080049import android.net.dhcp.DhcpServerCallbacks;
50import android.net.dhcp.DhcpServingParamsParcel;
51import android.net.dhcp.DhcpServingParamsParcelExt;
Xiao Ma49889dd2020-04-03 17:01:33 +090052import android.net.dhcp.IDhcpEventCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080053import android.net.dhcp.IDhcpServer;
54import android.net.ip.RouterAdvertisementDaemon.RaParams;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090055import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080056import android.os.Looper;
57import android.os.Message;
58import android.os.RemoteException;
59import android.os.ServiceSpecificException;
60import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080061import android.util.SparseArray;
62
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090063import androidx.annotation.NonNull;
Xiao Ma4455d6b2020-04-09 10:13:44 +090064import androidx.annotation.Nullable;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090065
markchien74a4fa92019-09-09 20:50:49 +080066import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080067import com.android.internal.util.State;
68import com.android.internal.util.StateMachine;
markchien932df542021-08-12 13:56:43 +080069import com.android.modules.utils.build.SdkLevel;
Patrick Rohr9f371f02022-03-04 15:14:27 +010070import com.android.net.module.util.InterfaceParams;
Chalard Jeanadcec9e2021-10-29 15:57:22 +090071import com.android.net.module.util.NetdUtils;
Patrick Rohrb873e252022-06-16 16:38:43 -070072import com.android.net.module.util.SharedLog;
Xiao Mac81c0662022-06-17 14:58:03 +090073import com.android.net.module.util.ip.InterfaceController;
74import com.android.net.module.util.ip.IpNeighborMonitor;
75import com.android.net.module.util.ip.IpNeighborMonitor.NeighborEvent;
Hungming Chen68f1c2a2020-03-12 21:24:01 +080076import com.android.networkstack.tethering.BpfCoordinator;
Hungming Chend71c06e2020-12-21 19:39:49 +080077import com.android.networkstack.tethering.BpfCoordinator.ClientInfo;
Hungming Chenb150b872020-05-23 22:54:49 +080078import com.android.networkstack.tethering.BpfCoordinator.Ipv6ForwardingRule;
markchienc9daba32020-02-12 00:19:21 +080079import com.android.networkstack.tethering.PrivateAddressCoordinator;
markchienb961d3d2022-02-26 00:39:06 +080080import com.android.networkstack.tethering.TetheringConfiguration;
Wayne Ma6cd440f2022-03-14 18:04:33 +080081import com.android.networkstack.tethering.metrics.TetheringMetrics;
markchiend02f9af2021-11-04 11:26:03 +080082import com.android.networkstack.tethering.util.InterfaceSet;
83import com.android.networkstack.tethering.util.PrefixUtils;
markchien74a4fa92019-09-09 20:50:49 +080084
85import java.net.Inet4Address;
86import java.net.Inet6Address;
markchien74a4fa92019-09-09 20:50:49 +080087import java.net.UnknownHostException;
88import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090089import java.util.Arrays;
90import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080091import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090092import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080093import java.util.Objects;
94import java.util.Random;
95import java.util.Set;
96
97/**
98 * Provides the interface to IP-layer serving functionality for a given network
99 * interface, e.g. for tethering or "local-only hotspot" mode.
100 *
101 * @hide
102 */
103public class IpServer extends StateMachine {
104 public static final int STATE_UNAVAILABLE = 0;
105 public static final int STATE_AVAILABLE = 1;
106 public static final int STATE_TETHERED = 2;
107 public static final int STATE_LOCAL_ONLY = 3;
108
109 /** Get string name of |state|.*/
110 public static String getStateString(int state) {
111 switch (state) {
112 case STATE_UNAVAILABLE: return "UNAVAILABLE";
113 case STATE_AVAILABLE: return "AVAILABLE";
114 case STATE_TETHERED: return "TETHERED";
115 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
116 }
117 return "UNKNOWN: " + state;
118 }
119
120 private static final byte DOUG_ADAMS = (byte) 42;
121
markchien74a4fa92019-09-09 20:50:49 +0800122 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800123 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800124
125 // TODO: have this configurable
126 private static final int DHCP_LEASE_TIME_SECS = 3600;
127
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900128 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
129
markchien74a4fa92019-09-09 20:50:49 +0800130 private static final String TAG = "IpServer";
131 private static final boolean DBG = false;
132 private static final boolean VDBG = false;
133 private static final Class[] sMessageClasses = {
134 IpServer.class
135 };
136 private static final SparseArray<String> sMagicDecoderRing =
137 MessageUtils.findMessageNames(sMessageClasses);
138
139 /** IpServer callback. */
140 public static class Callback {
141 /**
142 * Notify that |who| has changed its tethering state.
143 *
144 * @param who the calling instance of IpServer
145 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800146 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800147 */
markchien9d353822019-12-16 20:15:20 +0800148 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800149
150 /**
151 * Notify that |who| has new LinkProperties.
152 *
153 * @param who the calling instance of IpServer
154 * @param newLp the new LinkProperties to report
155 */
markchien9d353822019-12-16 20:15:20 +0800156 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900157
158 /**
159 * Notify that the DHCP leases changed in one of the IpServers.
160 */
161 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800162
163 /**
164 * Request Tethering change.
165 *
166 * @param tetheringType the downstream type of this IpServer.
167 * @param enabled enable or disable tethering.
168 */
169 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800170 }
171
172 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800173 public abstract static class Dependencies {
Tyler Wear90e40632020-03-13 11:38:38 -0700174 /**
175 * Create a DadProxy instance to be used by IpServer.
176 * To support multiple tethered interfaces concurrently DAD Proxy
177 * needs to be supported per IpServer instead of per upstream.
178 */
179 public DadProxy getDadProxy(Handler handler, InterfaceParams ifParams) {
180 return new DadProxy(handler, ifParams);
181 }
182
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900183 /** Create an IpNeighborMonitor to be used by this IpServer */
184 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
185 IpNeighborMonitor.NeighborEventConsumer consumer) {
186 return new IpNeighborMonitor(handler, log, consumer);
187 }
188
markchien74a4fa92019-09-09 20:50:49 +0800189 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
190 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
191 return new RouterAdvertisementDaemon(ifParams);
192 }
193
194 /** Get |ifName|'s interface information.*/
195 public InterfaceParams getInterfaceParams(String ifName) {
196 return InterfaceParams.getByName(ifName);
197 }
198
markchien9d353822019-12-16 20:15:20 +0800199 /** Create a DhcpServer instance to be used by IpServer. */
200 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
201 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800202 }
203
markchien74a4fa92019-09-09 20:50:49 +0800204 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800205 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800206 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800207 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800208 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800209 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800210 // notification from the {@link Tethering.TetherMainSM} that it had trouble enabling IP
211 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800212 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800213 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble disabling IP
214 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800215 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800216 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble starting
217 // tethering
markchien6cf0e552019-12-06 15:24:53 +0800218 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800219 // notification from the {@link Tethering.TetherMainSM} that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800220 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800221 // notification from the {@link Tethering.TetherMainSM} that it had trouble setting the DNS
222 // forwarders
markchien6cf0e552019-12-06 15:24:53 +0800223 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800224 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800225 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800226 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800227 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900228 // new neighbor cache entry on our interface
229 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900230 // request from DHCP server that it wants to have a new prefix
231 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800232 // request from PrivateAddressCoordinator to restart tethering.
233 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
markchien74a4fa92019-09-09 20:50:49 +0800234
235 private final State mInitialState;
236 private final State mLocalHotspotState;
237 private final State mTetheredState;
238 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800239 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800240
241 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800242 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800243 @NonNull
244 private final BpfCoordinator mBpfCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800245 private final Callback mCallback;
246 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800247 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800248
249 private final String mIfaceName;
250 private final int mInterfaceType;
251 private final LinkProperties mLinkProperties;
252 private final boolean mUsingLegacyDhcp;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800253 private final boolean mUsingBpfOffload;
markchienfb65dfe2022-02-25 23:14:58 +0800254 private final int mP2pLeasesSubnetPrefixLength;
markchien74a4fa92019-09-09 20:50:49 +0800255
256 private final Dependencies mDeps;
257
258 private int mLastError;
259 private int mServingMode;
260 private InterfaceSet mUpstreamIfaceSet; // may change over time
261 private InterfaceParams mInterfaceParams;
262 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
263 // properties are those selected by the IPv6TetheringCoordinator and relayed
264 // to us. By comparison, mLinkProperties contains the addresses and directly
265 // connected routes that have been formed from these properties iff. we have
266 // succeeded in configuring them and are able to announce them within Router
267 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
268 private LinkProperties mLastIPv6LinkProperties;
269 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700270 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800271
272 // To be accessed only on the handler thread
273 private int mDhcpServerStartIndex = 0;
274 private IDhcpServer mDhcpServer;
275 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800276
277 private LinkAddress mStaticIpv4ServerAddr;
278 private LinkAddress mStaticIpv4ClientAddr;
279
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900280 @NonNull
281 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800282
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900283 private int mLastIPv6UpstreamIfindex = 0;
284
285 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
286 public void accept(NeighborEvent e) {
287 sendMessage(CMD_NEIGHBOR_EVENT, e);
288 }
289 }
290
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900291 private final IpNeighborMonitor mIpNeighborMonitor;
292
markchienc9daba32020-02-12 00:19:21 +0800293 private LinkAddress mIpv4Address;
294
Wayne Ma6cd440f2022-03-14 18:04:33 +0800295 private final TetheringMetrics mTetheringMetrics;
296
Hungming Chen5bc3af92020-05-12 19:15:24 +0800297 // TODO: Add a dependency object to pass the data members or variables from the tethering
298 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800299 public IpServer(
300 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800301 INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
markchienb961d3d2022-02-26 00:39:06 +0800302 TetheringConfiguration config, PrivateAddressCoordinator addressCoordinator,
Wayne Ma6cd440f2022-03-14 18:04:33 +0800303 TetheringMetrics tetheringMetrics, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800304 super(ifaceName, looper);
305 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800306 mNetd = netd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800307 mBpfCoordinator = coordinator;
markchien74a4fa92019-09-09 20:50:49 +0800308 mCallback = callback;
309 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
310 mIfaceName = ifaceName;
311 mInterfaceType = interfaceType;
312 mLinkProperties = new LinkProperties();
markchienb961d3d2022-02-26 00:39:06 +0800313 mUsingLegacyDhcp = config.useLegacyDhcpServer();
314 mUsingBpfOffload = config.isBpfOffloadEnabled();
markchienfb65dfe2022-02-25 23:14:58 +0800315 mP2pLeasesSubnetPrefixLength = config.getP2pLeasesSubnetPrefixLength();
markchienc9daba32020-02-12 00:19:21 +0800316 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800317 mDeps = deps;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800318 mTetheringMetrics = tetheringMetrics;
markchien74a4fa92019-09-09 20:50:49 +0800319 resetLinkProperties();
Mark74461fc2022-12-14 08:49:40 +0000320 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800321 mServingMode = STATE_AVAILABLE;
322
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900323 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
324 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800325
Hungming Chen5bc3af92020-05-12 19:15:24 +0800326 // IP neighbor monitor monitors the neighbor events for adding/removing offload
Hungming Chen3d8fa882020-04-12 14:27:18 +0800327 // forwarding rules per client. If BPF offload is not supported, don't start listening
Hungming Chen5bc3af92020-05-12 19:15:24 +0800328 // for neighbor events. See updateIpv6ForwardingRules, addIpv6ForwardingRule,
Hungming Chen3d8fa882020-04-12 14:27:18 +0800329 // removeIpv6ForwardingRule.
Hungming Chen5bc3af92020-05-12 19:15:24 +0800330 if (mUsingBpfOffload && !mIpNeighborMonitor.start()) {
331 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900332 }
333
markchien74a4fa92019-09-09 20:50:49 +0800334 mInitialState = new InitialState();
335 mLocalHotspotState = new LocalHotspotState();
336 mTetheredState = new TetheredState();
337 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800338 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800339 addState(mInitialState);
340 addState(mLocalHotspotState);
341 addState(mTetheredState);
markchienc9daba32020-02-12 00:19:21 +0800342 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800343 addState(mUnavailableState);
344
345 setInitialState(mInitialState);
346 }
347
348 /** Interface name which IpServer served.*/
349 public String interfaceName() {
350 return mIfaceName;
351 }
352
353 /**
markchien9b4d7572019-12-25 19:40:32 +0800354 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800355 */
356 public int interfaceType() {
357 return mInterfaceType;
358 }
359
360 /** Last error from this IpServer. */
361 public int lastError() {
362 return mLastError;
363 }
364
365 /** Serving mode is the current state of IpServer state machine. */
366 public int servingMode() {
367 return mServingMode;
368 }
369
370 /** The properties of the network link which IpServer is serving. */
371 public LinkProperties linkProperties() {
372 return new LinkProperties(mLinkProperties);
373 }
374
markchienc9daba32020-02-12 00:19:21 +0800375 /** The address which IpServer is using. */
376 public LinkAddress getAddress() {
377 return mIpv4Address;
378 }
379
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900380 /**
381 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
382 * thread.
383 */
384 public List<TetheredClient> getAllLeases() {
385 return Collections.unmodifiableList(mDhcpLeases);
386 }
387
Marka5424582022-12-01 13:46:32 +0000388 /** Enable this IpServer. IpServer state machine will be tethered or localHotspot state. */
389 public void enable(final int requestedState, final TetheringRequestParcel request) {
390 sendMessage(CMD_TETHER_REQUESTED, requestedState, 0, request);
391 }
392
markchien74a4fa92019-09-09 20:50:49 +0800393 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
394 public void stop() {
395 sendMessage(CMD_INTERFACE_DOWN);
396 }
397
398 /**
399 * Tethering is canceled. IpServer state machine will be available and wait for
400 * next tethering request.
401 */
402 public void unwanted() {
403 sendMessage(CMD_TETHER_UNREQUESTED);
404 }
405
406 /** Internals. */
407
408 private boolean startIPv4() {
409 return configureIPv4(true);
410 }
411
412 /**
413 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
414 * handler.
415 *
416 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
417 * with different implementations of the callback, to differentiate handling of success/error in
418 * each call.
419 */
420 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
421 @Override
422 public void onStatusAvailable(int statusCode) {
423 getHandler().post(() -> callback(statusCode));
424 }
425
426 public abstract void callback(int statusCode);
427
428 @Override
429 public int getInterfaceVersion() {
430 return this.VERSION;
431 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900432
433 @Override
434 public String getInterfaceHash() {
435 return this.HASH;
436 }
markchien74a4fa92019-09-09 20:50:49 +0800437 }
438
439 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
440 private final int mStartIndex;
441
442 private DhcpServerCallbacksImpl(int startIndex) {
443 mStartIndex = startIndex;
444 }
445
446 @Override
447 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
448 getHandler().post(() -> {
449 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
450 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800451 // This start request is obsolete. Explicitly stop the DHCP server to shut
452 // down its thread. When the |server| binder token goes out of scope, the
453 // garbage collector will finalize it, which causes the network stack process
454 // garbage collector to collect the server itself.
455 try {
456 server.stop(null);
457 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800458 return;
459 }
460
461 if (statusCode != STATUS_SUCCESS) {
462 mLog.e("Error obtaining DHCP server: " + statusCode);
463 handleError();
464 return;
465 }
466
467 mDhcpServer = server;
468 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900469 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800470 @Override
471 public void callback(int startStatusCode) {
472 if (startStatusCode != STATUS_SUCCESS) {
473 mLog.e("Error starting DHCP server: " + startStatusCode);
474 handleError();
475 }
476 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900477 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800478 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800479 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800480 }
481 });
482 }
483
484 private void handleError() {
Mark74461fc2022-12-14 08:49:40 +0000485 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800486 transitionTo(mInitialState);
487 }
488 }
489
Xiao Ma4455d6b2020-04-09 10:13:44 +0900490 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900491 @Override
492 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
493 final ArrayList<TetheredClient> leases = new ArrayList<>();
494 for (DhcpLeaseParcelable lease : leaseParcelables) {
495 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900496 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
497 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
498 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900499
500 final MacAddress macAddress;
501 try {
502 macAddress = MacAddress.fromBytes(lease.hwAddr);
503 } catch (IllegalArgumentException e) {
504 Log.wtf(TAG, "Invalid address received from DhcpServer: "
505 + Arrays.toString(lease.hwAddr));
506 return;
507 }
508
509 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900510 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900511 leases.add(new TetheredClient(
512 macAddress,
513 Collections.singletonList(addressInfo),
514 mInterfaceType));
515 }
516
517 getHandler().post(() -> {
518 mDhcpLeases = leases;
519 mCallback.dhcpLeasesChanged();
520 });
521 }
522
523 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900524 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
525 Objects.requireNonNull(currentPrefix);
526 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900527 }
528
529 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900530 public int getInterfaceVersion() {
531 return this.VERSION;
532 }
533
534 @Override
535 public String getInterfaceHash() throws RemoteException {
536 return this.HASH;
537 }
538 }
539
Xiao Ma4455d6b2020-04-09 10:13:44 +0900540 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
541 Objects.requireNonNull(ipv4Address);
542 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
543 }
544
545 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
546 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
547 @Nullable Inet4Address clientAddr) {
548 final boolean changePrefixOnDecline =
549 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
markchienfb65dfe2022-02-25 23:14:58 +0800550 final int subnetPrefixLength = mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
551 ? mP2pLeasesSubnetPrefixLength : 0 /* default value */;
552
Xiao Ma4455d6b2020-04-09 10:13:44 +0900553 return new DhcpServingParamsParcelExt()
554 .setDefaultRouters(defaultRouter)
555 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
556 .setDnsServers(dnsServer)
557 .setServerAddr(serverAddr)
558 .setMetered(true)
559 .setSingleClientAddr(clientAddr)
markchienfb65dfe2022-02-25 23:14:58 +0800560 .setChangePrefixOnDecline(changePrefixOnDecline)
561 .setLeasesSubnetPrefixLength(subnetPrefixLength);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900562 // TODO: also advertise link MTU
563 }
564
markchien245352e2020-02-27 20:27:18 +0800565 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800566 if (mUsingLegacyDhcp) {
567 return true;
568 }
markchien245352e2020-02-27 20:27:18 +0800569
570 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800571 final Inet4Address clientAddr = clientLinkAddr == null ? null :
572 (Inet4Address) clientLinkAddr.getAddress();
573
Xiao Ma4455d6b2020-04-09 10:13:44 +0900574 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
575 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800576 mDhcpServerStartIndex++;
577 mDeps.makeDhcpServer(
578 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
579 return true;
580 }
581
582 private void stopDhcp() {
583 // Make all previous start requests obsolete so servers are not started later
584 mDhcpServerStartIndex++;
585
586 if (mDhcpServer != null) {
587 try {
588 mDhcpServer.stop(new OnHandlerStatusCallback() {
589 @Override
590 public void callback(int statusCode) {
591 if (statusCode != STATUS_SUCCESS) {
592 mLog.e("Error stopping DHCP server: " + statusCode);
Mark74461fc2022-12-14 08:49:40 +0000593 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800594 // Not much more we can do here
595 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900596 mDhcpLeases.clear();
597 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800598 }
599 });
600 mDhcpServer = null;
601 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900602 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800603 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800604 }
605 }
606 }
607
markchien245352e2020-02-27 20:27:18 +0800608 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
609 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800610 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800611 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800612 } else {
613 stopDhcp();
614 return true;
615 }
616 }
617
618 private void stopIPv4() {
619 configureIPv4(false);
620 // NOTE: All of configureIPv4() will be refactored out of existence
621 // into calls to InterfaceController, shared with startIPv4().
622 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800623 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800624 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800625 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800626 mStaticIpv4ServerAddr = null;
627 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800628 }
629
markchien74a4fa92019-09-09 20:50:49 +0800630 private boolean configureIPv4(boolean enabled) {
631 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
632
markchienc9daba32020-02-12 00:19:21 +0800633 if (enabled) {
markchiena2ffad82020-09-22 15:50:43 +0800634 mIpv4Address = requestIpv4Address(true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800635 }
636
637 if (mIpv4Address == null) {
638 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800639 return false;
markchien74a4fa92019-09-09 20:50:49 +0800640 }
641
markchien69681d62021-11-15 23:58:05 +0800642 if (shouldNotConfigureBluetoothInterface()) {
643 // Interface was already configured elsewhere, only start DHCP.
markchienc9daba32020-02-12 00:19:21 +0800644 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
645 }
646
647 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
648
markchien12c5bb82020-01-07 14:43:17 +0800649 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800650 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900651 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200652 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
653 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900654 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800655 // It is unclear whether the Bluetooth or USB stacks will manage their own
656 // state.
657 setIfaceUp = null;
658 } else {
659 setIfaceUp = enabled;
660 }
661 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
662 mLog.e("Error configuring interface");
663 if (!enabled) stopDhcp();
664 return false;
665 }
markchien74a4fa92019-09-09 20:50:49 +0800666
markchien74a4fa92019-09-09 20:50:49 +0800667 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800668 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900669 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800670 } else {
markchien12c5bb82020-01-07 14:43:17 +0800671 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900672 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800673 }
markchien245352e2020-02-27 20:27:18 +0800674 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800675 }
676
markchien69681d62021-11-15 23:58:05 +0800677 private boolean shouldNotConfigureBluetoothInterface() {
678 // Before T, bluetooth tethering configures the interface elsewhere.
679 return (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) && !SdkLevel.isAtLeastT();
680 }
681
markchiena2ffad82020-09-22 15:50:43 +0800682 private LinkAddress requestIpv4Address(final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800683 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800684
markchien69681d62021-11-15 23:58:05 +0800685 if (shouldNotConfigureBluetoothInterface()) return new LinkAddress(BLUETOOTH_IFACE_ADDR);
markchienc9daba32020-02-12 00:19:21 +0800686
markchiena2ffad82020-09-22 15:50:43 +0800687 return mPrivateAddressCoordinator.requestDownstreamAddress(this, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900688 }
689
markchien74a4fa92019-09-09 20:50:49 +0800690 private boolean startIPv6() {
691 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
692 if (mInterfaceParams == null) {
693 mLog.e("Failed to find InterfaceParams");
694 stopIPv6();
695 return false;
696 }
697
698 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
699 if (!mRaDaemon.start()) {
700 stopIPv6();
701 return false;
702 }
703
markchien932df542021-08-12 13:56:43 +0800704 if (SdkLevel.isAtLeastS()) {
Tyler Wear90e40632020-03-13 11:38:38 -0700705 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
706 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
707 }
708
markchien74a4fa92019-09-09 20:50:49 +0800709 return true;
710 }
711
712 private void stopIPv6() {
713 mInterfaceParams = null;
714 setRaParams(null);
715
716 if (mRaDaemon != null) {
717 mRaDaemon.stop();
718 mRaDaemon = null;
719 }
Tyler Wear90e40632020-03-13 11:38:38 -0700720
721 if (mDadProxy != null) {
722 mDadProxy.stop();
723 mDadProxy = null;
724 }
markchien74a4fa92019-09-09 20:50:49 +0800725 }
726
727 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
728 // LinkProperties. These have extraneous data filtered out and only the
729 // necessary prefixes included (per its prefix distribution policy).
730 //
731 // TODO: Evaluate using a data structure than is more directly suited to
732 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800733 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800734 if (mRaDaemon == null) return;
735
736 // Avoid unnecessary work on spurious updates.
737 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
738 return;
739 }
740
741 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700742 String upstreamIface = null;
743 InterfaceParams upstreamIfaceParams = null;
744 int upstreamIfIndex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800745
746 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700747 upstreamIface = v6only.getInterfaceName();
748 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
749 if (upstreamIfaceParams != null) {
750 upstreamIfIndex = upstreamIfaceParams.index;
751 }
markchien74a4fa92019-09-09 20:50:49 +0800752 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700753 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800754 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
755
markchiend63c4f32020-05-21 17:38:28 +0800756 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800757
758 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
759 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
760
761 final IpPrefix prefix = new IpPrefix(
762 linkAddr.getAddress(), linkAddr.getPrefixLength());
763 params.prefixes.add(prefix);
764
765 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
766 if (dnsServer != null) {
767 params.dnses.add(dnsServer);
768 }
769 }
770 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900771
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900772 // Add upstream index to name mapping. See the comment of the interface mapping update in
773 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
774 // timing issue. It prevents that the IPv6 capability is updated later than
775 // CMD_TETHER_CONNECTION_CHANGED.
776 mBpfCoordinator.addUpstreamNameToLookupTable(upstreamIfIndex, upstreamIface);
777
markchien74a4fa92019-09-09 20:50:49 +0800778 // If v6only is null, we pass in null to setRaParams(), which handles
779 // deprecation of any existing RA data.
780
781 setRaParams(params);
markchien7dc1b4d2021-07-13 17:12:56 +0800782 // Be aware that updateIpv6ForwardingRules use mLastIPv6LinkProperties, so this line should
783 // be eariler than updateIpv6ForwardingRules.
784 // TODO: avoid this dependencies and move this logic into BpfCoordinator.
markchien74a4fa92019-09-09 20:50:49 +0800785 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900786
Tyler Wear90e40632020-03-13 11:38:38 -0700787 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfIndex, null);
788 mLastIPv6UpstreamIfindex = upstreamIfIndex;
789 if (mDadProxy != null) {
790 mDadProxy.setUpstreamIface(upstreamIfaceParams);
791 }
markchien74a4fa92019-09-09 20:50:49 +0800792 }
793
Xiao Ma4455d6b2020-04-09 10:13:44 +0900794 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900795 final int removalFailures = NetdUtils.removeRoutesFromLocalNetwork(
Xiao Ma4455d6b2020-04-09 10:13:44 +0900796 mNetd, toBeRemoved);
797 if (removalFailures > 0) {
798 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
799 removalFailures));
800 }
801
802 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
803 }
804
805 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
806 try {
807 // It's safe to call networkAddInterface() even if
808 // the interface is already in the local_network.
809 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
810 try {
811 // Add routes from local network. Note that adding routes that
812 // already exist does not cause an error (EEXIST is silently ignored).
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900813 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900814 } catch (IllegalStateException e) {
815 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
816 return;
817 }
818 } catch (ServiceSpecificException | RemoteException e) {
819 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
820 return;
821 }
822
823 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
824 }
825
markchien74a4fa92019-09-09 20:50:49 +0800826 private void configureLocalIPv6Routes(
827 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
828 // [1] Remove the routes that are deprecated.
829 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900830 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800831 }
832
833 // [2] Add only the routes that have not previously been added.
834 if (newPrefixes != null && !newPrefixes.isEmpty()) {
835 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
836 if (mLastRaParams != null) {
837 addedPrefixes.removeAll(mLastRaParams.prefixes);
838 }
839
840 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900841 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800842 }
843 }
844 }
845
846 private void configureLocalIPv6Dns(
847 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
848 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
849 if (mNetd == null) {
850 if (newDnses != null) newDnses.clear();
851 mLog.e("No netd service instance available; not setting local IPv6 addresses");
852 return;
853 }
854
855 // [1] Remove deprecated local DNS IP addresses.
856 if (!deprecatedDnses.isEmpty()) {
857 for (Inet6Address dns : deprecatedDnses) {
858 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
859 mLog.e("Failed to remove local dns IP " + dns);
860 }
861
862 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
863 }
864 }
865
866 // [2] Add only the local DNS IP addresses that have not previously been added.
867 if (newDnses != null && !newDnses.isEmpty()) {
868 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
869 if (mLastRaParams != null) {
870 addedDnses.removeAll(mLastRaParams.dnses);
871 }
872
873 for (Inet6Address dns : addedDnses) {
874 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
875 mLog.e("Failed to add local dns IP " + dns);
876 newDnses.remove(dns);
877 }
878
879 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
880 }
881 }
882
883 try {
884 mNetd.tetherApplyDnsInterfaces();
885 } catch (ServiceSpecificException | RemoteException e) {
886 mLog.e("Failed to update local DNS caching server");
887 if (newDnses != null) newDnses.clear();
888 }
889 }
890
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900891 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800892 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
893 // offload is disabled. Add this check just in case.
894 // TODO: Perhaps remove this protection check.
895 if (!mUsingBpfOffload) return;
896
Hungming Chen269c0882020-05-06 14:57:35 +0800897 mBpfCoordinator.tetherOffloadRuleAdd(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900898 }
899
Hungming Chen269c0882020-05-06 14:57:35 +0800900 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800901 // TODO: Perhaps remove this protection check.
Hungming Chen269c0882020-05-06 14:57:35 +0800902 // See the related comment in #addIpv6ForwardingRule.
Hungming Chen3d8fa882020-04-12 14:27:18 +0800903 if (!mUsingBpfOffload) return;
904
Hungming Chen269c0882020-05-06 14:57:35 +0800905 mBpfCoordinator.tetherOffloadRuleRemove(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900906 }
907
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900908 private void clearIpv6ForwardingRules() {
Hungming Chen269c0882020-05-06 14:57:35 +0800909 if (!mUsingBpfOffload) return;
910
911 mBpfCoordinator.tetherOffloadRuleClear(this);
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900912 }
913
Hungming Chen269c0882020-05-06 14:57:35 +0800914 private void updateIpv6ForwardingRule(int newIfindex) {
915 // TODO: Perhaps remove this protection check.
916 // See the related comment in #addIpv6ForwardingRule.
917 if (!mUsingBpfOffload) return;
918
919 mBpfCoordinator.tetherOffloadRuleUpdate(this, newIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900920 }
921
markchien7dc1b4d2021-07-13 17:12:56 +0800922 private boolean isIpv6VcnNetworkInterface() {
923 if (mLastIPv6LinkProperties == null) return false;
924
925 return isVcnInterface(mLastIPv6LinkProperties.getInterfaceName());
926 }
927
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900928 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
929 // changes or if a neighbor event is received.
930 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
931 NeighborEvent e) {
markchien7dc1b4d2021-07-13 17:12:56 +0800932 // If no longer have an upstream or it is virtual network, clear forwarding rules and do
933 // nothing else.
934 // TODO: Rather than always clear rules, ensure whether ipv6 ever enable first.
935 if (upstreamIfindex == 0 || isIpv6VcnNetworkInterface()) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900936 clearIpv6ForwardingRules();
937 return;
938 }
939
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900940 // If the upstream interface has changed, remove all rules and re-add them with the new
941 // upstream interface.
942 if (prevUpstreamIfindex != upstreamIfindex) {
Hungming Chen269c0882020-05-06 14:57:35 +0800943 updateIpv6ForwardingRule(upstreamIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900944 }
945
946 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900947 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900948 if (e == null) return;
949 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
950 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
951 return;
952 }
953
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900954 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
955 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
956 // add rules with a null MAC, only delete them.
957 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900958 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900959 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900960 if (e.isValid()) {
961 addIpv6ForwardingRule(rule);
962 } else {
Hungming Chen269c0882020-05-06 14:57:35 +0800963 removeIpv6ForwardingRule(rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900964 }
965 }
966
Hungming Chend71c06e2020-12-21 19:39:49 +0800967 // TODO: consider moving into BpfCoordinator.
968 private void updateClientInfoIpv4(NeighborEvent e) {
969 // TODO: Perhaps remove this protection check.
970 // See the related comment in #addIpv6ForwardingRule.
971 if (!mUsingBpfOffload) return;
972
973 if (e == null) return;
974 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
975 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
976 return;
977 }
978
979 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
980 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
981 // IpServer never add clients with a null MAC, only delete them.
982 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
983 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
984 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
985 if (e.isValid()) {
986 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
987 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +0800988 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
989 }
990 }
991
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900992 private void handleNeighborEvent(NeighborEvent e) {
993 if (mInterfaceParams != null
994 && mInterfaceParams.index == e.ifindex
995 && mInterfaceParams.hasMacAddress) {
996 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
Hungming Chend71c06e2020-12-21 19:39:49 +0800997 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900998 }
999 }
1000
markchiend63c4f32020-05-21 17:38:28 +08001001 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001002 try {
1003 int upstreamHopLimit = Integer.parseUnsignedInt(
1004 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001005 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001006 // Cap the hop limit to 255.
1007 return (byte) Integer.min(upstreamHopLimit, 255);
1008 } catch (Exception e) {
1009 mLog.e("Failed to find upstream interface hop limit", e);
1010 }
1011 return RaParams.DEFAULT_HOPLIMIT;
1012 }
1013
1014 private void setRaParams(RaParams newParams) {
1015 if (mRaDaemon != null) {
1016 final RaParams deprecatedParams =
1017 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1018
1019 configureLocalIPv6Routes(deprecatedParams.prefixes,
1020 (newParams != null) ? newParams.prefixes : null);
1021
1022 configureLocalIPv6Dns(deprecatedParams.dnses,
1023 (newParams != null) ? newParams.dnses : null);
1024
1025 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1026 }
1027
1028 mLastRaParams = newParams;
1029 }
1030
markchien21021ef2021-06-01 10:58:04 +08001031 private void maybeLogMessage(State state, int what) {
1032 switch (what) {
1033 // Suppress some CMD_* to avoid log flooding.
1034 case CMD_IPV6_TETHER_UPDATE:
1035 case CMD_NEIGHBOR_EVENT:
1036 break;
1037 default:
1038 mLog.log(state.getName() + " got "
1039 + sMagicDecoderRing.get(what, Integer.toString(what)));
1040 }
markchien74a4fa92019-09-09 20:50:49 +08001041 }
1042
1043 private void sendInterfaceState(int newInterfaceState) {
1044 mServingMode = newInterfaceState;
1045 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1046 sendLinkProperties();
1047 }
1048
1049 private void sendLinkProperties() {
1050 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1051 }
1052
1053 private void resetLinkProperties() {
1054 mLinkProperties.clear();
1055 mLinkProperties.setInterfaceName(mIfaceName);
1056 }
1057
markchienf053e4b2020-03-16 21:49:48 +08001058 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001059 // Ignore static address configuration if they are invalid or null. In theory, static
1060 // addresses should not be invalid here because TetheringManager do not allow caller to
1061 // specify invalid static address configuration.
1062 if (request == null || request.localIPv4Address == null
1063 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1064 request.localIPv4Address, request.staticClientAddress)) {
1065 return;
1066 }
markchienf053e4b2020-03-16 21:49:48 +08001067
1068 mStaticIpv4ServerAddr = request.localIPv4Address;
1069 mStaticIpv4ClientAddr = request.staticClientAddress;
1070 }
1071
markchien74a4fa92019-09-09 20:50:49 +08001072 class InitialState extends State {
1073 @Override
1074 public void enter() {
1075 sendInterfaceState(STATE_AVAILABLE);
1076 }
1077
1078 @Override
1079 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001080 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001081 switch (message.what) {
1082 case CMD_TETHER_REQUESTED:
Mark74461fc2022-12-14 08:49:40 +00001083 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001084 switch (message.arg1) {
1085 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001086 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001087 transitionTo(mLocalHotspotState);
1088 break;
1089 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001090 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001091 transitionTo(mTetheredState);
1092 break;
1093 default:
1094 mLog.e("Invalid tethering interface serving state specified.");
1095 }
1096 break;
1097 case CMD_INTERFACE_DOWN:
1098 transitionTo(mUnavailableState);
1099 break;
markchien74a4fa92019-09-09 20:50:49 +08001100 default:
1101 return NOT_HANDLED;
1102 }
1103 return HANDLED;
1104 }
1105 }
1106
Hungming Chen46c30b12020-10-15 17:25:36 +08001107 private void startConntrackMonitoring() {
1108 mBpfCoordinator.startMonitoring(this);
1109 }
1110
1111 private void stopConntrackMonitoring() {
1112 mBpfCoordinator.stopMonitoring(this);
1113 }
1114
Mark3ec851e2023-05-19 08:50:38 +00001115 abstract class BaseServingState extends State {
1116 private final int mDesiredInterfaceState;
1117
1118 BaseServingState(int interfaceState) {
1119 mDesiredInterfaceState = interfaceState;
1120 }
1121
markchien74a4fa92019-09-09 20:50:49 +08001122 @Override
1123 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001124 startConntrackMonitoring();
1125
Mark3ec851e2023-05-19 08:50:38 +00001126 startServingInterface();
1127
1128 if (mLastError != TETHER_ERROR_NO_ERROR) {
1129 transitionTo(mInitialState);
1130 }
1131
1132 if (DBG) Log.d(TAG, getStateString(mDesiredInterfaceState) + " serve " + mIfaceName);
1133 sendInterfaceState(mDesiredInterfaceState);
1134 }
1135
1136 private void startServingInterface() {
markchien74a4fa92019-09-09 20:50:49 +08001137 if (!startIPv4()) {
Mark74461fc2022-12-14 08:49:40 +00001138 mLastError = TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001139 return;
1140 }
1141
1142 try {
markchienc9daba32020-02-12 00:19:21 +08001143 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001144 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001145 mLog.e("Error Tethering", e);
Mark74461fc2022-12-14 08:49:40 +00001146 mLastError = TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001147 return;
1148 }
1149
1150 if (!startIPv6()) {
1151 mLog.e("Failed to startIPv6");
1152 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1153 return;
1154 }
1155 }
1156
1157 @Override
1158 public void exit() {
1159 // Note that at this point, we're leaving the tethered state. We can fail any
1160 // of these operations, but it doesn't really change that we have to try them
1161 // all in sequence.
1162 stopIPv6();
1163
1164 try {
markchien12c5bb82020-01-07 14:43:17 +08001165 NetdUtils.untetherInterface(mNetd, mIfaceName);
1166 } catch (RemoteException | ServiceSpecificException e) {
Mark74461fc2022-12-14 08:49:40 +00001167 mLastError = TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001168 mLog.e("Failed to untether interface: " + e);
1169 }
1170
1171 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001172 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001173
1174 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001175
1176 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1177 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001178 }
1179
1180 @Override
1181 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001182 switch (message.what) {
1183 case CMD_TETHER_UNREQUESTED:
1184 transitionTo(mInitialState);
1185 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1186 break;
1187 case CMD_INTERFACE_DOWN:
1188 transitionTo(mUnavailableState);
1189 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1190 break;
1191 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001192 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001193 sendLinkProperties();
1194 break;
1195 case CMD_IP_FORWARDING_ENABLE_ERROR:
1196 case CMD_IP_FORWARDING_DISABLE_ERROR:
1197 case CMD_START_TETHERING_ERROR:
1198 case CMD_STOP_TETHERING_ERROR:
1199 case CMD_SET_DNS_FORWARDERS_ERROR:
Mark74461fc2022-12-14 08:49:40 +00001200 mLastError = TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001201 transitionTo(mInitialState);
1202 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001203 case CMD_NEW_PREFIX_REQUEST:
1204 handleNewPrefixRequest((IpPrefix) message.obj);
1205 break;
markchienc9daba32020-02-12 00:19:21 +08001206 case CMD_NOTIFY_PREFIX_CONFLICT:
1207 mLog.i("restart tethering: " + mInterfaceType);
1208 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1209 transitionTo(mWaitingForRestartState);
1210 break;
markchien74a4fa92019-09-09 20:50:49 +08001211 default:
1212 return false;
1213 }
1214 return true;
1215 }
Mark3ec851e2023-05-19 08:50:38 +00001216
1217 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
1218 if (!currentPrefix.contains(mIpv4Address.getAddress())
1219 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
1220 Log.e(TAG, "Invalid prefix: " + currentPrefix);
1221 return;
1222 }
1223
1224 final LinkAddress deprecatedLinkAddress = mIpv4Address;
1225 mIpv4Address = requestIpv4Address(false);
1226 if (mIpv4Address == null) {
1227 mLog.e("Fail to request a new downstream prefix");
1228 return;
1229 }
1230 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
1231
1232 // Add new IPv4 address on the interface.
1233 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1234 mLog.e("Failed to add new IP " + srvAddr);
1235 return;
1236 }
1237
1238 // Remove deprecated routes from local network.
1239 removeRoutesFromLocalNetwork(
1240 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1241 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1242
1243 // Add new routes to local network.
1244 addRoutesToLocalNetwork(
1245 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1246 mLinkProperties.addLinkAddress(mIpv4Address);
1247
1248 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1249 // listen on the interface configured with new IPv4 address, that results DNS validation
1250 // failure of downstream client even if appropriate routes have been configured.
1251 try {
1252 mNetd.tetherApplyDnsInterfaces();
1253 } catch (ServiceSpecificException | RemoteException e) {
1254 mLog.e("Failed to update local DNS caching server");
1255 return;
1256 }
1257 sendLinkProperties();
1258
1259 // Notify DHCP server that new prefix/route has been applied on IpServer.
1260 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1261 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1262 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1263 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1264 try {
1265 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1266 @Override
1267 public void callback(int statusCode) {
1268 if (statusCode != STATUS_SUCCESS) {
1269 mLog.e("Error updating DHCP serving params: " + statusCode);
1270 }
1271 }
1272 });
1273 } catch (RemoteException e) {
1274 mLog.e("Error updating DHCP serving params", e);
1275 }
1276 }
markchien74a4fa92019-09-09 20:50:49 +08001277 }
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 LocalHotspotState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001285 LocalHotspotState() {
1286 super(STATE_LOCAL_ONLY);
markchien74a4fa92019-09-09 20:50:49 +08001287 }
1288
1289 @Override
1290 public boolean processMessage(Message message) {
1291 if (super.processMessage(message)) return true;
1292
markchien21021ef2021-06-01 10:58:04 +08001293 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001294 switch (message.what) {
1295 case CMD_TETHER_REQUESTED:
1296 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1297 break;
1298 case CMD_TETHER_CONNECTION_CHANGED:
1299 // Ignored in local hotspot state.
1300 break;
1301 default:
1302 return false;
1303 }
1304 return true;
1305 }
1306 }
1307
1308 // Handling errors in BaseServingState.enter() by transitioning is
1309 // problematic because transitioning during a multi-state jump yields
1310 // a Log.wtf(). Ultimately, there should be only one ServingState,
1311 // and forwarding and NAT rules should be handled by a coordinating
1312 // functional element outside of IpServer.
1313 class TetheredState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001314 TetheredState() {
1315 super(STATE_TETHERED);
markchien74a4fa92019-09-09 20:50:49 +08001316 }
1317
1318 @Override
1319 public void exit() {
1320 cleanupUpstream();
1321 super.exit();
1322 }
1323
Hungming Chena6e78692021-02-08 17:15:35 +08001324 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1325 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1326 // and behaviour. While upstream is switching from offload supported interface to
1327 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1328 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1329 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1330 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1331 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1332 // in the state machine. Once there is any case out whish is not covered by previous cases,
1333 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001334 private void cleanupUpstream() {
1335 if (mUpstreamIfaceSet == null) return;
1336
1337 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1338 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001339 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001340 }
1341
1342 private void cleanupUpstreamInterface(String upstreamIface) {
1343 // Note that we don't care about errors here.
1344 // Sometimes interfaces are gone before we get
1345 // to remove their rules, which generates errors.
1346 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001347 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001348 try {
markchien12c5bb82020-01-07 14:43:17 +08001349 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1350 } catch (RemoteException | ServiceSpecificException e) {
1351 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001352 }
1353 try {
markchien12c5bb82020-01-07 14:43:17 +08001354 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1355 } catch (RemoteException | ServiceSpecificException e) {
1356 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001357 }
1358 }
1359
1360 @Override
1361 public boolean processMessage(Message message) {
1362 if (super.processMessage(message)) return true;
1363
markchien21021ef2021-06-01 10:58:04 +08001364 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001365 switch (message.what) {
1366 case CMD_TETHER_REQUESTED:
1367 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1368 break;
1369 case CMD_TETHER_CONNECTION_CHANGED:
1370 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1371 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1372 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1373 break;
1374 }
1375
1376 if (newUpstreamIfaceSet == null) {
1377 cleanupUpstream();
1378 break;
1379 }
1380
1381 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1382 cleanupUpstreamInterface(removed);
1383 }
1384
1385 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1386 // This makes the call to cleanupUpstream() in the error
1387 // path for any interface neatly cleanup all the interfaces.
1388 mUpstreamIfaceSet = newUpstreamIfaceSet;
1389
1390 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001391 // Add upstream index to name mapping for the tether stats usage in the
1392 // coordinator. Although this mapping could be added by both class
1393 // Tethering and IpServer, adding mapping from IpServer guarantees that
1394 // the mapping is added before adding forwarding rules. That is because
1395 // there are different state machines in both classes. It is hard to
1396 // guarantee the link property update order between multiple state machines.
1397 // Note that both IPv4 and IPv6 interface may be added because
1398 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1399 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1400 // capability may be updated later. In that case, IPv6 interface mapping is
1401 // updated in updateUpstreamIPv6LinkProperties.
1402 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1403 final InterfaceParams upstreamIfaceParams =
1404 mDeps.getInterfaceParams(ifname);
1405 if (upstreamIfaceParams != null) {
1406 mBpfCoordinator.addUpstreamNameToLookupTable(
1407 upstreamIfaceParams.index, ifname);
1408 }
1409 }
1410
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001411 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001412 try {
markchien12c5bb82020-01-07 14:43:17 +08001413 mNetd.tetherAddForward(mIfaceName, ifname);
1414 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1415 } catch (RemoteException | ServiceSpecificException e) {
1416 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001417 cleanupUpstream();
Mark74461fc2022-12-14 08:49:40 +00001418 mLastError = TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001419 transitionTo(mInitialState);
1420 return true;
1421 }
1422 }
1423 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001424 case CMD_NEIGHBOR_EVENT:
1425 handleNeighborEvent((NeighborEvent) message.obj);
1426 break;
markchien74a4fa92019-09-09 20:50:49 +08001427 default:
1428 return false;
1429 }
1430 return true;
1431 }
1432
1433 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1434 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1435 if (mUpstreamIfaceSet != null && newIfaces != null) {
1436 return mUpstreamIfaceSet.equals(newIfaces);
1437 }
1438 return false;
1439 }
1440
1441 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1442 if (mUpstreamIfaceSet == null) return new HashSet<>();
1443
1444 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1445 removed.removeAll(newIfaces.ifnames);
1446 return removed;
1447 }
1448
1449 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1450 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1451 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1452 return added;
1453 }
1454 }
1455
1456 /**
1457 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001458 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001459 * specific state machine from its list of possible recipients of
1460 * tethering requests. The state machine itself will hang around until
1461 * the garbage collector finds it.
1462 */
1463 class UnavailableState extends State {
1464 @Override
1465 public void enter() {
h.zhangd244bd02020-06-14 14:46:54 +08001466 mIpNeighborMonitor.stop();
Mark74461fc2022-12-14 08:49:40 +00001467 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001468 sendInterfaceState(STATE_UNAVAILABLE);
1469 }
1470 }
1471
markchienc9daba32020-02-12 00:19:21 +08001472 class WaitingForRestartState extends State {
1473 @Override
1474 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001475 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001476 switch (message.what) {
1477 case CMD_TETHER_UNREQUESTED:
1478 transitionTo(mInitialState);
1479 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1480 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1481 break;
1482 case CMD_INTERFACE_DOWN:
1483 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001484 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001485 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1486 break;
1487 default:
1488 return false;
1489 }
1490 return true;
1491 }
1492 }
1493
markchien74a4fa92019-09-09 20:50:49 +08001494 // Accumulate routes representing "prefixes to be assigned to the local
1495 // interface", for subsequent modification of local_network routing.
1496 private static ArrayList<RouteInfo> getLocalRoutesFor(
1497 String ifname, HashSet<IpPrefix> prefixes) {
1498 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1499 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001500 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001501 }
1502 return localRoutes;
1503 }
1504
1505 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1506 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1507 final byte[] dnsBytes = localPrefix.getRawAddress();
1508 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1509 try {
1510 return Inet6Address.getByAddress(null, dnsBytes, 0);
1511 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001512 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001513 return null;
1514 }
1515 }
1516
1517 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1518 final byte random = (byte) (new Random()).nextInt();
1519 for (int value : excluded) {
1520 if (random == value) return dflt;
1521 }
1522 return random;
1523 }
1524}