blob: a85141060ccd4f9bc8a91f4e5d8c9774258d8971 [file] [log] [blame]
markchien74a4fa92019-09-09 20:50:49 +08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.net.ip;
18
markchien6cf0e552019-12-06 15:24:53 +080019import static android.net.RouteInfo.RTN_UNICAST;
Mark49649c92023-03-15 06:45:04 +000020import static android.net.TetheringManager.CONNECTIVITY_SCOPE_GLOBAL;
21import static android.net.TetheringManager.CONNECTIVITY_SCOPE_LOCAL;
Mark74461fc2022-12-14 08:49:40 +000022import static android.net.TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
23import static android.net.TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
24import static android.net.TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
25import static android.net.TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
26import static android.net.TetheringManager.TETHER_ERROR_NO_ERROR;
27import static android.net.TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
28import static android.net.TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien245352e2020-02-27 20:27:18 +080029import static android.net.TetheringManager.TetheringRequest.checkStaticAddressConfiguration;
markchien74a4fa92019-09-09 20:50:49 +080030import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
markchien74a4fa92019-09-09 20:50:49 +080031import static android.net.util.NetworkConstants.asByte;
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +090032import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080033
Chalard Jean78701642020-07-31 20:00:30 +090034import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH;
Xiao Ma1f993302023-08-09 18:55:49 +090035import static com.android.net.module.util.NetworkStackConstants.RFC7421_PREFIX_LENGTH;
markchien7dc1b4d2021-07-13 17:12:56 +080036import static com.android.networkstack.tethering.UpstreamNetworkState.isVcnInterface;
markchiend02f9af2021-11-04 11:26:03 +080037import static com.android.networkstack.tethering.util.PrefixUtils.asIpPrefix;
38import static com.android.networkstack.tethering.util.TetheringMessageBase.BASE_IPSERVER;
Chalard Jean78701642020-07-31 20:00:30 +090039
markchien74a4fa92019-09-09 20:50:49 +080040import android.net.INetd;
41import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080042import android.net.IpPrefix;
43import android.net.LinkAddress;
44import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090045import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080046import android.net.RouteInfo;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090047import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080048import android.net.TetheringManager;
markchienf053e4b2020-03-16 21:49:48 +080049import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090050import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080051import android.net.dhcp.DhcpServerCallbacks;
52import android.net.dhcp.DhcpServingParamsParcel;
53import android.net.dhcp.DhcpServingParamsParcelExt;
Xiao Ma49889dd2020-04-03 17:01:33 +090054import android.net.dhcp.IDhcpEventCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080055import android.net.dhcp.IDhcpServer;
56import android.net.ip.RouterAdvertisementDaemon.RaParams;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090057import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080058import android.os.Looper;
59import android.os.Message;
60import android.os.RemoteException;
61import android.os.ServiceSpecificException;
62import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080063import android.util.SparseArray;
64
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090065import androidx.annotation.NonNull;
Xiao Ma4455d6b2020-04-09 10:13:44 +090066import androidx.annotation.Nullable;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090067
markchien74a4fa92019-09-09 20:50:49 +080068import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080069import com.android.internal.util.State;
70import com.android.internal.util.StateMachine;
markchien932df542021-08-12 13:56:43 +080071import com.android.modules.utils.build.SdkLevel;
Patrick Rohr9f371f02022-03-04 15:14:27 +010072import com.android.net.module.util.InterfaceParams;
Chalard Jeanadcec9e2021-10-29 15:57:22 +090073import com.android.net.module.util.NetdUtils;
Patrick Rohrb873e252022-06-16 16:38:43 -070074import com.android.net.module.util.SharedLog;
Xiao Mac81c0662022-06-17 14:58:03 +090075import com.android.net.module.util.ip.InterfaceController;
76import com.android.net.module.util.ip.IpNeighborMonitor;
77import com.android.net.module.util.ip.IpNeighborMonitor.NeighborEvent;
Hungming Chen68f1c2a2020-03-12 21:24:01 +080078import com.android.networkstack.tethering.BpfCoordinator;
Hungming Chend71c06e2020-12-21 19:39:49 +080079import com.android.networkstack.tethering.BpfCoordinator.ClientInfo;
KH Shi59ad35e2023-08-15 07:13:00 +000080import com.android.networkstack.tethering.BpfCoordinator.Ipv6DownstreamRule;
markchienc9daba32020-02-12 00:19:21 +080081import com.android.networkstack.tethering.PrivateAddressCoordinator;
markchienb961d3d2022-02-26 00:39:06 +080082import com.android.networkstack.tethering.TetheringConfiguration;
Wayne Ma6cd440f2022-03-14 18:04:33 +080083import com.android.networkstack.tethering.metrics.TetheringMetrics;
markchiend02f9af2021-11-04 11:26:03 +080084import com.android.networkstack.tethering.util.InterfaceSet;
85import com.android.networkstack.tethering.util.PrefixUtils;
markchien74a4fa92019-09-09 20:50:49 +080086
87import java.net.Inet4Address;
88import java.net.Inet6Address;
markchien74a4fa92019-09-09 20:50:49 +080089import java.net.UnknownHostException;
90import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090091import java.util.Arrays;
92import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080093import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090094import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080095import java.util.Objects;
96import java.util.Random;
97import java.util.Set;
98
99/**
100 * Provides the interface to IP-layer serving functionality for a given network
101 * interface, e.g. for tethering or "local-only hotspot" mode.
102 *
103 * @hide
104 */
105public class IpServer extends StateMachine {
106 public static final int STATE_UNAVAILABLE = 0;
107 public static final int STATE_AVAILABLE = 1;
108 public static final int STATE_TETHERED = 2;
109 public static final int STATE_LOCAL_ONLY = 3;
110
111 /** Get string name of |state|.*/
112 public static String getStateString(int state) {
113 switch (state) {
114 case STATE_UNAVAILABLE: return "UNAVAILABLE";
115 case STATE_AVAILABLE: return "AVAILABLE";
116 case STATE_TETHERED: return "TETHERED";
117 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
118 }
119 return "UNKNOWN: " + state;
120 }
121
122 private static final byte DOUG_ADAMS = (byte) 42;
123
markchien74a4fa92019-09-09 20:50:49 +0800124 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800125 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800126
127 // TODO: have this configurable
128 private static final int DHCP_LEASE_TIME_SECS = 3600;
129
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900130 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
131
markchien74a4fa92019-09-09 20:50:49 +0800132 private static final String TAG = "IpServer";
133 private static final boolean DBG = false;
134 private static final boolean VDBG = false;
135 private static final Class[] sMessageClasses = {
136 IpServer.class
137 };
138 private static final SparseArray<String> sMagicDecoderRing =
139 MessageUtils.findMessageNames(sMessageClasses);
140
141 /** IpServer callback. */
142 public static class Callback {
143 /**
144 * Notify that |who| has changed its tethering state.
145 *
146 * @param who the calling instance of IpServer
147 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800148 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800149 */
markchien9d353822019-12-16 20:15:20 +0800150 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800151
152 /**
153 * Notify that |who| has new LinkProperties.
154 *
155 * @param who the calling instance of IpServer
156 * @param newLp the new LinkProperties to report
157 */
markchien9d353822019-12-16 20:15:20 +0800158 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900159
160 /**
161 * Notify that the DHCP leases changed in one of the IpServers.
162 */
163 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800164
165 /**
166 * Request Tethering change.
167 *
168 * @param tetheringType the downstream type of this IpServer.
169 * @param enabled enable or disable tethering.
170 */
171 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800172 }
173
174 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800175 public abstract static class Dependencies {
Tyler Wear90e40632020-03-13 11:38:38 -0700176 /**
177 * Create a DadProxy instance to be used by IpServer.
178 * To support multiple tethered interfaces concurrently DAD Proxy
179 * needs to be supported per IpServer instead of per upstream.
180 */
181 public DadProxy getDadProxy(Handler handler, InterfaceParams ifParams) {
182 return new DadProxy(handler, ifParams);
183 }
184
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900185 /** Create an IpNeighborMonitor to be used by this IpServer */
186 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
187 IpNeighborMonitor.NeighborEventConsumer consumer) {
188 return new IpNeighborMonitor(handler, log, consumer);
189 }
190
markchien74a4fa92019-09-09 20:50:49 +0800191 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
192 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
193 return new RouterAdvertisementDaemon(ifParams);
194 }
195
196 /** Get |ifName|'s interface information.*/
197 public InterfaceParams getInterfaceParams(String ifName) {
198 return InterfaceParams.getByName(ifName);
199 }
200
markchien9d353822019-12-16 20:15:20 +0800201 /** Create a DhcpServer instance to be used by IpServer. */
202 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
203 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800204 }
205
markchien74a4fa92019-09-09 20:50:49 +0800206 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800207 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800208 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800209 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800210 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800211 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800212 // notification from the {@link Tethering.TetherMainSM} that it had trouble enabling IP
213 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800214 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800215 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble disabling IP
216 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800217 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800218 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble starting
219 // tethering
markchien6cf0e552019-12-06 15:24:53 +0800220 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800221 // notification from the {@link Tethering.TetherMainSM} that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800222 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800223 // notification from the {@link Tethering.TetherMainSM} that it had trouble setting the DNS
224 // forwarders
markchien6cf0e552019-12-06 15:24:53 +0800225 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800226 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800227 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800228 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800229 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900230 // new neighbor cache entry on our interface
231 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900232 // request from DHCP server that it wants to have a new prefix
233 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800234 // request from PrivateAddressCoordinator to restart tethering.
235 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
markchien74a4fa92019-09-09 20:50:49 +0800236
237 private final State mInitialState;
238 private final State mLocalHotspotState;
239 private final State mTetheredState;
240 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800241 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800242
243 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800244 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800245 @NonNull
246 private final BpfCoordinator mBpfCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800247 private final Callback mCallback;
248 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800249 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800250
251 private final String mIfaceName;
252 private final int mInterfaceType;
253 private final LinkProperties mLinkProperties;
254 private final boolean mUsingLegacyDhcp;
markchienfb65dfe2022-02-25 23:14:58 +0800255 private final int mP2pLeasesSubnetPrefixLength;
markchien74a4fa92019-09-09 20:50:49 +0800256
257 private final Dependencies mDeps;
258
259 private int mLastError;
260 private int mServingMode;
261 private InterfaceSet mUpstreamIfaceSet; // may change over time
262 private InterfaceParams mInterfaceParams;
263 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
264 // properties are those selected by the IPv6TetheringCoordinator and relayed
265 // to us. By comparison, mLinkProperties contains the addresses and directly
266 // connected routes that have been formed from these properties iff. we have
267 // succeeded in configuring them and are able to announce them within Router
268 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
269 private LinkProperties mLastIPv6LinkProperties;
270 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700271 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800272
273 // To be accessed only on the handler thread
274 private int mDhcpServerStartIndex = 0;
275 private IDhcpServer mDhcpServer;
276 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800277
278 private LinkAddress mStaticIpv4ServerAddr;
279 private LinkAddress mStaticIpv4ClientAddr;
280
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900281 @NonNull
282 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800283
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900284 private int mLastIPv6UpstreamIfindex = 0;
KH Shi68770342023-08-17 14:34:31 +0000285 private boolean mUpstreamSupportsBpf = false;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900286
287 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
288 public void accept(NeighborEvent e) {
289 sendMessage(CMD_NEIGHBOR_EVENT, e);
290 }
291 }
292
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900293 private final IpNeighborMonitor mIpNeighborMonitor;
294
markchienc9daba32020-02-12 00:19:21 +0800295 private LinkAddress mIpv4Address;
296
Wayne Ma6cd440f2022-03-14 18:04:33 +0800297 private final TetheringMetrics mTetheringMetrics;
298
Hungming Chen5bc3af92020-05-12 19:15:24 +0800299 // TODO: Add a dependency object to pass the data members or variables from the tethering
300 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800301 public IpServer(
302 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800303 INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
markchienb961d3d2022-02-26 00:39:06 +0800304 TetheringConfiguration config, PrivateAddressCoordinator addressCoordinator,
Wayne Ma6cd440f2022-03-14 18:04:33 +0800305 TetheringMetrics tetheringMetrics, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800306 super(ifaceName, looper);
307 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800308 mNetd = netd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800309 mBpfCoordinator = coordinator;
markchien74a4fa92019-09-09 20:50:49 +0800310 mCallback = callback;
311 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
312 mIfaceName = ifaceName;
313 mInterfaceType = interfaceType;
314 mLinkProperties = new LinkProperties();
markchienb961d3d2022-02-26 00:39:06 +0800315 mUsingLegacyDhcp = config.useLegacyDhcpServer();
markchienfb65dfe2022-02-25 23:14:58 +0800316 mP2pLeasesSubnetPrefixLength = config.getP2pLeasesSubnetPrefixLength();
markchienc9daba32020-02-12 00:19:21 +0800317 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800318 mDeps = deps;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800319 mTetheringMetrics = tetheringMetrics;
markchien74a4fa92019-09-09 20:50:49 +0800320 resetLinkProperties();
Mark74461fc2022-12-14 08:49:40 +0000321 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800322 mServingMode = STATE_AVAILABLE;
323
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900324 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
325 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800326
KH Shie4d549a2023-08-28 09:57:34 +0000327 // IP neighbor monitor monitors the neighbor events for adding/removing IPv6 downstream rule
328 // per client. If BPF offload is not supported, don't start listening for neighbor events.
329 if (mBpfCoordinator.isUsingBpfOffload() && !mIpNeighborMonitor.start()) {
Hungming Chen5bc3af92020-05-12 19:15:24 +0800330 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900331 }
332
markchien74a4fa92019-09-09 20:50:49 +0800333 mInitialState = new InitialState();
334 mLocalHotspotState = new LocalHotspotState();
335 mTetheredState = new TetheredState();
336 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800337 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800338 addState(mInitialState);
339 addState(mLocalHotspotState);
340 addState(mTetheredState);
markchienc9daba32020-02-12 00:19:21 +0800341 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800342 addState(mUnavailableState);
343
344 setInitialState(mInitialState);
345 }
346
347 /** Interface name which IpServer served.*/
348 public String interfaceName() {
349 return mIfaceName;
350 }
351
352 /**
markchien9b4d7572019-12-25 19:40:32 +0800353 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800354 */
355 public int interfaceType() {
356 return mInterfaceType;
357 }
358
359 /** Last error from this IpServer. */
360 public int lastError() {
361 return mLastError;
362 }
363
364 /** Serving mode is the current state of IpServer state machine. */
365 public int servingMode() {
366 return mServingMode;
367 }
368
369 /** The properties of the network link which IpServer is serving. */
370 public LinkProperties linkProperties() {
371 return new LinkProperties(mLinkProperties);
372 }
373
markchienc9daba32020-02-12 00:19:21 +0800374 /** The address which IpServer is using. */
375 public LinkAddress getAddress() {
376 return mIpv4Address;
377 }
378
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900379 /**
380 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
381 * thread.
382 */
383 public List<TetheredClient> getAllLeases() {
384 return Collections.unmodifiableList(mDhcpLeases);
385 }
386
Marka5424582022-12-01 13:46:32 +0000387 /** Enable this IpServer. IpServer state machine will be tethered or localHotspot state. */
388 public void enable(final int requestedState, final TetheringRequestParcel request) {
389 sendMessage(CMD_TETHER_REQUESTED, requestedState, 0, request);
390 }
391
markchien74a4fa92019-09-09 20:50:49 +0800392 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
393 public void stop() {
394 sendMessage(CMD_INTERFACE_DOWN);
395 }
396
397 /**
398 * Tethering is canceled. IpServer state machine will be available and wait for
399 * next tethering request.
400 */
401 public void unwanted() {
402 sendMessage(CMD_TETHER_UNREQUESTED);
403 }
404
405 /** Internals. */
406
Mark49649c92023-03-15 06:45:04 +0000407 private boolean startIPv4(int scope) {
408 return configureIPv4(true, scope);
markchien74a4fa92019-09-09 20:50:49 +0800409 }
410
411 /**
412 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
413 * handler.
414 *
415 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
416 * with different implementations of the callback, to differentiate handling of success/error in
417 * each call.
418 */
419 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
420 @Override
421 public void onStatusAvailable(int statusCode) {
422 getHandler().post(() -> callback(statusCode));
423 }
424
425 public abstract void callback(int statusCode);
426
427 @Override
428 public int getInterfaceVersion() {
429 return this.VERSION;
430 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900431
432 @Override
433 public String getInterfaceHash() {
434 return this.HASH;
435 }
markchien74a4fa92019-09-09 20:50:49 +0800436 }
437
438 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
439 private final int mStartIndex;
440
441 private DhcpServerCallbacksImpl(int startIndex) {
442 mStartIndex = startIndex;
443 }
444
445 @Override
446 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
447 getHandler().post(() -> {
448 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
449 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800450 // This start request is obsolete. Explicitly stop the DHCP server to shut
451 // down its thread. When the |server| binder token goes out of scope, the
452 // garbage collector will finalize it, which causes the network stack process
453 // garbage collector to collect the server itself.
454 try {
455 server.stop(null);
456 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800457 return;
458 }
459
460 if (statusCode != STATUS_SUCCESS) {
461 mLog.e("Error obtaining DHCP server: " + statusCode);
462 handleError();
463 return;
464 }
465
466 mDhcpServer = server;
467 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900468 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800469 @Override
470 public void callback(int startStatusCode) {
471 if (startStatusCode != STATUS_SUCCESS) {
472 mLog.e("Error starting DHCP server: " + startStatusCode);
473 handleError();
474 }
475 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900476 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800477 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800478 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800479 }
480 });
481 }
482
483 private void handleError() {
Mark74461fc2022-12-14 08:49:40 +0000484 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800485 transitionTo(mInitialState);
486 }
487 }
488
Xiao Ma4455d6b2020-04-09 10:13:44 +0900489 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900490 @Override
491 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
492 final ArrayList<TetheredClient> leases = new ArrayList<>();
493 for (DhcpLeaseParcelable lease : leaseParcelables) {
494 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900495 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
496 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
497 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900498
499 final MacAddress macAddress;
500 try {
501 macAddress = MacAddress.fromBytes(lease.hwAddr);
502 } catch (IllegalArgumentException e) {
503 Log.wtf(TAG, "Invalid address received from DhcpServer: "
504 + Arrays.toString(lease.hwAddr));
505 return;
506 }
507
508 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900509 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900510 leases.add(new TetheredClient(
511 macAddress,
512 Collections.singletonList(addressInfo),
513 mInterfaceType));
514 }
515
516 getHandler().post(() -> {
517 mDhcpLeases = leases;
518 mCallback.dhcpLeasesChanged();
519 });
520 }
521
522 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900523 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
524 Objects.requireNonNull(currentPrefix);
525 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900526 }
527
528 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900529 public int getInterfaceVersion() {
530 return this.VERSION;
531 }
532
533 @Override
534 public String getInterfaceHash() throws RemoteException {
535 return this.HASH;
536 }
537 }
538
Xiao Ma4455d6b2020-04-09 10:13:44 +0900539 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
540 Objects.requireNonNull(ipv4Address);
541 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
542 }
543
544 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
545 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
546 @Nullable Inet4Address clientAddr) {
547 final boolean changePrefixOnDecline =
548 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
markchienfb65dfe2022-02-25 23:14:58 +0800549 final int subnetPrefixLength = mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
550 ? mP2pLeasesSubnetPrefixLength : 0 /* default value */;
551
Xiao Ma4455d6b2020-04-09 10:13:44 +0900552 return new DhcpServingParamsParcelExt()
553 .setDefaultRouters(defaultRouter)
554 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
555 .setDnsServers(dnsServer)
556 .setServerAddr(serverAddr)
557 .setMetered(true)
558 .setSingleClientAddr(clientAddr)
markchienfb65dfe2022-02-25 23:14:58 +0800559 .setChangePrefixOnDecline(changePrefixOnDecline)
560 .setLeasesSubnetPrefixLength(subnetPrefixLength);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900561 // TODO: also advertise link MTU
562 }
563
markchien245352e2020-02-27 20:27:18 +0800564 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800565 if (mUsingLegacyDhcp) {
566 return true;
567 }
markchien245352e2020-02-27 20:27:18 +0800568
569 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800570 final Inet4Address clientAddr = clientLinkAddr == null ? null :
571 (Inet4Address) clientLinkAddr.getAddress();
572
Xiao Ma4455d6b2020-04-09 10:13:44 +0900573 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
574 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800575 mDhcpServerStartIndex++;
576 mDeps.makeDhcpServer(
577 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
578 return true;
579 }
580
581 private void stopDhcp() {
582 // Make all previous start requests obsolete so servers are not started later
583 mDhcpServerStartIndex++;
584
585 if (mDhcpServer != null) {
586 try {
587 mDhcpServer.stop(new OnHandlerStatusCallback() {
588 @Override
589 public void callback(int statusCode) {
590 if (statusCode != STATUS_SUCCESS) {
591 mLog.e("Error stopping DHCP server: " + statusCode);
Mark74461fc2022-12-14 08:49:40 +0000592 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800593 // Not much more we can do here
594 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900595 mDhcpLeases.clear();
596 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800597 }
598 });
599 mDhcpServer = null;
600 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900601 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800602 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800603 }
604 }
605 }
606
markchien245352e2020-02-27 20:27:18 +0800607 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
608 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800609 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800610 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800611 } else {
612 stopDhcp();
613 return true;
614 }
615 }
616
617 private void stopIPv4() {
Mark49649c92023-03-15 06:45:04 +0000618 configureIPv4(false /* enabled */, CONNECTIVITY_SCOPE_GLOBAL /* not used */);
markchien74a4fa92019-09-09 20:50:49 +0800619 // NOTE: All of configureIPv4() will be refactored out of existence
620 // into calls to InterfaceController, shared with startIPv4().
621 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800622 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800623 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800624 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800625 mStaticIpv4ServerAddr = null;
626 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800627 }
628
Mark49649c92023-03-15 06:45:04 +0000629 private boolean configureIPv4(boolean enabled, int scope) {
markchien74a4fa92019-09-09 20:50:49 +0800630 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
631
markchienc9daba32020-02-12 00:19:21 +0800632 if (enabled) {
Mark49649c92023-03-15 06:45:04 +0000633 mIpv4Address = requestIpv4Address(scope, true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800634 }
635
636 if (mIpv4Address == null) {
637 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800638 return false;
markchien74a4fa92019-09-09 20:50:49 +0800639 }
640
markchien69681d62021-11-15 23:58:05 +0800641 if (shouldNotConfigureBluetoothInterface()) {
642 // Interface was already configured elsewhere, only start DHCP.
markchienc9daba32020-02-12 00:19:21 +0800643 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
644 }
645
646 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
647
markchien12c5bb82020-01-07 14:43:17 +0800648 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800649 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900650 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200651 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
652 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900653 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800654 // It is unclear whether the Bluetooth or USB stacks will manage their own
655 // state.
656 setIfaceUp = null;
657 } else {
658 setIfaceUp = enabled;
659 }
660 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
661 mLog.e("Error configuring interface");
662 if (!enabled) stopDhcp();
663 return false;
664 }
markchien74a4fa92019-09-09 20:50:49 +0800665
markchien74a4fa92019-09-09 20:50:49 +0800666 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800667 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900668 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800669 } else {
markchien12c5bb82020-01-07 14:43:17 +0800670 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900671 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800672 }
markchien245352e2020-02-27 20:27:18 +0800673 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800674 }
675
markchien69681d62021-11-15 23:58:05 +0800676 private boolean shouldNotConfigureBluetoothInterface() {
677 // Before T, bluetooth tethering configures the interface elsewhere.
678 return (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) && !SdkLevel.isAtLeastT();
679 }
680
Mark49649c92023-03-15 06:45:04 +0000681 private LinkAddress requestIpv4Address(final int scope, final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800682 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800683
markchien69681d62021-11-15 23:58:05 +0800684 if (shouldNotConfigureBluetoothInterface()) return new LinkAddress(BLUETOOTH_IFACE_ADDR);
markchienc9daba32020-02-12 00:19:21 +0800685
Mark49649c92023-03-15 06:45:04 +0000686 return mPrivateAddressCoordinator.requestDownstreamAddress(this, scope, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900687 }
688
markchien74a4fa92019-09-09 20:50:49 +0800689 private boolean startIPv6() {
690 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
691 if (mInterfaceParams == null) {
692 mLog.e("Failed to find InterfaceParams");
693 stopIPv6();
694 return false;
695 }
696
697 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
698 if (!mRaDaemon.start()) {
699 stopIPv6();
700 return false;
701 }
702
markchien932df542021-08-12 13:56:43 +0800703 if (SdkLevel.isAtLeastS()) {
Tyler Wear90e40632020-03-13 11:38:38 -0700704 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
705 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
706 }
707
markchien74a4fa92019-09-09 20:50:49 +0800708 return true;
709 }
710
711 private void stopIPv6() {
712 mInterfaceParams = null;
713 setRaParams(null);
714
715 if (mRaDaemon != null) {
716 mRaDaemon.stop();
717 mRaDaemon = null;
718 }
Tyler Wear90e40632020-03-13 11:38:38 -0700719
720 if (mDadProxy != null) {
721 mDadProxy.stop();
722 mDadProxy = null;
723 }
markchien74a4fa92019-09-09 20:50:49 +0800724 }
725
726 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
727 // LinkProperties. These have extraneous data filtered out and only the
728 // necessary prefixes included (per its prefix distribution policy).
729 //
730 // TODO: Evaluate using a data structure than is more directly suited to
731 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800732 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800733 if (mRaDaemon == null) return;
734
735 // Avoid unnecessary work on spurious updates.
736 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
737 return;
738 }
739
740 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700741 String upstreamIface = null;
742 InterfaceParams upstreamIfaceParams = null;
743 int upstreamIfIndex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800744
745 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700746 upstreamIface = v6only.getInterfaceName();
747 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
748 if (upstreamIfaceParams != null) {
749 upstreamIfIndex = upstreamIfaceParams.index;
750 }
markchien74a4fa92019-09-09 20:50:49 +0800751 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700752 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800753 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
754
markchiend63c4f32020-05-21 17:38:28 +0800755 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800756
757 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
758 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
759
760 final IpPrefix prefix = new IpPrefix(
761 linkAddr.getAddress(), linkAddr.getPrefixLength());
762 params.prefixes.add(prefix);
763
764 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
765 if (dnsServer != null) {
766 params.dnses.add(dnsServer);
767 }
768 }
769 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900770
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900771 // Add upstream index to name mapping. See the comment of the interface mapping update in
772 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
773 // timing issue. It prevents that the IPv6 capability is updated later than
774 // CMD_TETHER_CONNECTION_CHANGED.
775 mBpfCoordinator.addUpstreamNameToLookupTable(upstreamIfIndex, upstreamIface);
776
markchien74a4fa92019-09-09 20:50:49 +0800777 // If v6only is null, we pass in null to setRaParams(), which handles
778 // deprecation of any existing RA data.
markchien74a4fa92019-09-09 20:50:49 +0800779 setRaParams(params);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900780
KH Shi68770342023-08-17 14:34:31 +0000781 // Not support BPF on virtual upstream interface
782 final boolean upstreamSupportsBpf = upstreamIface != null && !isVcnInterface(upstreamIface);
783 updateIpv6ForwardingRules(
784 mLastIPv6UpstreamIfindex, upstreamIfIndex, upstreamSupportsBpf, null);
785 mLastIPv6LinkProperties = v6only;
Tyler Wear90e40632020-03-13 11:38:38 -0700786 mLastIPv6UpstreamIfindex = upstreamIfIndex;
KH Shi68770342023-08-17 14:34:31 +0000787 mUpstreamSupportsBpf = upstreamSupportsBpf;
Tyler Wear90e40632020-03-13 11:38:38 -0700788 if (mDadProxy != null) {
789 mDadProxy.setUpstreamIface(upstreamIfaceParams);
790 }
markchien74a4fa92019-09-09 20:50:49 +0800791 }
792
Xiao Ma4455d6b2020-04-09 10:13:44 +0900793 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900794 final int removalFailures = NetdUtils.removeRoutesFromLocalNetwork(
Xiao Ma4455d6b2020-04-09 10:13:44 +0900795 mNetd, toBeRemoved);
796 if (removalFailures > 0) {
797 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
798 removalFailures));
799 }
800
801 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
802 }
803
804 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
805 try {
806 // It's safe to call networkAddInterface() even if
807 // the interface is already in the local_network.
808 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
809 try {
810 // Add routes from local network. Note that adding routes that
811 // already exist does not cause an error (EEXIST is silently ignored).
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900812 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900813 } catch (IllegalStateException e) {
814 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
815 return;
816 }
817 } catch (ServiceSpecificException | RemoteException e) {
818 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
819 return;
820 }
821
822 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
823 }
824
markchien74a4fa92019-09-09 20:50:49 +0800825 private void configureLocalIPv6Routes(
826 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
827 // [1] Remove the routes that are deprecated.
828 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900829 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800830 }
831
832 // [2] Add only the routes that have not previously been added.
833 if (newPrefixes != null && !newPrefixes.isEmpty()) {
834 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
835 if (mLastRaParams != null) {
836 addedPrefixes.removeAll(mLastRaParams.prefixes);
837 }
838
839 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900840 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800841 }
842 }
843 }
844
845 private void configureLocalIPv6Dns(
846 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
847 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
848 if (mNetd == null) {
849 if (newDnses != null) newDnses.clear();
850 mLog.e("No netd service instance available; not setting local IPv6 addresses");
851 return;
852 }
853
854 // [1] Remove deprecated local DNS IP addresses.
855 if (!deprecatedDnses.isEmpty()) {
856 for (Inet6Address dns : deprecatedDnses) {
857 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
858 mLog.e("Failed to remove local dns IP " + dns);
859 }
860
861 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
862 }
863 }
864
865 // [2] Add only the local DNS IP addresses that have not previously been added.
866 if (newDnses != null && !newDnses.isEmpty()) {
867 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
868 if (mLastRaParams != null) {
869 addedDnses.removeAll(mLastRaParams.dnses);
870 }
871
872 for (Inet6Address dns : addedDnses) {
873 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
874 mLog.e("Failed to add local dns IP " + dns);
875 newDnses.remove(dns);
876 }
877
878 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
879 }
880 }
881
882 try {
883 mNetd.tetherApplyDnsInterfaces();
884 } catch (ServiceSpecificException | RemoteException e) {
885 mLog.e("Failed to update local DNS caching server");
886 if (newDnses != null) newDnses.clear();
887 }
888 }
889
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900890 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
891 // changes or if a neighbor event is received.
892 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
KH Shi68770342023-08-17 14:34:31 +0000893 boolean upstreamSupportsBpf, NeighborEvent e) {
894 // If no longer have an upstream or upstream not supports BPF, clear forwarding rules and do
markchien7dc1b4d2021-07-13 17:12:56 +0800895 // nothing else.
896 // TODO: Rather than always clear rules, ensure whether ipv6 ever enable first.
KH Shi68770342023-08-17 14:34:31 +0000897 if (upstreamIfindex == 0 || !upstreamSupportsBpf) {
KH Shie4d549a2023-08-28 09:57:34 +0000898 mBpfCoordinator.tetherOffloadRuleClear(this);
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900899 return;
900 }
901
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900902 // If the upstream interface has changed, remove all rules and re-add them with the new
903 // upstream interface.
904 if (prevUpstreamIfindex != upstreamIfindex) {
KH Shie4d549a2023-08-28 09:57:34 +0000905 mBpfCoordinator.tetherOffloadRuleUpdate(this, upstreamIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900906 }
907
908 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900909 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900910 if (e == null) return;
911 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
912 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
913 return;
914 }
915
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900916 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
KH Shi59ad35e2023-08-15 07:13:00 +0000917 // Do this here instead of in the Ipv6DownstreamRule constructor to ensure that we
918 // never add rules with a null MAC, only delete them.
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900919 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
KH Shi59ad35e2023-08-15 07:13:00 +0000920 Ipv6DownstreamRule rule = new Ipv6DownstreamRule(upstreamIfindex, mInterfaceParams.index,
921 (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900922 if (e.isValid()) {
KH Shie4d549a2023-08-28 09:57:34 +0000923 mBpfCoordinator.addIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900924 } else {
KH Shie4d549a2023-08-28 09:57:34 +0000925 mBpfCoordinator.removeIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900926 }
927 }
928
Hungming Chend71c06e2020-12-21 19:39:49 +0800929 // TODO: consider moving into BpfCoordinator.
930 private void updateClientInfoIpv4(NeighborEvent e) {
Hungming Chend71c06e2020-12-21 19:39:49 +0800931 if (e == null) return;
932 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
933 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
934 return;
935 }
936
937 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
938 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
939 // IpServer never add clients with a null MAC, only delete them.
940 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
941 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
942 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
943 if (e.isValid()) {
944 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
945 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +0800946 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
947 }
948 }
949
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900950 private void handleNeighborEvent(NeighborEvent e) {
951 if (mInterfaceParams != null
952 && mInterfaceParams.index == e.ifindex
953 && mInterfaceParams.hasMacAddress) {
KH Shi68770342023-08-17 14:34:31 +0000954 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex,
955 mUpstreamSupportsBpf, e);
Hungming Chend71c06e2020-12-21 19:39:49 +0800956 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900957 }
958 }
959
markchiend63c4f32020-05-21 17:38:28 +0800960 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +0800961 try {
962 int upstreamHopLimit = Integer.parseUnsignedInt(
963 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +0800964 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +0800965 // Cap the hop limit to 255.
966 return (byte) Integer.min(upstreamHopLimit, 255);
967 } catch (Exception e) {
968 mLog.e("Failed to find upstream interface hop limit", e);
969 }
970 return RaParams.DEFAULT_HOPLIMIT;
971 }
972
973 private void setRaParams(RaParams newParams) {
974 if (mRaDaemon != null) {
975 final RaParams deprecatedParams =
976 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
977
978 configureLocalIPv6Routes(deprecatedParams.prefixes,
979 (newParams != null) ? newParams.prefixes : null);
980
981 configureLocalIPv6Dns(deprecatedParams.dnses,
982 (newParams != null) ? newParams.dnses : null);
983
984 mRaDaemon.buildNewRa(deprecatedParams, newParams);
985 }
986
987 mLastRaParams = newParams;
988 }
989
markchien21021ef2021-06-01 10:58:04 +0800990 private void maybeLogMessage(State state, int what) {
991 switch (what) {
992 // Suppress some CMD_* to avoid log flooding.
993 case CMD_IPV6_TETHER_UPDATE:
994 case CMD_NEIGHBOR_EVENT:
995 break;
996 default:
997 mLog.log(state.getName() + " got "
998 + sMagicDecoderRing.get(what, Integer.toString(what)));
999 }
markchien74a4fa92019-09-09 20:50:49 +08001000 }
1001
1002 private void sendInterfaceState(int newInterfaceState) {
1003 mServingMode = newInterfaceState;
1004 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1005 sendLinkProperties();
1006 }
1007
1008 private void sendLinkProperties() {
1009 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1010 }
1011
1012 private void resetLinkProperties() {
1013 mLinkProperties.clear();
1014 mLinkProperties.setInterfaceName(mIfaceName);
1015 }
1016
markchienf053e4b2020-03-16 21:49:48 +08001017 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001018 // Ignore static address configuration if they are invalid or null. In theory, static
1019 // addresses should not be invalid here because TetheringManager do not allow caller to
1020 // specify invalid static address configuration.
1021 if (request == null || request.localIPv4Address == null
1022 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1023 request.localIPv4Address, request.staticClientAddress)) {
1024 return;
1025 }
markchienf053e4b2020-03-16 21:49:48 +08001026
1027 mStaticIpv4ServerAddr = request.localIPv4Address;
1028 mStaticIpv4ClientAddr = request.staticClientAddress;
1029 }
1030
markchien74a4fa92019-09-09 20:50:49 +08001031 class InitialState extends State {
1032 @Override
1033 public void enter() {
1034 sendInterfaceState(STATE_AVAILABLE);
1035 }
1036
1037 @Override
1038 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001039 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001040 switch (message.what) {
1041 case CMD_TETHER_REQUESTED:
Mark74461fc2022-12-14 08:49:40 +00001042 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001043 switch (message.arg1) {
1044 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001045 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001046 transitionTo(mLocalHotspotState);
1047 break;
1048 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001049 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001050 transitionTo(mTetheredState);
1051 break;
1052 default:
1053 mLog.e("Invalid tethering interface serving state specified.");
1054 }
1055 break;
1056 case CMD_INTERFACE_DOWN:
1057 transitionTo(mUnavailableState);
1058 break;
markchien74a4fa92019-09-09 20:50:49 +08001059 default:
1060 return NOT_HANDLED;
1061 }
1062 return HANDLED;
1063 }
1064 }
1065
Hungming Chen46c30b12020-10-15 17:25:36 +08001066 private void startConntrackMonitoring() {
1067 mBpfCoordinator.startMonitoring(this);
1068 }
1069
1070 private void stopConntrackMonitoring() {
1071 mBpfCoordinator.stopMonitoring(this);
1072 }
1073
Mark3ec851e2023-05-19 08:50:38 +00001074 abstract class BaseServingState extends State {
1075 private final int mDesiredInterfaceState;
1076
1077 BaseServingState(int interfaceState) {
1078 mDesiredInterfaceState = interfaceState;
1079 }
1080
markchien74a4fa92019-09-09 20:50:49 +08001081 @Override
1082 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001083 startConntrackMonitoring();
1084
Mark3ec851e2023-05-19 08:50:38 +00001085 startServingInterface();
1086
1087 if (mLastError != TETHER_ERROR_NO_ERROR) {
1088 transitionTo(mInitialState);
1089 }
1090
1091 if (DBG) Log.d(TAG, getStateString(mDesiredInterfaceState) + " serve " + mIfaceName);
1092 sendInterfaceState(mDesiredInterfaceState);
1093 }
1094
Mark49649c92023-03-15 06:45:04 +00001095 private int getScope() {
1096 if (mDesiredInterfaceState == STATE_TETHERED) {
1097 return CONNECTIVITY_SCOPE_GLOBAL;
1098 }
1099
1100 return CONNECTIVITY_SCOPE_LOCAL;
1101 }
1102
Mark3ec851e2023-05-19 08:50:38 +00001103 private void startServingInterface() {
Mark49649c92023-03-15 06:45:04 +00001104 if (!startIPv4(getScope())) {
Mark74461fc2022-12-14 08:49:40 +00001105 mLastError = TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001106 return;
1107 }
1108
1109 try {
markchienc9daba32020-02-12 00:19:21 +08001110 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001111 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001112 mLog.e("Error Tethering", e);
Mark74461fc2022-12-14 08:49:40 +00001113 mLastError = TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001114 return;
1115 }
1116
1117 if (!startIPv6()) {
1118 mLog.e("Failed to startIPv6");
1119 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1120 return;
1121 }
1122 }
1123
1124 @Override
1125 public void exit() {
1126 // Note that at this point, we're leaving the tethered state. We can fail any
1127 // of these operations, but it doesn't really change that we have to try them
1128 // all in sequence.
1129 stopIPv6();
1130
1131 try {
markchien12c5bb82020-01-07 14:43:17 +08001132 NetdUtils.untetherInterface(mNetd, mIfaceName);
1133 } catch (RemoteException | ServiceSpecificException e) {
Mark74461fc2022-12-14 08:49:40 +00001134 mLastError = TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001135 mLog.e("Failed to untether interface: " + e);
1136 }
1137
1138 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001139 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001140
1141 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001142
1143 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1144 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001145 }
1146
1147 @Override
1148 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001149 switch (message.what) {
1150 case CMD_TETHER_UNREQUESTED:
1151 transitionTo(mInitialState);
1152 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1153 break;
1154 case CMD_INTERFACE_DOWN:
1155 transitionTo(mUnavailableState);
1156 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1157 break;
1158 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001159 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001160 sendLinkProperties();
1161 break;
1162 case CMD_IP_FORWARDING_ENABLE_ERROR:
1163 case CMD_IP_FORWARDING_DISABLE_ERROR:
1164 case CMD_START_TETHERING_ERROR:
1165 case CMD_STOP_TETHERING_ERROR:
1166 case CMD_SET_DNS_FORWARDERS_ERROR:
Mark74461fc2022-12-14 08:49:40 +00001167 mLastError = TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001168 transitionTo(mInitialState);
1169 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001170 case CMD_NEW_PREFIX_REQUEST:
1171 handleNewPrefixRequest((IpPrefix) message.obj);
1172 break;
markchienc9daba32020-02-12 00:19:21 +08001173 case CMD_NOTIFY_PREFIX_CONFLICT:
1174 mLog.i("restart tethering: " + mInterfaceType);
1175 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1176 transitionTo(mWaitingForRestartState);
1177 break;
markchien74a4fa92019-09-09 20:50:49 +08001178 default:
1179 return false;
1180 }
1181 return true;
1182 }
Mark3ec851e2023-05-19 08:50:38 +00001183
1184 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
1185 if (!currentPrefix.contains(mIpv4Address.getAddress())
1186 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
1187 Log.e(TAG, "Invalid prefix: " + currentPrefix);
1188 return;
1189 }
1190
1191 final LinkAddress deprecatedLinkAddress = mIpv4Address;
Mark49649c92023-03-15 06:45:04 +00001192 mIpv4Address = requestIpv4Address(getScope(), false);
Mark3ec851e2023-05-19 08:50:38 +00001193 if (mIpv4Address == null) {
1194 mLog.e("Fail to request a new downstream prefix");
1195 return;
1196 }
1197 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
1198
1199 // Add new IPv4 address on the interface.
1200 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1201 mLog.e("Failed to add new IP " + srvAddr);
1202 return;
1203 }
1204
1205 // Remove deprecated routes from local network.
1206 removeRoutesFromLocalNetwork(
1207 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1208 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1209
1210 // Add new routes to local network.
1211 addRoutesToLocalNetwork(
1212 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1213 mLinkProperties.addLinkAddress(mIpv4Address);
1214
1215 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1216 // listen on the interface configured with new IPv4 address, that results DNS validation
1217 // failure of downstream client even if appropriate routes have been configured.
1218 try {
1219 mNetd.tetherApplyDnsInterfaces();
1220 } catch (ServiceSpecificException | RemoteException e) {
1221 mLog.e("Failed to update local DNS caching server");
1222 return;
1223 }
1224 sendLinkProperties();
1225
1226 // Notify DHCP server that new prefix/route has been applied on IpServer.
1227 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1228 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1229 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1230 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1231 try {
1232 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1233 @Override
1234 public void callback(int statusCode) {
1235 if (statusCode != STATUS_SUCCESS) {
1236 mLog.e("Error updating DHCP serving params: " + statusCode);
1237 }
1238 }
1239 });
1240 } catch (RemoteException e) {
1241 mLog.e("Error updating DHCP serving params", e);
1242 }
1243 }
markchien74a4fa92019-09-09 20:50:49 +08001244 }
1245
1246 // Handling errors in BaseServingState.enter() by transitioning is
1247 // problematic because transitioning during a multi-state jump yields
1248 // a Log.wtf(). Ultimately, there should be only one ServingState,
1249 // and forwarding and NAT rules should be handled by a coordinating
1250 // functional element outside of IpServer.
1251 class LocalHotspotState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001252 LocalHotspotState() {
1253 super(STATE_LOCAL_ONLY);
markchien74a4fa92019-09-09 20:50:49 +08001254 }
1255
1256 @Override
1257 public boolean processMessage(Message message) {
1258 if (super.processMessage(message)) return true;
1259
markchien21021ef2021-06-01 10:58:04 +08001260 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001261 switch (message.what) {
1262 case CMD_TETHER_REQUESTED:
1263 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1264 break;
1265 case CMD_TETHER_CONNECTION_CHANGED:
1266 // Ignored in local hotspot state.
1267 break;
1268 default:
1269 return false;
1270 }
1271 return true;
1272 }
1273 }
1274
1275 // Handling errors in BaseServingState.enter() by transitioning is
1276 // problematic because transitioning during a multi-state jump yields
1277 // a Log.wtf(). Ultimately, there should be only one ServingState,
1278 // and forwarding and NAT rules should be handled by a coordinating
1279 // functional element outside of IpServer.
1280 class TetheredState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001281 TetheredState() {
1282 super(STATE_TETHERED);
markchien74a4fa92019-09-09 20:50:49 +08001283 }
1284
1285 @Override
1286 public void exit() {
1287 cleanupUpstream();
1288 super.exit();
1289 }
1290
Hungming Chena6e78692021-02-08 17:15:35 +08001291 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1292 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1293 // and behaviour. While upstream is switching from offload supported interface to
1294 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1295 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1296 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1297 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1298 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1299 // in the state machine. Once there is any case out whish is not covered by previous cases,
1300 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001301 private void cleanupUpstream() {
1302 if (mUpstreamIfaceSet == null) return;
1303
1304 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1305 mUpstreamIfaceSet = null;
KH Shie4d549a2023-08-28 09:57:34 +00001306 mBpfCoordinator.tetherOffloadRuleClear(IpServer.this);
markchien74a4fa92019-09-09 20:50:49 +08001307 }
1308
1309 private void cleanupUpstreamInterface(String upstreamIface) {
1310 // Note that we don't care about errors here.
1311 // Sometimes interfaces are gone before we get
1312 // to remove their rules, which generates errors.
1313 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001314 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001315 try {
markchien12c5bb82020-01-07 14:43:17 +08001316 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1317 } catch (RemoteException | ServiceSpecificException e) {
1318 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001319 }
1320 try {
markchien12c5bb82020-01-07 14:43:17 +08001321 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1322 } catch (RemoteException | ServiceSpecificException e) {
1323 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001324 }
1325 }
1326
1327 @Override
1328 public boolean processMessage(Message message) {
1329 if (super.processMessage(message)) return true;
1330
markchien21021ef2021-06-01 10:58:04 +08001331 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001332 switch (message.what) {
1333 case CMD_TETHER_REQUESTED:
1334 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1335 break;
1336 case CMD_TETHER_CONNECTION_CHANGED:
1337 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1338 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1339 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1340 break;
1341 }
1342
1343 if (newUpstreamIfaceSet == null) {
1344 cleanupUpstream();
1345 break;
1346 }
1347
1348 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1349 cleanupUpstreamInterface(removed);
1350 }
1351
1352 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1353 // This makes the call to cleanupUpstream() in the error
1354 // path for any interface neatly cleanup all the interfaces.
1355 mUpstreamIfaceSet = newUpstreamIfaceSet;
1356
1357 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001358 // Add upstream index to name mapping for the tether stats usage in the
1359 // coordinator. Although this mapping could be added by both class
1360 // Tethering and IpServer, adding mapping from IpServer guarantees that
1361 // the mapping is added before adding forwarding rules. That is because
1362 // there are different state machines in both classes. It is hard to
1363 // guarantee the link property update order between multiple state machines.
1364 // Note that both IPv4 and IPv6 interface may be added because
1365 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1366 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1367 // capability may be updated later. In that case, IPv6 interface mapping is
1368 // updated in updateUpstreamIPv6LinkProperties.
1369 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1370 final InterfaceParams upstreamIfaceParams =
1371 mDeps.getInterfaceParams(ifname);
1372 if (upstreamIfaceParams != null) {
1373 mBpfCoordinator.addUpstreamNameToLookupTable(
1374 upstreamIfaceParams.index, ifname);
1375 }
1376 }
1377
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001378 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001379 try {
markchien12c5bb82020-01-07 14:43:17 +08001380 mNetd.tetherAddForward(mIfaceName, ifname);
1381 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1382 } catch (RemoteException | ServiceSpecificException e) {
1383 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001384 cleanupUpstream();
Mark74461fc2022-12-14 08:49:40 +00001385 mLastError = TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001386 transitionTo(mInitialState);
1387 return true;
1388 }
1389 }
1390 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001391 case CMD_NEIGHBOR_EVENT:
1392 handleNeighborEvent((NeighborEvent) message.obj);
1393 break;
markchien74a4fa92019-09-09 20:50:49 +08001394 default:
1395 return false;
1396 }
1397 return true;
1398 }
1399
1400 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1401 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1402 if (mUpstreamIfaceSet != null && newIfaces != null) {
1403 return mUpstreamIfaceSet.equals(newIfaces);
1404 }
1405 return false;
1406 }
1407
1408 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1409 if (mUpstreamIfaceSet == null) return new HashSet<>();
1410
1411 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1412 removed.removeAll(newIfaces.ifnames);
1413 return removed;
1414 }
1415
1416 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1417 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1418 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1419 return added;
1420 }
1421 }
1422
1423 /**
1424 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001425 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001426 * specific state machine from its list of possible recipients of
1427 * tethering requests. The state machine itself will hang around until
1428 * the garbage collector finds it.
1429 */
1430 class UnavailableState extends State {
1431 @Override
1432 public void enter() {
h.zhangd244bd02020-06-14 14:46:54 +08001433 mIpNeighborMonitor.stop();
Mark74461fc2022-12-14 08:49:40 +00001434 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001435 sendInterfaceState(STATE_UNAVAILABLE);
1436 }
1437 }
1438
markchienc9daba32020-02-12 00:19:21 +08001439 class WaitingForRestartState extends State {
1440 @Override
1441 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001442 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001443 switch (message.what) {
1444 case CMD_TETHER_UNREQUESTED:
1445 transitionTo(mInitialState);
1446 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1447 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1448 break;
1449 case CMD_INTERFACE_DOWN:
1450 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001451 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001452 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1453 break;
1454 default:
1455 return false;
1456 }
1457 return true;
1458 }
1459 }
1460
markchien74a4fa92019-09-09 20:50:49 +08001461 // Accumulate routes representing "prefixes to be assigned to the local
1462 // interface", for subsequent modification of local_network routing.
1463 private static ArrayList<RouteInfo> getLocalRoutesFor(
1464 String ifname, HashSet<IpPrefix> prefixes) {
1465 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1466 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001467 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001468 }
1469 return localRoutes;
1470 }
1471
1472 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1473 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1474 final byte[] dnsBytes = localPrefix.getRawAddress();
1475 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1476 try {
1477 return Inet6Address.getByAddress(null, dnsBytes, 0);
1478 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001479 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001480 return null;
1481 }
1482 }
1483
1484 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1485 final byte random = (byte) (new Random()).nextInt();
1486 for (int value : excluded) {
1487 if (random == value) return dflt;
1488 }
1489 return random;
1490 }
1491}