blob: eadba58c22098df8eda384eb32bd8e1fac5a6c0f [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;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800255 private final boolean mUsingBpfOffload;
markchienfb65dfe2022-02-25 23:14:58 +0800256 private final int mP2pLeasesSubnetPrefixLength;
markchien74a4fa92019-09-09 20:50:49 +0800257
258 private final Dependencies mDeps;
259
260 private int mLastError;
261 private int mServingMode;
262 private InterfaceSet mUpstreamIfaceSet; // may change over time
263 private InterfaceParams mInterfaceParams;
264 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
265 // properties are those selected by the IPv6TetheringCoordinator and relayed
266 // to us. By comparison, mLinkProperties contains the addresses and directly
267 // connected routes that have been formed from these properties iff. we have
268 // succeeded in configuring them and are able to announce them within Router
269 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
270 private LinkProperties mLastIPv6LinkProperties;
271 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700272 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800273
274 // To be accessed only on the handler thread
275 private int mDhcpServerStartIndex = 0;
276 private IDhcpServer mDhcpServer;
277 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800278
279 private LinkAddress mStaticIpv4ServerAddr;
280 private LinkAddress mStaticIpv4ClientAddr;
281
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900282 @NonNull
283 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800284
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900285 private int mLastIPv6UpstreamIfindex = 0;
KH Shi68770342023-08-17 14:34:31 +0000286 private boolean mUpstreamSupportsBpf = false;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900287
288 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
289 public void accept(NeighborEvent e) {
290 sendMessage(CMD_NEIGHBOR_EVENT, e);
291 }
292 }
293
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900294 private final IpNeighborMonitor mIpNeighborMonitor;
295
markchienc9daba32020-02-12 00:19:21 +0800296 private LinkAddress mIpv4Address;
297
Wayne Ma6cd440f2022-03-14 18:04:33 +0800298 private final TetheringMetrics mTetheringMetrics;
299
Hungming Chen5bc3af92020-05-12 19:15:24 +0800300 // TODO: Add a dependency object to pass the data members or variables from the tethering
301 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800302 public IpServer(
303 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800304 INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
markchienb961d3d2022-02-26 00:39:06 +0800305 TetheringConfiguration config, PrivateAddressCoordinator addressCoordinator,
Wayne Ma6cd440f2022-03-14 18:04:33 +0800306 TetheringMetrics tetheringMetrics, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800307 super(ifaceName, looper);
308 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800309 mNetd = netd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800310 mBpfCoordinator = coordinator;
markchien74a4fa92019-09-09 20:50:49 +0800311 mCallback = callback;
312 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
313 mIfaceName = ifaceName;
314 mInterfaceType = interfaceType;
315 mLinkProperties = new LinkProperties();
markchienb961d3d2022-02-26 00:39:06 +0800316 mUsingLegacyDhcp = config.useLegacyDhcpServer();
317 mUsingBpfOffload = config.isBpfOffloadEnabled();
markchienfb65dfe2022-02-25 23:14:58 +0800318 mP2pLeasesSubnetPrefixLength = config.getP2pLeasesSubnetPrefixLength();
markchienc9daba32020-02-12 00:19:21 +0800319 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800320 mDeps = deps;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800321 mTetheringMetrics = tetheringMetrics;
markchien74a4fa92019-09-09 20:50:49 +0800322 resetLinkProperties();
Mark74461fc2022-12-14 08:49:40 +0000323 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800324 mServingMode = STATE_AVAILABLE;
325
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900326 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
327 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800328
Hungming Chen5bc3af92020-05-12 19:15:24 +0800329 // IP neighbor monitor monitors the neighbor events for adding/removing offload
Hungming Chen3d8fa882020-04-12 14:27:18 +0800330 // forwarding rules per client. If BPF offload is not supported, don't start listening
KH Shi59ad35e2023-08-15 07:13:00 +0000331 // for neighbor events. See updateIpv6ForwardingRules, addIpv6DownstreamRule,
332 // removeIpv6DownstreamRule.
Hungming Chen5bc3af92020-05-12 19:15:24 +0800333 if (mUsingBpfOffload && !mIpNeighborMonitor.start()) {
334 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900335 }
336
markchien74a4fa92019-09-09 20:50:49 +0800337 mInitialState = new InitialState();
338 mLocalHotspotState = new LocalHotspotState();
339 mTetheredState = new TetheredState();
340 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800341 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800342 addState(mInitialState);
343 addState(mLocalHotspotState);
344 addState(mTetheredState);
markchienc9daba32020-02-12 00:19:21 +0800345 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800346 addState(mUnavailableState);
347
348 setInitialState(mInitialState);
349 }
350
351 /** Interface name which IpServer served.*/
352 public String interfaceName() {
353 return mIfaceName;
354 }
355
356 /**
markchien9b4d7572019-12-25 19:40:32 +0800357 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800358 */
359 public int interfaceType() {
360 return mInterfaceType;
361 }
362
363 /** Last error from this IpServer. */
364 public int lastError() {
365 return mLastError;
366 }
367
368 /** Serving mode is the current state of IpServer state machine. */
369 public int servingMode() {
370 return mServingMode;
371 }
372
373 /** The properties of the network link which IpServer is serving. */
374 public LinkProperties linkProperties() {
375 return new LinkProperties(mLinkProperties);
376 }
377
markchienc9daba32020-02-12 00:19:21 +0800378 /** The address which IpServer is using. */
379 public LinkAddress getAddress() {
380 return mIpv4Address;
381 }
382
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900383 /**
384 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
385 * thread.
386 */
387 public List<TetheredClient> getAllLeases() {
388 return Collections.unmodifiableList(mDhcpLeases);
389 }
390
Marka5424582022-12-01 13:46:32 +0000391 /** Enable this IpServer. IpServer state machine will be tethered or localHotspot state. */
392 public void enable(final int requestedState, final TetheringRequestParcel request) {
393 sendMessage(CMD_TETHER_REQUESTED, requestedState, 0, request);
394 }
395
markchien74a4fa92019-09-09 20:50:49 +0800396 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
397 public void stop() {
398 sendMessage(CMD_INTERFACE_DOWN);
399 }
400
401 /**
402 * Tethering is canceled. IpServer state machine will be available and wait for
403 * next tethering request.
404 */
405 public void unwanted() {
406 sendMessage(CMD_TETHER_UNREQUESTED);
407 }
408
409 /** Internals. */
410
Mark49649c92023-03-15 06:45:04 +0000411 private boolean startIPv4(int scope) {
412 return configureIPv4(true, scope);
markchien74a4fa92019-09-09 20:50:49 +0800413 }
414
415 /**
416 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
417 * handler.
418 *
419 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
420 * with different implementations of the callback, to differentiate handling of success/error in
421 * each call.
422 */
423 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
424 @Override
425 public void onStatusAvailable(int statusCode) {
426 getHandler().post(() -> callback(statusCode));
427 }
428
429 public abstract void callback(int statusCode);
430
431 @Override
432 public int getInterfaceVersion() {
433 return this.VERSION;
434 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900435
436 @Override
437 public String getInterfaceHash() {
438 return this.HASH;
439 }
markchien74a4fa92019-09-09 20:50:49 +0800440 }
441
442 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
443 private final int mStartIndex;
444
445 private DhcpServerCallbacksImpl(int startIndex) {
446 mStartIndex = startIndex;
447 }
448
449 @Override
450 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
451 getHandler().post(() -> {
452 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
453 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800454 // This start request is obsolete. Explicitly stop the DHCP server to shut
455 // down its thread. When the |server| binder token goes out of scope, the
456 // garbage collector will finalize it, which causes the network stack process
457 // garbage collector to collect the server itself.
458 try {
459 server.stop(null);
460 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800461 return;
462 }
463
464 if (statusCode != STATUS_SUCCESS) {
465 mLog.e("Error obtaining DHCP server: " + statusCode);
466 handleError();
467 return;
468 }
469
470 mDhcpServer = server;
471 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900472 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800473 @Override
474 public void callback(int startStatusCode) {
475 if (startStatusCode != STATUS_SUCCESS) {
476 mLog.e("Error starting DHCP server: " + startStatusCode);
477 handleError();
478 }
479 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900480 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800481 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800482 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800483 }
484 });
485 }
486
487 private void handleError() {
Mark74461fc2022-12-14 08:49:40 +0000488 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800489 transitionTo(mInitialState);
490 }
491 }
492
Xiao Ma4455d6b2020-04-09 10:13:44 +0900493 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900494 @Override
495 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
496 final ArrayList<TetheredClient> leases = new ArrayList<>();
497 for (DhcpLeaseParcelable lease : leaseParcelables) {
498 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900499 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
500 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
501 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900502
503 final MacAddress macAddress;
504 try {
505 macAddress = MacAddress.fromBytes(lease.hwAddr);
506 } catch (IllegalArgumentException e) {
507 Log.wtf(TAG, "Invalid address received from DhcpServer: "
508 + Arrays.toString(lease.hwAddr));
509 return;
510 }
511
512 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900513 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900514 leases.add(new TetheredClient(
515 macAddress,
516 Collections.singletonList(addressInfo),
517 mInterfaceType));
518 }
519
520 getHandler().post(() -> {
521 mDhcpLeases = leases;
522 mCallback.dhcpLeasesChanged();
523 });
524 }
525
526 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900527 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
528 Objects.requireNonNull(currentPrefix);
529 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900530 }
531
532 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900533 public int getInterfaceVersion() {
534 return this.VERSION;
535 }
536
537 @Override
538 public String getInterfaceHash() throws RemoteException {
539 return this.HASH;
540 }
541 }
542
Xiao Ma4455d6b2020-04-09 10:13:44 +0900543 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
544 Objects.requireNonNull(ipv4Address);
545 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
546 }
547
548 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
549 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
550 @Nullable Inet4Address clientAddr) {
551 final boolean changePrefixOnDecline =
552 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
markchienfb65dfe2022-02-25 23:14:58 +0800553 final int subnetPrefixLength = mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
554 ? mP2pLeasesSubnetPrefixLength : 0 /* default value */;
555
Xiao Ma4455d6b2020-04-09 10:13:44 +0900556 return new DhcpServingParamsParcelExt()
557 .setDefaultRouters(defaultRouter)
558 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
559 .setDnsServers(dnsServer)
560 .setServerAddr(serverAddr)
561 .setMetered(true)
562 .setSingleClientAddr(clientAddr)
markchienfb65dfe2022-02-25 23:14:58 +0800563 .setChangePrefixOnDecline(changePrefixOnDecline)
564 .setLeasesSubnetPrefixLength(subnetPrefixLength);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900565 // TODO: also advertise link MTU
566 }
567
markchien245352e2020-02-27 20:27:18 +0800568 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800569 if (mUsingLegacyDhcp) {
570 return true;
571 }
markchien245352e2020-02-27 20:27:18 +0800572
573 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800574 final Inet4Address clientAddr = clientLinkAddr == null ? null :
575 (Inet4Address) clientLinkAddr.getAddress();
576
Xiao Ma4455d6b2020-04-09 10:13:44 +0900577 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
578 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800579 mDhcpServerStartIndex++;
580 mDeps.makeDhcpServer(
581 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
582 return true;
583 }
584
585 private void stopDhcp() {
586 // Make all previous start requests obsolete so servers are not started later
587 mDhcpServerStartIndex++;
588
589 if (mDhcpServer != null) {
590 try {
591 mDhcpServer.stop(new OnHandlerStatusCallback() {
592 @Override
593 public void callback(int statusCode) {
594 if (statusCode != STATUS_SUCCESS) {
595 mLog.e("Error stopping DHCP server: " + statusCode);
Mark74461fc2022-12-14 08:49:40 +0000596 mLastError = TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800597 // Not much more we can do here
598 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900599 mDhcpLeases.clear();
600 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800601 }
602 });
603 mDhcpServer = null;
604 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900605 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800606 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800607 }
608 }
609 }
610
markchien245352e2020-02-27 20:27:18 +0800611 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
612 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800613 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800614 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800615 } else {
616 stopDhcp();
617 return true;
618 }
619 }
620
621 private void stopIPv4() {
Mark49649c92023-03-15 06:45:04 +0000622 configureIPv4(false /* enabled */, CONNECTIVITY_SCOPE_GLOBAL /* not used */);
markchien74a4fa92019-09-09 20:50:49 +0800623 // NOTE: All of configureIPv4() will be refactored out of existence
624 // into calls to InterfaceController, shared with startIPv4().
625 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800626 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800627 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800628 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800629 mStaticIpv4ServerAddr = null;
630 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800631 }
632
Mark49649c92023-03-15 06:45:04 +0000633 private boolean configureIPv4(boolean enabled, int scope) {
markchien74a4fa92019-09-09 20:50:49 +0800634 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
635
markchienc9daba32020-02-12 00:19:21 +0800636 if (enabled) {
Mark49649c92023-03-15 06:45:04 +0000637 mIpv4Address = requestIpv4Address(scope, true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800638 }
639
640 if (mIpv4Address == null) {
641 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800642 return false;
markchien74a4fa92019-09-09 20:50:49 +0800643 }
644
markchien69681d62021-11-15 23:58:05 +0800645 if (shouldNotConfigureBluetoothInterface()) {
646 // Interface was already configured elsewhere, only start DHCP.
markchienc9daba32020-02-12 00:19:21 +0800647 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
648 }
649
650 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
651
markchien12c5bb82020-01-07 14:43:17 +0800652 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800653 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900654 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200655 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
656 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900657 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800658 // It is unclear whether the Bluetooth or USB stacks will manage their own
659 // state.
660 setIfaceUp = null;
661 } else {
662 setIfaceUp = enabled;
663 }
664 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
665 mLog.e("Error configuring interface");
666 if (!enabled) stopDhcp();
667 return false;
668 }
markchien74a4fa92019-09-09 20:50:49 +0800669
markchien74a4fa92019-09-09 20:50:49 +0800670 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800671 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900672 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800673 } else {
markchien12c5bb82020-01-07 14:43:17 +0800674 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900675 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800676 }
markchien245352e2020-02-27 20:27:18 +0800677 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800678 }
679
markchien69681d62021-11-15 23:58:05 +0800680 private boolean shouldNotConfigureBluetoothInterface() {
681 // Before T, bluetooth tethering configures the interface elsewhere.
682 return (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) && !SdkLevel.isAtLeastT();
683 }
684
Mark49649c92023-03-15 06:45:04 +0000685 private LinkAddress requestIpv4Address(final int scope, final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800686 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800687
markchien69681d62021-11-15 23:58:05 +0800688 if (shouldNotConfigureBluetoothInterface()) return new LinkAddress(BLUETOOTH_IFACE_ADDR);
markchienc9daba32020-02-12 00:19:21 +0800689
Mark49649c92023-03-15 06:45:04 +0000690 return mPrivateAddressCoordinator.requestDownstreamAddress(this, scope, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900691 }
692
markchien74a4fa92019-09-09 20:50:49 +0800693 private boolean startIPv6() {
694 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
695 if (mInterfaceParams == null) {
696 mLog.e("Failed to find InterfaceParams");
697 stopIPv6();
698 return false;
699 }
700
701 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
702 if (!mRaDaemon.start()) {
703 stopIPv6();
704 return false;
705 }
706
markchien932df542021-08-12 13:56:43 +0800707 if (SdkLevel.isAtLeastS()) {
Tyler Wear90e40632020-03-13 11:38:38 -0700708 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
709 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
710 }
711
markchien74a4fa92019-09-09 20:50:49 +0800712 return true;
713 }
714
715 private void stopIPv6() {
716 mInterfaceParams = null;
717 setRaParams(null);
718
719 if (mRaDaemon != null) {
720 mRaDaemon.stop();
721 mRaDaemon = null;
722 }
Tyler Wear90e40632020-03-13 11:38:38 -0700723
724 if (mDadProxy != null) {
725 mDadProxy.stop();
726 mDadProxy = null;
727 }
markchien74a4fa92019-09-09 20:50:49 +0800728 }
729
730 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
731 // LinkProperties. These have extraneous data filtered out and only the
732 // necessary prefixes included (per its prefix distribution policy).
733 //
734 // TODO: Evaluate using a data structure than is more directly suited to
735 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800736 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800737 if (mRaDaemon == null) return;
738
739 // Avoid unnecessary work on spurious updates.
740 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
741 return;
742 }
743
744 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700745 String upstreamIface = null;
746 InterfaceParams upstreamIfaceParams = null;
747 int upstreamIfIndex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800748
749 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700750 upstreamIface = v6only.getInterfaceName();
751 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
752 if (upstreamIfaceParams != null) {
753 upstreamIfIndex = upstreamIfaceParams.index;
754 }
markchien74a4fa92019-09-09 20:50:49 +0800755 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700756 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800757 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
758
markchiend63c4f32020-05-21 17:38:28 +0800759 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800760
761 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
762 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
763
764 final IpPrefix prefix = new IpPrefix(
765 linkAddr.getAddress(), linkAddr.getPrefixLength());
766 params.prefixes.add(prefix);
767
768 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
769 if (dnsServer != null) {
770 params.dnses.add(dnsServer);
771 }
772 }
773 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900774
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900775 // Add upstream index to name mapping. See the comment of the interface mapping update in
776 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
777 // timing issue. It prevents that the IPv6 capability is updated later than
778 // CMD_TETHER_CONNECTION_CHANGED.
779 mBpfCoordinator.addUpstreamNameToLookupTable(upstreamIfIndex, upstreamIface);
780
markchien74a4fa92019-09-09 20:50:49 +0800781 // If v6only is null, we pass in null to setRaParams(), which handles
782 // deprecation of any existing RA data.
markchien74a4fa92019-09-09 20:50:49 +0800783 setRaParams(params);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900784
KH Shi68770342023-08-17 14:34:31 +0000785 // Not support BPF on virtual upstream interface
786 final boolean upstreamSupportsBpf = upstreamIface != null && !isVcnInterface(upstreamIface);
787 updateIpv6ForwardingRules(
788 mLastIPv6UpstreamIfindex, upstreamIfIndex, upstreamSupportsBpf, null);
789 mLastIPv6LinkProperties = v6only;
Tyler Wear90e40632020-03-13 11:38:38 -0700790 mLastIPv6UpstreamIfindex = upstreamIfIndex;
KH Shi68770342023-08-17 14:34:31 +0000791 mUpstreamSupportsBpf = upstreamSupportsBpf;
Tyler Wear90e40632020-03-13 11:38:38 -0700792 if (mDadProxy != null) {
793 mDadProxy.setUpstreamIface(upstreamIfaceParams);
794 }
markchien74a4fa92019-09-09 20:50:49 +0800795 }
796
Xiao Ma4455d6b2020-04-09 10:13:44 +0900797 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900798 final int removalFailures = NetdUtils.removeRoutesFromLocalNetwork(
Xiao Ma4455d6b2020-04-09 10:13:44 +0900799 mNetd, toBeRemoved);
800 if (removalFailures > 0) {
801 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
802 removalFailures));
803 }
804
805 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
806 }
807
808 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
809 try {
810 // It's safe to call networkAddInterface() even if
811 // the interface is already in the local_network.
812 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
813 try {
814 // Add routes from local network. Note that adding routes that
815 // already exist does not cause an error (EEXIST is silently ignored).
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900816 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900817 } catch (IllegalStateException e) {
818 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
819 return;
820 }
821 } catch (ServiceSpecificException | RemoteException e) {
822 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
823 return;
824 }
825
826 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
827 }
828
markchien74a4fa92019-09-09 20:50:49 +0800829 private void configureLocalIPv6Routes(
830 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
831 // [1] Remove the routes that are deprecated.
832 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900833 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800834 }
835
836 // [2] Add only the routes that have not previously been added.
837 if (newPrefixes != null && !newPrefixes.isEmpty()) {
838 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
839 if (mLastRaParams != null) {
840 addedPrefixes.removeAll(mLastRaParams.prefixes);
841 }
842
843 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900844 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800845 }
846 }
847 }
848
849 private void configureLocalIPv6Dns(
850 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
851 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
852 if (mNetd == null) {
853 if (newDnses != null) newDnses.clear();
854 mLog.e("No netd service instance available; not setting local IPv6 addresses");
855 return;
856 }
857
858 // [1] Remove deprecated local DNS IP addresses.
859 if (!deprecatedDnses.isEmpty()) {
860 for (Inet6Address dns : deprecatedDnses) {
861 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
862 mLog.e("Failed to remove local dns IP " + dns);
863 }
864
865 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
866 }
867 }
868
869 // [2] Add only the local DNS IP addresses that have not previously been added.
870 if (newDnses != null && !newDnses.isEmpty()) {
871 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
872 if (mLastRaParams != null) {
873 addedDnses.removeAll(mLastRaParams.dnses);
874 }
875
876 for (Inet6Address dns : addedDnses) {
877 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
878 mLog.e("Failed to add local dns IP " + dns);
879 newDnses.remove(dns);
880 }
881
882 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
883 }
884 }
885
886 try {
887 mNetd.tetherApplyDnsInterfaces();
888 } catch (ServiceSpecificException | RemoteException e) {
889 mLog.e("Failed to update local DNS caching server");
890 if (newDnses != null) newDnses.clear();
891 }
892 }
893
KH Shi59ad35e2023-08-15 07:13:00 +0000894 private void addIpv6DownstreamRule(Ipv6DownstreamRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800895 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
896 // offload is disabled. Add this check just in case.
897 // TODO: Perhaps remove this protection check.
898 if (!mUsingBpfOffload) return;
899
KH Shi59ad35e2023-08-15 07:13:00 +0000900 mBpfCoordinator.addIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900901 }
902
KH Shi59ad35e2023-08-15 07:13:00 +0000903 private void removeIpv6DownstreamRule(Ipv6DownstreamRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800904 // TODO: Perhaps remove this protection check.
KH Shi59ad35e2023-08-15 07:13:00 +0000905 // See the related comment in #addIpv6DownstreamRule.
Hungming Chen3d8fa882020-04-12 14:27:18 +0800906 if (!mUsingBpfOffload) return;
907
KH Shi59ad35e2023-08-15 07:13:00 +0000908 mBpfCoordinator.removeIpv6DownstreamRule(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900909 }
910
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900911 private void clearIpv6ForwardingRules() {
Hungming Chen269c0882020-05-06 14:57:35 +0800912 if (!mUsingBpfOffload) return;
913
914 mBpfCoordinator.tetherOffloadRuleClear(this);
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900915 }
916
Hungming Chen269c0882020-05-06 14:57:35 +0800917 private void updateIpv6ForwardingRule(int newIfindex) {
918 // TODO: Perhaps remove this protection check.
KH Shi59ad35e2023-08-15 07:13:00 +0000919 // See the related comment in #addIpv6DownstreamRule.
Hungming Chen269c0882020-05-06 14:57:35 +0800920 if (!mUsingBpfOffload) return;
921
922 mBpfCoordinator.tetherOffloadRuleUpdate(this, newIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900923 }
924
925 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
926 // changes or if a neighbor event is received.
927 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
KH Shi68770342023-08-17 14:34:31 +0000928 boolean upstreamSupportsBpf, NeighborEvent e) {
929 // If no longer have an upstream or upstream not supports BPF, clear forwarding rules and do
markchien7dc1b4d2021-07-13 17:12:56 +0800930 // nothing else.
931 // TODO: Rather than always clear rules, ensure whether ipv6 ever enable first.
KH Shi68770342023-08-17 14:34:31 +0000932 if (upstreamIfindex == 0 || !upstreamSupportsBpf) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900933 clearIpv6ForwardingRules();
934 return;
935 }
936
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900937 // If the upstream interface has changed, remove all rules and re-add them with the new
938 // upstream interface.
939 if (prevUpstreamIfindex != upstreamIfindex) {
Hungming Chen269c0882020-05-06 14:57:35 +0800940 updateIpv6ForwardingRule(upstreamIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900941 }
942
943 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900944 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900945 if (e == null) return;
946 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
947 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
948 return;
949 }
950
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900951 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
KH Shi59ad35e2023-08-15 07:13:00 +0000952 // Do this here instead of in the Ipv6DownstreamRule constructor to ensure that we
953 // never add rules with a null MAC, only delete them.
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900954 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
KH Shi59ad35e2023-08-15 07:13:00 +0000955 Ipv6DownstreamRule rule = new Ipv6DownstreamRule(upstreamIfindex, mInterfaceParams.index,
956 (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900957 if (e.isValid()) {
KH Shi59ad35e2023-08-15 07:13:00 +0000958 addIpv6DownstreamRule(rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900959 } else {
KH Shi59ad35e2023-08-15 07:13:00 +0000960 removeIpv6DownstreamRule(rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900961 }
962 }
963
Hungming Chend71c06e2020-12-21 19:39:49 +0800964 // TODO: consider moving into BpfCoordinator.
965 private void updateClientInfoIpv4(NeighborEvent e) {
966 // TODO: Perhaps remove this protection check.
KH Shi59ad35e2023-08-15 07:13:00 +0000967 // See the related comment in #addIpv6DownstreamRule.
Hungming Chend71c06e2020-12-21 19:39:49 +0800968 if (!mUsingBpfOffload) return;
969
970 if (e == null) return;
971 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
972 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
973 return;
974 }
975
976 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
977 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
978 // IpServer never add clients with a null MAC, only delete them.
979 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
980 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
981 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
982 if (e.isValid()) {
983 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
984 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +0800985 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
986 }
987 }
988
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900989 private void handleNeighborEvent(NeighborEvent e) {
990 if (mInterfaceParams != null
991 && mInterfaceParams.index == e.ifindex
992 && mInterfaceParams.hasMacAddress) {
KH Shi68770342023-08-17 14:34:31 +0000993 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex,
994 mUpstreamSupportsBpf, e);
Hungming Chend71c06e2020-12-21 19:39:49 +0800995 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900996 }
997 }
998
markchiend63c4f32020-05-21 17:38:28 +0800999 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001000 try {
1001 int upstreamHopLimit = Integer.parseUnsignedInt(
1002 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001003 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001004 // Cap the hop limit to 255.
1005 return (byte) Integer.min(upstreamHopLimit, 255);
1006 } catch (Exception e) {
1007 mLog.e("Failed to find upstream interface hop limit", e);
1008 }
1009 return RaParams.DEFAULT_HOPLIMIT;
1010 }
1011
1012 private void setRaParams(RaParams newParams) {
1013 if (mRaDaemon != null) {
1014 final RaParams deprecatedParams =
1015 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1016
1017 configureLocalIPv6Routes(deprecatedParams.prefixes,
1018 (newParams != null) ? newParams.prefixes : null);
1019
1020 configureLocalIPv6Dns(deprecatedParams.dnses,
1021 (newParams != null) ? newParams.dnses : null);
1022
1023 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1024 }
1025
1026 mLastRaParams = newParams;
1027 }
1028
markchien21021ef2021-06-01 10:58:04 +08001029 private void maybeLogMessage(State state, int what) {
1030 switch (what) {
1031 // Suppress some CMD_* to avoid log flooding.
1032 case CMD_IPV6_TETHER_UPDATE:
1033 case CMD_NEIGHBOR_EVENT:
1034 break;
1035 default:
1036 mLog.log(state.getName() + " got "
1037 + sMagicDecoderRing.get(what, Integer.toString(what)));
1038 }
markchien74a4fa92019-09-09 20:50:49 +08001039 }
1040
1041 private void sendInterfaceState(int newInterfaceState) {
1042 mServingMode = newInterfaceState;
1043 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1044 sendLinkProperties();
1045 }
1046
1047 private void sendLinkProperties() {
1048 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1049 }
1050
1051 private void resetLinkProperties() {
1052 mLinkProperties.clear();
1053 mLinkProperties.setInterfaceName(mIfaceName);
1054 }
1055
markchienf053e4b2020-03-16 21:49:48 +08001056 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001057 // Ignore static address configuration if they are invalid or null. In theory, static
1058 // addresses should not be invalid here because TetheringManager do not allow caller to
1059 // specify invalid static address configuration.
1060 if (request == null || request.localIPv4Address == null
1061 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1062 request.localIPv4Address, request.staticClientAddress)) {
1063 return;
1064 }
markchienf053e4b2020-03-16 21:49:48 +08001065
1066 mStaticIpv4ServerAddr = request.localIPv4Address;
1067 mStaticIpv4ClientAddr = request.staticClientAddress;
1068 }
1069
markchien74a4fa92019-09-09 20:50:49 +08001070 class InitialState extends State {
1071 @Override
1072 public void enter() {
1073 sendInterfaceState(STATE_AVAILABLE);
1074 }
1075
1076 @Override
1077 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001078 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001079 switch (message.what) {
1080 case CMD_TETHER_REQUESTED:
Mark74461fc2022-12-14 08:49:40 +00001081 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001082 switch (message.arg1) {
1083 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001084 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001085 transitionTo(mLocalHotspotState);
1086 break;
1087 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001088 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001089 transitionTo(mTetheredState);
1090 break;
1091 default:
1092 mLog.e("Invalid tethering interface serving state specified.");
1093 }
1094 break;
1095 case CMD_INTERFACE_DOWN:
1096 transitionTo(mUnavailableState);
1097 break;
markchien74a4fa92019-09-09 20:50:49 +08001098 default:
1099 return NOT_HANDLED;
1100 }
1101 return HANDLED;
1102 }
1103 }
1104
Hungming Chen46c30b12020-10-15 17:25:36 +08001105 private void startConntrackMonitoring() {
1106 mBpfCoordinator.startMonitoring(this);
1107 }
1108
1109 private void stopConntrackMonitoring() {
1110 mBpfCoordinator.stopMonitoring(this);
1111 }
1112
Mark3ec851e2023-05-19 08:50:38 +00001113 abstract class BaseServingState extends State {
1114 private final int mDesiredInterfaceState;
1115
1116 BaseServingState(int interfaceState) {
1117 mDesiredInterfaceState = interfaceState;
1118 }
1119
markchien74a4fa92019-09-09 20:50:49 +08001120 @Override
1121 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001122 startConntrackMonitoring();
1123
Mark3ec851e2023-05-19 08:50:38 +00001124 startServingInterface();
1125
1126 if (mLastError != TETHER_ERROR_NO_ERROR) {
1127 transitionTo(mInitialState);
1128 }
1129
1130 if (DBG) Log.d(TAG, getStateString(mDesiredInterfaceState) + " serve " + mIfaceName);
1131 sendInterfaceState(mDesiredInterfaceState);
1132 }
1133
Mark49649c92023-03-15 06:45:04 +00001134 private int getScope() {
1135 if (mDesiredInterfaceState == STATE_TETHERED) {
1136 return CONNECTIVITY_SCOPE_GLOBAL;
1137 }
1138
1139 return CONNECTIVITY_SCOPE_LOCAL;
1140 }
1141
Mark3ec851e2023-05-19 08:50:38 +00001142 private void startServingInterface() {
Mark49649c92023-03-15 06:45:04 +00001143 if (!startIPv4(getScope())) {
Mark74461fc2022-12-14 08:49:40 +00001144 mLastError = TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001145 return;
1146 }
1147
1148 try {
markchienc9daba32020-02-12 00:19:21 +08001149 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001150 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001151 mLog.e("Error Tethering", e);
Mark74461fc2022-12-14 08:49:40 +00001152 mLastError = TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001153 return;
1154 }
1155
1156 if (!startIPv6()) {
1157 mLog.e("Failed to startIPv6");
1158 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1159 return;
1160 }
1161 }
1162
1163 @Override
1164 public void exit() {
1165 // Note that at this point, we're leaving the tethered state. We can fail any
1166 // of these operations, but it doesn't really change that we have to try them
1167 // all in sequence.
1168 stopIPv6();
1169
1170 try {
markchien12c5bb82020-01-07 14:43:17 +08001171 NetdUtils.untetherInterface(mNetd, mIfaceName);
1172 } catch (RemoteException | ServiceSpecificException e) {
Mark74461fc2022-12-14 08:49:40 +00001173 mLastError = TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001174 mLog.e("Failed to untether interface: " + e);
1175 }
1176
1177 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001178 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001179
1180 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001181
1182 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1183 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001184 }
1185
1186 @Override
1187 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001188 switch (message.what) {
1189 case CMD_TETHER_UNREQUESTED:
1190 transitionTo(mInitialState);
1191 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1192 break;
1193 case CMD_INTERFACE_DOWN:
1194 transitionTo(mUnavailableState);
1195 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1196 break;
1197 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001198 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001199 sendLinkProperties();
1200 break;
1201 case CMD_IP_FORWARDING_ENABLE_ERROR:
1202 case CMD_IP_FORWARDING_DISABLE_ERROR:
1203 case CMD_START_TETHERING_ERROR:
1204 case CMD_STOP_TETHERING_ERROR:
1205 case CMD_SET_DNS_FORWARDERS_ERROR:
Mark74461fc2022-12-14 08:49:40 +00001206 mLastError = TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001207 transitionTo(mInitialState);
1208 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001209 case CMD_NEW_PREFIX_REQUEST:
1210 handleNewPrefixRequest((IpPrefix) message.obj);
1211 break;
markchienc9daba32020-02-12 00:19:21 +08001212 case CMD_NOTIFY_PREFIX_CONFLICT:
1213 mLog.i("restart tethering: " + mInterfaceType);
1214 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1215 transitionTo(mWaitingForRestartState);
1216 break;
markchien74a4fa92019-09-09 20:50:49 +08001217 default:
1218 return false;
1219 }
1220 return true;
1221 }
Mark3ec851e2023-05-19 08:50:38 +00001222
1223 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
1224 if (!currentPrefix.contains(mIpv4Address.getAddress())
1225 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
1226 Log.e(TAG, "Invalid prefix: " + currentPrefix);
1227 return;
1228 }
1229
1230 final LinkAddress deprecatedLinkAddress = mIpv4Address;
Mark49649c92023-03-15 06:45:04 +00001231 mIpv4Address = requestIpv4Address(getScope(), false);
Mark3ec851e2023-05-19 08:50:38 +00001232 if (mIpv4Address == null) {
1233 mLog.e("Fail to request a new downstream prefix");
1234 return;
1235 }
1236 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
1237
1238 // Add new IPv4 address on the interface.
1239 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1240 mLog.e("Failed to add new IP " + srvAddr);
1241 return;
1242 }
1243
1244 // Remove deprecated routes from local network.
1245 removeRoutesFromLocalNetwork(
1246 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1247 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1248
1249 // Add new routes to local network.
1250 addRoutesToLocalNetwork(
1251 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1252 mLinkProperties.addLinkAddress(mIpv4Address);
1253
1254 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1255 // listen on the interface configured with new IPv4 address, that results DNS validation
1256 // failure of downstream client even if appropriate routes have been configured.
1257 try {
1258 mNetd.tetherApplyDnsInterfaces();
1259 } catch (ServiceSpecificException | RemoteException e) {
1260 mLog.e("Failed to update local DNS caching server");
1261 return;
1262 }
1263 sendLinkProperties();
1264
1265 // Notify DHCP server that new prefix/route has been applied on IpServer.
1266 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1267 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1268 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1269 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1270 try {
1271 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1272 @Override
1273 public void callback(int statusCode) {
1274 if (statusCode != STATUS_SUCCESS) {
1275 mLog.e("Error updating DHCP serving params: " + statusCode);
1276 }
1277 }
1278 });
1279 } catch (RemoteException e) {
1280 mLog.e("Error updating DHCP serving params", e);
1281 }
1282 }
markchien74a4fa92019-09-09 20:50:49 +08001283 }
1284
1285 // Handling errors in BaseServingState.enter() by transitioning is
1286 // problematic because transitioning during a multi-state jump yields
1287 // a Log.wtf(). Ultimately, there should be only one ServingState,
1288 // and forwarding and NAT rules should be handled by a coordinating
1289 // functional element outside of IpServer.
1290 class LocalHotspotState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001291 LocalHotspotState() {
1292 super(STATE_LOCAL_ONLY);
markchien74a4fa92019-09-09 20:50:49 +08001293 }
1294
1295 @Override
1296 public boolean processMessage(Message message) {
1297 if (super.processMessage(message)) return true;
1298
markchien21021ef2021-06-01 10:58:04 +08001299 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001300 switch (message.what) {
1301 case CMD_TETHER_REQUESTED:
1302 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1303 break;
1304 case CMD_TETHER_CONNECTION_CHANGED:
1305 // Ignored in local hotspot state.
1306 break;
1307 default:
1308 return false;
1309 }
1310 return true;
1311 }
1312 }
1313
1314 // Handling errors in BaseServingState.enter() by transitioning is
1315 // problematic because transitioning during a multi-state jump yields
1316 // a Log.wtf(). Ultimately, there should be only one ServingState,
1317 // and forwarding and NAT rules should be handled by a coordinating
1318 // functional element outside of IpServer.
1319 class TetheredState extends BaseServingState {
Mark3ec851e2023-05-19 08:50:38 +00001320 TetheredState() {
1321 super(STATE_TETHERED);
markchien74a4fa92019-09-09 20:50:49 +08001322 }
1323
1324 @Override
1325 public void exit() {
1326 cleanupUpstream();
1327 super.exit();
1328 }
1329
Hungming Chena6e78692021-02-08 17:15:35 +08001330 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1331 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1332 // and behaviour. While upstream is switching from offload supported interface to
1333 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1334 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1335 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1336 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1337 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1338 // in the state machine. Once there is any case out whish is not covered by previous cases,
1339 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001340 private void cleanupUpstream() {
1341 if (mUpstreamIfaceSet == null) return;
1342
1343 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1344 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001345 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001346 }
1347
1348 private void cleanupUpstreamInterface(String upstreamIface) {
1349 // Note that we don't care about errors here.
1350 // Sometimes interfaces are gone before we get
1351 // to remove their rules, which generates errors.
1352 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001353 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001354 try {
markchien12c5bb82020-01-07 14:43:17 +08001355 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1356 } catch (RemoteException | ServiceSpecificException e) {
1357 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001358 }
1359 try {
markchien12c5bb82020-01-07 14:43:17 +08001360 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1361 } catch (RemoteException | ServiceSpecificException e) {
1362 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001363 }
1364 }
1365
1366 @Override
1367 public boolean processMessage(Message message) {
1368 if (super.processMessage(message)) return true;
1369
markchien21021ef2021-06-01 10:58:04 +08001370 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001371 switch (message.what) {
1372 case CMD_TETHER_REQUESTED:
1373 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1374 break;
1375 case CMD_TETHER_CONNECTION_CHANGED:
1376 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1377 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1378 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1379 break;
1380 }
1381
1382 if (newUpstreamIfaceSet == null) {
1383 cleanupUpstream();
1384 break;
1385 }
1386
1387 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1388 cleanupUpstreamInterface(removed);
1389 }
1390
1391 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1392 // This makes the call to cleanupUpstream() in the error
1393 // path for any interface neatly cleanup all the interfaces.
1394 mUpstreamIfaceSet = newUpstreamIfaceSet;
1395
1396 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001397 // Add upstream index to name mapping for the tether stats usage in the
1398 // coordinator. Although this mapping could be added by both class
1399 // Tethering and IpServer, adding mapping from IpServer guarantees that
1400 // the mapping is added before adding forwarding rules. That is because
1401 // there are different state machines in both classes. It is hard to
1402 // guarantee the link property update order between multiple state machines.
1403 // Note that both IPv4 and IPv6 interface may be added because
1404 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1405 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1406 // capability may be updated later. In that case, IPv6 interface mapping is
1407 // updated in updateUpstreamIPv6LinkProperties.
1408 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1409 final InterfaceParams upstreamIfaceParams =
1410 mDeps.getInterfaceParams(ifname);
1411 if (upstreamIfaceParams != null) {
1412 mBpfCoordinator.addUpstreamNameToLookupTable(
1413 upstreamIfaceParams.index, ifname);
1414 }
1415 }
1416
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001417 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001418 try {
markchien12c5bb82020-01-07 14:43:17 +08001419 mNetd.tetherAddForward(mIfaceName, ifname);
1420 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1421 } catch (RemoteException | ServiceSpecificException e) {
1422 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001423 cleanupUpstream();
Mark74461fc2022-12-14 08:49:40 +00001424 mLastError = TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001425 transitionTo(mInitialState);
1426 return true;
1427 }
1428 }
1429 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001430 case CMD_NEIGHBOR_EVENT:
1431 handleNeighborEvent((NeighborEvent) message.obj);
1432 break;
markchien74a4fa92019-09-09 20:50:49 +08001433 default:
1434 return false;
1435 }
1436 return true;
1437 }
1438
1439 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1440 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1441 if (mUpstreamIfaceSet != null && newIfaces != null) {
1442 return mUpstreamIfaceSet.equals(newIfaces);
1443 }
1444 return false;
1445 }
1446
1447 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1448 if (mUpstreamIfaceSet == null) return new HashSet<>();
1449
1450 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1451 removed.removeAll(newIfaces.ifnames);
1452 return removed;
1453 }
1454
1455 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1456 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1457 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1458 return added;
1459 }
1460 }
1461
1462 /**
1463 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001464 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001465 * specific state machine from its list of possible recipients of
1466 * tethering requests. The state machine itself will hang around until
1467 * the garbage collector finds it.
1468 */
1469 class UnavailableState extends State {
1470 @Override
1471 public void enter() {
h.zhangd244bd02020-06-14 14:46:54 +08001472 mIpNeighborMonitor.stop();
Mark74461fc2022-12-14 08:49:40 +00001473 mLastError = TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001474 sendInterfaceState(STATE_UNAVAILABLE);
1475 }
1476 }
1477
markchienc9daba32020-02-12 00:19:21 +08001478 class WaitingForRestartState extends State {
1479 @Override
1480 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001481 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001482 switch (message.what) {
1483 case CMD_TETHER_UNREQUESTED:
1484 transitionTo(mInitialState);
1485 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1486 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1487 break;
1488 case CMD_INTERFACE_DOWN:
1489 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001490 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001491 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1492 break;
1493 default:
1494 return false;
1495 }
1496 return true;
1497 }
1498 }
1499
markchien74a4fa92019-09-09 20:50:49 +08001500 // Accumulate routes representing "prefixes to be assigned to the local
1501 // interface", for subsequent modification of local_network routing.
1502 private static ArrayList<RouteInfo> getLocalRoutesFor(
1503 String ifname, HashSet<IpPrefix> prefixes) {
1504 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1505 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001506 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001507 }
1508 return localRoutes;
1509 }
1510
1511 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1512 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1513 final byte[] dnsBytes = localPrefix.getRawAddress();
1514 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1515 try {
1516 return Inet6Address.getByAddress(null, dnsBytes, 0);
1517 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001518 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001519 return null;
1520 }
1521 }
1522
1523 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1524 final byte random = (byte) (new Random()).nextInt();
1525 for (int value : excluded) {
1526 if (random == value) return dflt;
1527 }
1528 return random;
1529 }
1530}