blob: 65ea8e55d03c451da07d8e6137187a46688657a1 [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
Xiao Ma4455d6b2020-04-09 10:13:44 +09001001 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
1002 if (!currentPrefix.contains(mIpv4Address.getAddress())
1003 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
1004 Log.e(TAG, "Invalid prefix: " + currentPrefix);
1005 return;
1006 }
1007
1008 final LinkAddress deprecatedLinkAddress = mIpv4Address;
markchiena2ffad82020-09-22 15:50:43 +08001009 mIpv4Address = requestIpv4Address(false);
markchienc9daba32020-02-12 00:19:21 +08001010 if (mIpv4Address == null) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001011 mLog.e("Fail to request a new downstream prefix");
1012 return;
1013 }
markchienc9daba32020-02-12 00:19:21 +08001014 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
Xiao Ma4455d6b2020-04-09 10:13:44 +09001015
1016 // Add new IPv4 address on the interface.
1017 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1018 mLog.e("Failed to add new IP " + srvAddr);
1019 return;
1020 }
1021
1022 // Remove deprecated routes from local network.
1023 removeRoutesFromLocalNetwork(
1024 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1025 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1026
1027 // Add new routes to local network.
1028 addRoutesToLocalNetwork(
1029 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1030 mLinkProperties.addLinkAddress(mIpv4Address);
1031
1032 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1033 // listen on the interface configured with new IPv4 address, that results DNS validation
1034 // failure of downstream client even if appropriate routes have been configured.
1035 try {
1036 mNetd.tetherApplyDnsInterfaces();
1037 } catch (ServiceSpecificException | RemoteException e) {
1038 mLog.e("Failed to update local DNS caching server");
1039 return;
1040 }
1041 sendLinkProperties();
1042
1043 // Notify DHCP server that new prefix/route has been applied on IpServer.
1044 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1045 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1046 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1047 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1048 try {
1049 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1050 @Override
1051 public void callback(int statusCode) {
1052 if (statusCode != STATUS_SUCCESS) {
1053 mLog.e("Error updating DHCP serving params: " + statusCode);
1054 }
1055 }
1056 });
1057 } catch (RemoteException e) {
1058 mLog.e("Error updating DHCP serving params", e);
1059 }
1060 }
1061
markchiend63c4f32020-05-21 17:38:28 +08001062 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001063 try {
1064 int upstreamHopLimit = Integer.parseUnsignedInt(
1065 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001066 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001067 // Cap the hop limit to 255.
1068 return (byte) Integer.min(upstreamHopLimit, 255);
1069 } catch (Exception e) {
1070 mLog.e("Failed to find upstream interface hop limit", e);
1071 }
1072 return RaParams.DEFAULT_HOPLIMIT;
1073 }
1074
1075 private void setRaParams(RaParams newParams) {
1076 if (mRaDaemon != null) {
1077 final RaParams deprecatedParams =
1078 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1079
1080 configureLocalIPv6Routes(deprecatedParams.prefixes,
1081 (newParams != null) ? newParams.prefixes : null);
1082
1083 configureLocalIPv6Dns(deprecatedParams.dnses,
1084 (newParams != null) ? newParams.dnses : null);
1085
1086 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1087 }
1088
1089 mLastRaParams = newParams;
1090 }
1091
markchien21021ef2021-06-01 10:58:04 +08001092 private void maybeLogMessage(State state, int what) {
1093 switch (what) {
1094 // Suppress some CMD_* to avoid log flooding.
1095 case CMD_IPV6_TETHER_UPDATE:
1096 case CMD_NEIGHBOR_EVENT:
1097 break;
1098 default:
1099 mLog.log(state.getName() + " got "
1100 + sMagicDecoderRing.get(what, Integer.toString(what)));
1101 }
markchien74a4fa92019-09-09 20:50:49 +08001102 }
1103
1104 private void sendInterfaceState(int newInterfaceState) {
1105 mServingMode = newInterfaceState;
1106 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1107 sendLinkProperties();
1108 }
1109
1110 private void sendLinkProperties() {
1111 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1112 }
1113
1114 private void resetLinkProperties() {
1115 mLinkProperties.clear();
1116 mLinkProperties.setInterfaceName(mIfaceName);
1117 }
1118
markchienf053e4b2020-03-16 21:49:48 +08001119 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001120 // Ignore static address configuration if they are invalid or null. In theory, static
1121 // addresses should not be invalid here because TetheringManager do not allow caller to
1122 // specify invalid static address configuration.
1123 if (request == null || request.localIPv4Address == null
1124 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1125 request.localIPv4Address, request.staticClientAddress)) {
1126 return;
1127 }
markchienf053e4b2020-03-16 21:49:48 +08001128
1129 mStaticIpv4ServerAddr = request.localIPv4Address;
1130 mStaticIpv4ClientAddr = request.staticClientAddress;
1131 }
1132
markchien74a4fa92019-09-09 20:50:49 +08001133 class InitialState extends State {
1134 @Override
1135 public void enter() {
1136 sendInterfaceState(STATE_AVAILABLE);
1137 }
1138
1139 @Override
1140 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001141 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001142 switch (message.what) {
1143 case CMD_TETHER_REQUESTED:
Mark74461fc2022-12-14 08:49:40 +00001144 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001145 switch (message.arg1) {
1146 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001147 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001148 transitionTo(mLocalHotspotState);
1149 break;
1150 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001151 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001152 transitionTo(mTetheredState);
1153 break;
1154 default:
1155 mLog.e("Invalid tethering interface serving state specified.");
1156 }
1157 break;
1158 case CMD_INTERFACE_DOWN:
1159 transitionTo(mUnavailableState);
1160 break;
markchien74a4fa92019-09-09 20:50:49 +08001161 default:
1162 return NOT_HANDLED;
1163 }
1164 return HANDLED;
1165 }
1166 }
1167
Hungming Chen46c30b12020-10-15 17:25:36 +08001168 private void startConntrackMonitoring() {
1169 mBpfCoordinator.startMonitoring(this);
1170 }
1171
1172 private void stopConntrackMonitoring() {
1173 mBpfCoordinator.stopMonitoring(this);
1174 }
1175
markchien74a4fa92019-09-09 20:50:49 +08001176 class BaseServingState extends State {
1177 @Override
1178 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001179 startConntrackMonitoring();
1180
markchien74a4fa92019-09-09 20:50:49 +08001181 if (!startIPv4()) {
Mark74461fc2022-12-14 08:49:40 +00001182 mLastError = TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001183 return;
1184 }
1185
1186 try {
markchienc9daba32020-02-12 00:19:21 +08001187 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001188 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001189 mLog.e("Error Tethering", e);
Mark74461fc2022-12-14 08:49:40 +00001190 mLastError = TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001191 return;
1192 }
1193
1194 if (!startIPv6()) {
1195 mLog.e("Failed to startIPv6");
1196 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1197 return;
1198 }
1199 }
1200
1201 @Override
1202 public void exit() {
1203 // Note that at this point, we're leaving the tethered state. We can fail any
1204 // of these operations, but it doesn't really change that we have to try them
1205 // all in sequence.
1206 stopIPv6();
1207
1208 try {
markchien12c5bb82020-01-07 14:43:17 +08001209 NetdUtils.untetherInterface(mNetd, mIfaceName);
1210 } catch (RemoteException | ServiceSpecificException e) {
Mark74461fc2022-12-14 08:49:40 +00001211 mLastError = TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001212 mLog.e("Failed to untether interface: " + e);
1213 }
1214
1215 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001216 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001217
1218 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001219
1220 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1221 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001222 }
1223
1224 @Override
1225 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001226 switch (message.what) {
1227 case CMD_TETHER_UNREQUESTED:
1228 transitionTo(mInitialState);
1229 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1230 break;
1231 case CMD_INTERFACE_DOWN:
1232 transitionTo(mUnavailableState);
1233 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1234 break;
1235 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001236 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001237 sendLinkProperties();
1238 break;
1239 case CMD_IP_FORWARDING_ENABLE_ERROR:
1240 case CMD_IP_FORWARDING_DISABLE_ERROR:
1241 case CMD_START_TETHERING_ERROR:
1242 case CMD_STOP_TETHERING_ERROR:
1243 case CMD_SET_DNS_FORWARDERS_ERROR:
Mark74461fc2022-12-14 08:49:40 +00001244 mLastError = TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001245 transitionTo(mInitialState);
1246 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001247 case CMD_NEW_PREFIX_REQUEST:
1248 handleNewPrefixRequest((IpPrefix) message.obj);
1249 break;
markchienc9daba32020-02-12 00:19:21 +08001250 case CMD_NOTIFY_PREFIX_CONFLICT:
1251 mLog.i("restart tethering: " + mInterfaceType);
1252 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1253 transitionTo(mWaitingForRestartState);
1254 break;
markchien74a4fa92019-09-09 20:50:49 +08001255 default:
1256 return false;
1257 }
1258 return true;
1259 }
1260 }
1261
1262 // Handling errors in BaseServingState.enter() by transitioning is
1263 // problematic because transitioning during a multi-state jump yields
1264 // a Log.wtf(). Ultimately, there should be only one ServingState,
1265 // and forwarding and NAT rules should be handled by a coordinating
1266 // functional element outside of IpServer.
1267 class LocalHotspotState extends BaseServingState {
1268 @Override
1269 public void enter() {
1270 super.enter();
Mark74461fc2022-12-14 08:49:40 +00001271 if (mLastError != TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001272 transitionTo(mInitialState);
1273 }
1274
1275 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1276 sendInterfaceState(STATE_LOCAL_ONLY);
1277 }
1278
1279 @Override
1280 public boolean processMessage(Message message) {
1281 if (super.processMessage(message)) return true;
1282
markchien21021ef2021-06-01 10:58:04 +08001283 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001284 switch (message.what) {
1285 case CMD_TETHER_REQUESTED:
1286 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1287 break;
1288 case CMD_TETHER_CONNECTION_CHANGED:
1289 // Ignored in local hotspot state.
1290 break;
1291 default:
1292 return false;
1293 }
1294 return true;
1295 }
1296 }
1297
1298 // Handling errors in BaseServingState.enter() by transitioning is
1299 // problematic because transitioning during a multi-state jump yields
1300 // a Log.wtf(). Ultimately, there should be only one ServingState,
1301 // and forwarding and NAT rules should be handled by a coordinating
1302 // functional element outside of IpServer.
1303 class TetheredState extends BaseServingState {
1304 @Override
1305 public void enter() {
1306 super.enter();
Mark74461fc2022-12-14 08:49:40 +00001307 if (mLastError != TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001308 transitionTo(mInitialState);
1309 }
1310
1311 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1312 sendInterfaceState(STATE_TETHERED);
1313 }
1314
1315 @Override
1316 public void exit() {
1317 cleanupUpstream();
1318 super.exit();
1319 }
1320
Hungming Chena6e78692021-02-08 17:15:35 +08001321 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1322 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1323 // and behaviour. While upstream is switching from offload supported interface to
1324 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1325 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1326 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1327 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1328 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1329 // in the state machine. Once there is any case out whish is not covered by previous cases,
1330 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001331 private void cleanupUpstream() {
1332 if (mUpstreamIfaceSet == null) return;
1333
1334 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1335 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001336 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001337 }
1338
1339 private void cleanupUpstreamInterface(String upstreamIface) {
1340 // Note that we don't care about errors here.
1341 // Sometimes interfaces are gone before we get
1342 // to remove their rules, which generates errors.
1343 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001344 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001345 try {
markchien12c5bb82020-01-07 14:43:17 +08001346 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1347 } catch (RemoteException | ServiceSpecificException e) {
1348 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001349 }
1350 try {
markchien12c5bb82020-01-07 14:43:17 +08001351 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1352 } catch (RemoteException | ServiceSpecificException e) {
1353 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001354 }
1355 }
1356
1357 @Override
1358 public boolean processMessage(Message message) {
1359 if (super.processMessage(message)) return true;
1360
markchien21021ef2021-06-01 10:58:04 +08001361 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001362 switch (message.what) {
1363 case CMD_TETHER_REQUESTED:
1364 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1365 break;
1366 case CMD_TETHER_CONNECTION_CHANGED:
1367 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1368 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1369 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1370 break;
1371 }
1372
1373 if (newUpstreamIfaceSet == null) {
1374 cleanupUpstream();
1375 break;
1376 }
1377
1378 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1379 cleanupUpstreamInterface(removed);
1380 }
1381
1382 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1383 // This makes the call to cleanupUpstream() in the error
1384 // path for any interface neatly cleanup all the interfaces.
1385 mUpstreamIfaceSet = newUpstreamIfaceSet;
1386
1387 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001388 // Add upstream index to name mapping for the tether stats usage in the
1389 // coordinator. Although this mapping could be added by both class
1390 // Tethering and IpServer, adding mapping from IpServer guarantees that
1391 // the mapping is added before adding forwarding rules. That is because
1392 // there are different state machines in both classes. It is hard to
1393 // guarantee the link property update order between multiple state machines.
1394 // Note that both IPv4 and IPv6 interface may be added because
1395 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1396 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1397 // capability may be updated later. In that case, IPv6 interface mapping is
1398 // updated in updateUpstreamIPv6LinkProperties.
1399 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1400 final InterfaceParams upstreamIfaceParams =
1401 mDeps.getInterfaceParams(ifname);
1402 if (upstreamIfaceParams != null) {
1403 mBpfCoordinator.addUpstreamNameToLookupTable(
1404 upstreamIfaceParams.index, ifname);
1405 }
1406 }
1407
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001408 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001409 try {
markchien12c5bb82020-01-07 14:43:17 +08001410 mNetd.tetherAddForward(mIfaceName, ifname);
1411 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1412 } catch (RemoteException | ServiceSpecificException e) {
1413 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001414 cleanupUpstream();
Mark74461fc2022-12-14 08:49:40 +00001415 mLastError = TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001416 transitionTo(mInitialState);
1417 return true;
1418 }
1419 }
1420 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001421 case CMD_NEIGHBOR_EVENT:
1422 handleNeighborEvent((NeighborEvent) message.obj);
1423 break;
markchien74a4fa92019-09-09 20:50:49 +08001424 default:
1425 return false;
1426 }
1427 return true;
1428 }
1429
1430 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1431 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1432 if (mUpstreamIfaceSet != null && newIfaces != null) {
1433 return mUpstreamIfaceSet.equals(newIfaces);
1434 }
1435 return false;
1436 }
1437
1438 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1439 if (mUpstreamIfaceSet == null) return new HashSet<>();
1440
1441 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1442 removed.removeAll(newIfaces.ifnames);
1443 return removed;
1444 }
1445
1446 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1447 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1448 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1449 return added;
1450 }
1451 }
1452
1453 /**
1454 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001455 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001456 * specific state machine from its list of possible recipients of
1457 * tethering requests. The state machine itself will hang around until
1458 * the garbage collector finds it.
1459 */
1460 class UnavailableState extends State {
1461 @Override
1462 public void enter() {
h.zhangd244bd02020-06-14 14:46:54 +08001463 mIpNeighborMonitor.stop();
Mark74461fc2022-12-14 08:49:40 +00001464 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001465 sendInterfaceState(STATE_UNAVAILABLE);
1466 }
1467 }
1468
markchienc9daba32020-02-12 00:19:21 +08001469 class WaitingForRestartState extends State {
1470 @Override
1471 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001472 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001473 switch (message.what) {
1474 case CMD_TETHER_UNREQUESTED:
1475 transitionTo(mInitialState);
1476 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1477 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1478 break;
1479 case CMD_INTERFACE_DOWN:
1480 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001481 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001482 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1483 break;
1484 default:
1485 return false;
1486 }
1487 return true;
1488 }
1489 }
1490
markchien74a4fa92019-09-09 20:50:49 +08001491 // Accumulate routes representing "prefixes to be assigned to the local
1492 // interface", for subsequent modification of local_network routing.
1493 private static ArrayList<RouteInfo> getLocalRoutesFor(
1494 String ifname, HashSet<IpPrefix> prefixes) {
1495 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1496 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001497 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001498 }
1499 return localRoutes;
1500 }
1501
1502 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1503 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1504 final byte[] dnsBytes = localPrefix.getRawAddress();
1505 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1506 try {
1507 return Inet6Address.getByAddress(null, dnsBytes, 0);
1508 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001509 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001510 return null;
1511 }
1512 }
1513
1514 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1515 final byte random = (byte) (new Random()).nextInt();
1516 for (int value : excluded) {
1517 if (random == value) return dflt;
1518 }
1519 return random;
1520 }
1521}