blob: 8cf13d36cace8495d50157f73f7cb79ec6eec5e6 [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;
markchien245352e2020-02-27 20:27:18 +080020import static android.net.TetheringManager.TetheringRequest.checkStaticAddressConfiguration;
markchien74a4fa92019-09-09 20:50:49 +080021import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
markchien74a4fa92019-09-09 20:50:49 +080022import static android.net.util.NetworkConstants.RFC7421_PREFIX_LENGTH;
23import static android.net.util.NetworkConstants.asByte;
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +090024import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080025
Chalard Jean78701642020-07-31 20:00:30 +090026import static com.android.net.module.util.Inet4AddressUtils.intToInet4AddressHTH;
markchien7dc1b4d2021-07-13 17:12:56 +080027import static com.android.networkstack.tethering.UpstreamNetworkState.isVcnInterface;
markchiend02f9af2021-11-04 11:26:03 +080028import static com.android.networkstack.tethering.util.PrefixUtils.asIpPrefix;
29import static com.android.networkstack.tethering.util.TetheringMessageBase.BASE_IPSERVER;
Chalard Jean78701642020-07-31 20:00:30 +090030
markchien74a4fa92019-09-09 20:50:49 +080031import android.net.INetd;
32import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080033import android.net.IpPrefix;
34import android.net.LinkAddress;
35import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090036import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080037import android.net.RouteInfo;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090038import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080039import android.net.TetheringManager;
markchienf053e4b2020-03-16 21:49:48 +080040import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090041import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080042import android.net.dhcp.DhcpServerCallbacks;
43import android.net.dhcp.DhcpServingParamsParcel;
44import android.net.dhcp.DhcpServingParamsParcelExt;
Xiao Ma49889dd2020-04-03 17:01:33 +090045import android.net.dhcp.IDhcpEventCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080046import android.net.dhcp.IDhcpServer;
47import android.net.ip.RouterAdvertisementDaemon.RaParams;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090048import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080049import android.os.Looper;
50import android.os.Message;
51import android.os.RemoteException;
52import android.os.ServiceSpecificException;
53import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080054import android.util.SparseArray;
55
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090056import androidx.annotation.NonNull;
Xiao Ma4455d6b2020-04-09 10:13:44 +090057import androidx.annotation.Nullable;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090058
markchien74a4fa92019-09-09 20:50:49 +080059import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080060import com.android.internal.util.State;
61import com.android.internal.util.StateMachine;
markchien932df542021-08-12 13:56:43 +080062import com.android.modules.utils.build.SdkLevel;
Patrick Rohr9f371f02022-03-04 15:14:27 +010063import com.android.net.module.util.InterfaceParams;
Chalard Jeanadcec9e2021-10-29 15:57:22 +090064import com.android.net.module.util.NetdUtils;
Patrick Rohrb873e252022-06-16 16:38:43 -070065import com.android.net.module.util.SharedLog;
Xiao Mac81c0662022-06-17 14:58:03 +090066import com.android.net.module.util.ip.InterfaceController;
67import com.android.net.module.util.ip.IpNeighborMonitor;
68import com.android.net.module.util.ip.IpNeighborMonitor.NeighborEvent;
Hungming Chen68f1c2a2020-03-12 21:24:01 +080069import com.android.networkstack.tethering.BpfCoordinator;
Hungming Chend71c06e2020-12-21 19:39:49 +080070import com.android.networkstack.tethering.BpfCoordinator.ClientInfo;
Hungming Chenb150b872020-05-23 22:54:49 +080071import com.android.networkstack.tethering.BpfCoordinator.Ipv6ForwardingRule;
markchienc9daba32020-02-12 00:19:21 +080072import com.android.networkstack.tethering.PrivateAddressCoordinator;
markchienb961d3d2022-02-26 00:39:06 +080073import com.android.networkstack.tethering.TetheringConfiguration;
Wayne Ma6cd440f2022-03-14 18:04:33 +080074import com.android.networkstack.tethering.metrics.TetheringMetrics;
markchiend02f9af2021-11-04 11:26:03 +080075import com.android.networkstack.tethering.util.InterfaceSet;
76import com.android.networkstack.tethering.util.PrefixUtils;
markchien74a4fa92019-09-09 20:50:49 +080077
78import java.net.Inet4Address;
79import java.net.Inet6Address;
markchien74a4fa92019-09-09 20:50:49 +080080import java.net.UnknownHostException;
81import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090082import java.util.Arrays;
83import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080084import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090085import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080086import java.util.Objects;
87import java.util.Random;
88import java.util.Set;
89
90/**
91 * Provides the interface to IP-layer serving functionality for a given network
92 * interface, e.g. for tethering or "local-only hotspot" mode.
93 *
94 * @hide
95 */
96public class IpServer extends StateMachine {
97 public static final int STATE_UNAVAILABLE = 0;
98 public static final int STATE_AVAILABLE = 1;
99 public static final int STATE_TETHERED = 2;
100 public static final int STATE_LOCAL_ONLY = 3;
101
102 /** Get string name of |state|.*/
103 public static String getStateString(int state) {
104 switch (state) {
105 case STATE_UNAVAILABLE: return "UNAVAILABLE";
106 case STATE_AVAILABLE: return "AVAILABLE";
107 case STATE_TETHERED: return "TETHERED";
108 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
109 }
110 return "UNKNOWN: " + state;
111 }
112
113 private static final byte DOUG_ADAMS = (byte) 42;
114
markchien74a4fa92019-09-09 20:50:49 +0800115 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800116 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800117
118 // TODO: have this configurable
119 private static final int DHCP_LEASE_TIME_SECS = 3600;
120
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900121 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
122
markchien74a4fa92019-09-09 20:50:49 +0800123 private static final String TAG = "IpServer";
124 private static final boolean DBG = false;
125 private static final boolean VDBG = false;
126 private static final Class[] sMessageClasses = {
127 IpServer.class
128 };
129 private static final SparseArray<String> sMagicDecoderRing =
130 MessageUtils.findMessageNames(sMessageClasses);
131
132 /** IpServer callback. */
133 public static class Callback {
134 /**
135 * Notify that |who| has changed its tethering state.
136 *
137 * @param who the calling instance of IpServer
138 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800139 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800140 */
markchien9d353822019-12-16 20:15:20 +0800141 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800142
143 /**
144 * Notify that |who| has new LinkProperties.
145 *
146 * @param who the calling instance of IpServer
147 * @param newLp the new LinkProperties to report
148 */
markchien9d353822019-12-16 20:15:20 +0800149 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900150
151 /**
152 * Notify that the DHCP leases changed in one of the IpServers.
153 */
154 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800155
156 /**
157 * Request Tethering change.
158 *
159 * @param tetheringType the downstream type of this IpServer.
160 * @param enabled enable or disable tethering.
161 */
162 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800163 }
164
165 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800166 public abstract static class Dependencies {
Tyler Wear90e40632020-03-13 11:38:38 -0700167 /**
168 * Create a DadProxy instance to be used by IpServer.
169 * To support multiple tethered interfaces concurrently DAD Proxy
170 * needs to be supported per IpServer instead of per upstream.
171 */
172 public DadProxy getDadProxy(Handler handler, InterfaceParams ifParams) {
173 return new DadProxy(handler, ifParams);
174 }
175
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900176 /** Create an IpNeighborMonitor to be used by this IpServer */
177 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
178 IpNeighborMonitor.NeighborEventConsumer consumer) {
179 return new IpNeighborMonitor(handler, log, consumer);
180 }
181
markchien74a4fa92019-09-09 20:50:49 +0800182 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
183 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
184 return new RouterAdvertisementDaemon(ifParams);
185 }
186
187 /** Get |ifName|'s interface information.*/
188 public InterfaceParams getInterfaceParams(String ifName) {
189 return InterfaceParams.getByName(ifName);
190 }
191
markchien9d353822019-12-16 20:15:20 +0800192 /** Create a DhcpServer instance to be used by IpServer. */
193 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
194 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800195 }
196
markchien74a4fa92019-09-09 20:50:49 +0800197 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800198 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800199 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800200 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800201 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800202 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800203 // notification from the {@link Tethering.TetherMainSM} that it had trouble enabling IP
204 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800205 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800206 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble disabling IP
207 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800208 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800209 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble starting
210 // tethering
markchien6cf0e552019-12-06 15:24:53 +0800211 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800212 // notification from the {@link Tethering.TetherMainSM} that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800213 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800214 // notification from the {@link Tethering.TetherMainSM} that it had trouble setting the DNS
215 // forwarders
markchien6cf0e552019-12-06 15:24:53 +0800216 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800217 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800218 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800219 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800220 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900221 // new neighbor cache entry on our interface
222 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900223 // request from DHCP server that it wants to have a new prefix
224 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800225 // request from PrivateAddressCoordinator to restart tethering.
226 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
markchien74a4fa92019-09-09 20:50:49 +0800227
228 private final State mInitialState;
229 private final State mLocalHotspotState;
230 private final State mTetheredState;
231 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800232 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800233
234 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800235 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800236 @NonNull
237 private final BpfCoordinator mBpfCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800238 private final Callback mCallback;
239 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800240 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800241
242 private final String mIfaceName;
243 private final int mInterfaceType;
244 private final LinkProperties mLinkProperties;
245 private final boolean mUsingLegacyDhcp;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800246 private final boolean mUsingBpfOffload;
markchienfb65dfe2022-02-25 23:14:58 +0800247 private final int mP2pLeasesSubnetPrefixLength;
markchien74a4fa92019-09-09 20:50:49 +0800248
249 private final Dependencies mDeps;
250
251 private int mLastError;
252 private int mServingMode;
253 private InterfaceSet mUpstreamIfaceSet; // may change over time
254 private InterfaceParams mInterfaceParams;
255 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
256 // properties are those selected by the IPv6TetheringCoordinator and relayed
257 // to us. By comparison, mLinkProperties contains the addresses and directly
258 // connected routes that have been formed from these properties iff. we have
259 // succeeded in configuring them and are able to announce them within Router
260 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
261 private LinkProperties mLastIPv6LinkProperties;
262 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700263 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800264
265 // To be accessed only on the handler thread
266 private int mDhcpServerStartIndex = 0;
267 private IDhcpServer mDhcpServer;
268 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800269
270 private LinkAddress mStaticIpv4ServerAddr;
271 private LinkAddress mStaticIpv4ClientAddr;
272
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900273 @NonNull
274 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800275
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900276 private int mLastIPv6UpstreamIfindex = 0;
277
278 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
279 public void accept(NeighborEvent e) {
280 sendMessage(CMD_NEIGHBOR_EVENT, e);
281 }
282 }
283
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900284 private final IpNeighborMonitor mIpNeighborMonitor;
285
markchienc9daba32020-02-12 00:19:21 +0800286 private LinkAddress mIpv4Address;
287
Wayne Ma6cd440f2022-03-14 18:04:33 +0800288 private final TetheringMetrics mTetheringMetrics;
289
Hungming Chen5bc3af92020-05-12 19:15:24 +0800290 // TODO: Add a dependency object to pass the data members or variables from the tethering
291 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800292 public IpServer(
293 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800294 INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
markchienb961d3d2022-02-26 00:39:06 +0800295 TetheringConfiguration config, PrivateAddressCoordinator addressCoordinator,
Wayne Ma6cd440f2022-03-14 18:04:33 +0800296 TetheringMetrics tetheringMetrics, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800297 super(ifaceName, looper);
298 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800299 mNetd = netd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800300 mBpfCoordinator = coordinator;
markchien74a4fa92019-09-09 20:50:49 +0800301 mCallback = callback;
302 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
303 mIfaceName = ifaceName;
304 mInterfaceType = interfaceType;
305 mLinkProperties = new LinkProperties();
markchienb961d3d2022-02-26 00:39:06 +0800306 mUsingLegacyDhcp = config.useLegacyDhcpServer();
307 mUsingBpfOffload = config.isBpfOffloadEnabled();
markchienfb65dfe2022-02-25 23:14:58 +0800308 mP2pLeasesSubnetPrefixLength = config.getP2pLeasesSubnetPrefixLength();
markchienc9daba32020-02-12 00:19:21 +0800309 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800310 mDeps = deps;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800311 mTetheringMetrics = tetheringMetrics;
markchien74a4fa92019-09-09 20:50:49 +0800312 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800313 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800314 mServingMode = STATE_AVAILABLE;
315
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900316 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
317 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800318
Hungming Chen5bc3af92020-05-12 19:15:24 +0800319 // IP neighbor monitor monitors the neighbor events for adding/removing offload
Hungming Chen3d8fa882020-04-12 14:27:18 +0800320 // forwarding rules per client. If BPF offload is not supported, don't start listening
Hungming Chen5bc3af92020-05-12 19:15:24 +0800321 // for neighbor events. See updateIpv6ForwardingRules, addIpv6ForwardingRule,
Hungming Chen3d8fa882020-04-12 14:27:18 +0800322 // removeIpv6ForwardingRule.
Hungming Chen5bc3af92020-05-12 19:15:24 +0800323 if (mUsingBpfOffload && !mIpNeighborMonitor.start()) {
324 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900325 }
326
markchien74a4fa92019-09-09 20:50:49 +0800327 mInitialState = new InitialState();
328 mLocalHotspotState = new LocalHotspotState();
329 mTetheredState = new TetheredState();
330 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800331 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800332 addState(mInitialState);
333 addState(mLocalHotspotState);
334 addState(mTetheredState);
markchienc9daba32020-02-12 00:19:21 +0800335 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800336 addState(mUnavailableState);
337
338 setInitialState(mInitialState);
339 }
340
341 /** Interface name which IpServer served.*/
342 public String interfaceName() {
343 return mIfaceName;
344 }
345
346 /**
markchien9b4d7572019-12-25 19:40:32 +0800347 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800348 */
349 public int interfaceType() {
350 return mInterfaceType;
351 }
352
353 /** Last error from this IpServer. */
354 public int lastError() {
355 return mLastError;
356 }
357
358 /** Serving mode is the current state of IpServer state machine. */
359 public int servingMode() {
360 return mServingMode;
361 }
362
363 /** The properties of the network link which IpServer is serving. */
364 public LinkProperties linkProperties() {
365 return new LinkProperties(mLinkProperties);
366 }
367
markchienc9daba32020-02-12 00:19:21 +0800368 /** The address which IpServer is using. */
369 public LinkAddress getAddress() {
370 return mIpv4Address;
371 }
372
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900373 /**
374 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
375 * thread.
376 */
377 public List<TetheredClient> getAllLeases() {
378 return Collections.unmodifiableList(mDhcpLeases);
379 }
380
Marka5424582022-12-01 13:46:32 +0000381 /** Enable this IpServer. IpServer state machine will be tethered or localHotspot state. */
382 public void enable(final int requestedState, final TetheringRequestParcel request) {
383 sendMessage(CMD_TETHER_REQUESTED, requestedState, 0, request);
384 }
385
markchien74a4fa92019-09-09 20:50:49 +0800386 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
387 public void stop() {
388 sendMessage(CMD_INTERFACE_DOWN);
389 }
390
391 /**
392 * Tethering is canceled. IpServer state machine will be available and wait for
393 * next tethering request.
394 */
395 public void unwanted() {
396 sendMessage(CMD_TETHER_UNREQUESTED);
397 }
398
399 /** Internals. */
400
401 private boolean startIPv4() {
402 return configureIPv4(true);
403 }
404
405 /**
406 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
407 * handler.
408 *
409 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
410 * with different implementations of the callback, to differentiate handling of success/error in
411 * each call.
412 */
413 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
414 @Override
415 public void onStatusAvailable(int statusCode) {
416 getHandler().post(() -> callback(statusCode));
417 }
418
419 public abstract void callback(int statusCode);
420
421 @Override
422 public int getInterfaceVersion() {
423 return this.VERSION;
424 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900425
426 @Override
427 public String getInterfaceHash() {
428 return this.HASH;
429 }
markchien74a4fa92019-09-09 20:50:49 +0800430 }
431
432 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
433 private final int mStartIndex;
434
435 private DhcpServerCallbacksImpl(int startIndex) {
436 mStartIndex = startIndex;
437 }
438
439 @Override
440 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
441 getHandler().post(() -> {
442 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
443 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800444 // This start request is obsolete. Explicitly stop the DHCP server to shut
445 // down its thread. When the |server| binder token goes out of scope, the
446 // garbage collector will finalize it, which causes the network stack process
447 // garbage collector to collect the server itself.
448 try {
449 server.stop(null);
450 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800451 return;
452 }
453
454 if (statusCode != STATUS_SUCCESS) {
455 mLog.e("Error obtaining DHCP server: " + statusCode);
456 handleError();
457 return;
458 }
459
460 mDhcpServer = server;
461 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900462 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800463 @Override
464 public void callback(int startStatusCode) {
465 if (startStatusCode != STATUS_SUCCESS) {
466 mLog.e("Error starting DHCP server: " + startStatusCode);
467 handleError();
468 }
469 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900470 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800471 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800472 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800473 }
474 });
475 }
476
477 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800478 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800479 transitionTo(mInitialState);
480 }
481 }
482
Xiao Ma4455d6b2020-04-09 10:13:44 +0900483 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900484 @Override
485 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
486 final ArrayList<TetheredClient> leases = new ArrayList<>();
487 for (DhcpLeaseParcelable lease : leaseParcelables) {
488 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900489 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
490 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
491 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900492
493 final MacAddress macAddress;
494 try {
495 macAddress = MacAddress.fromBytes(lease.hwAddr);
496 } catch (IllegalArgumentException e) {
497 Log.wtf(TAG, "Invalid address received from DhcpServer: "
498 + Arrays.toString(lease.hwAddr));
499 return;
500 }
501
502 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900503 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900504 leases.add(new TetheredClient(
505 macAddress,
506 Collections.singletonList(addressInfo),
507 mInterfaceType));
508 }
509
510 getHandler().post(() -> {
511 mDhcpLeases = leases;
512 mCallback.dhcpLeasesChanged();
513 });
514 }
515
516 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900517 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
518 Objects.requireNonNull(currentPrefix);
519 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900520 }
521
522 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900523 public int getInterfaceVersion() {
524 return this.VERSION;
525 }
526
527 @Override
528 public String getInterfaceHash() throws RemoteException {
529 return this.HASH;
530 }
531 }
532
Xiao Ma4455d6b2020-04-09 10:13:44 +0900533 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
534 Objects.requireNonNull(ipv4Address);
535 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
536 }
537
538 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
539 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
540 @Nullable Inet4Address clientAddr) {
541 final boolean changePrefixOnDecline =
542 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
markchienfb65dfe2022-02-25 23:14:58 +0800543 final int subnetPrefixLength = mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
544 ? mP2pLeasesSubnetPrefixLength : 0 /* default value */;
545
Xiao Ma4455d6b2020-04-09 10:13:44 +0900546 return new DhcpServingParamsParcelExt()
547 .setDefaultRouters(defaultRouter)
548 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
549 .setDnsServers(dnsServer)
550 .setServerAddr(serverAddr)
551 .setMetered(true)
552 .setSingleClientAddr(clientAddr)
markchienfb65dfe2022-02-25 23:14:58 +0800553 .setChangePrefixOnDecline(changePrefixOnDecline)
554 .setLeasesSubnetPrefixLength(subnetPrefixLength);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900555 // TODO: also advertise link MTU
556 }
557
markchien245352e2020-02-27 20:27:18 +0800558 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800559 if (mUsingLegacyDhcp) {
560 return true;
561 }
markchien245352e2020-02-27 20:27:18 +0800562
563 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800564 final Inet4Address clientAddr = clientLinkAddr == null ? null :
565 (Inet4Address) clientLinkAddr.getAddress();
566
Xiao Ma4455d6b2020-04-09 10:13:44 +0900567 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
568 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800569 mDhcpServerStartIndex++;
570 mDeps.makeDhcpServer(
571 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
572 return true;
573 }
574
575 private void stopDhcp() {
576 // Make all previous start requests obsolete so servers are not started later
577 mDhcpServerStartIndex++;
578
579 if (mDhcpServer != null) {
580 try {
581 mDhcpServer.stop(new OnHandlerStatusCallback() {
582 @Override
583 public void callback(int statusCode) {
584 if (statusCode != STATUS_SUCCESS) {
585 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800586 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800587 // Not much more we can do here
588 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900589 mDhcpLeases.clear();
590 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800591 }
592 });
593 mDhcpServer = null;
594 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900595 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800596 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800597 }
598 }
599 }
600
markchien245352e2020-02-27 20:27:18 +0800601 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
602 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800603 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800604 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800605 } else {
606 stopDhcp();
607 return true;
608 }
609 }
610
611 private void stopIPv4() {
612 configureIPv4(false);
613 // NOTE: All of configureIPv4() will be refactored out of existence
614 // into calls to InterfaceController, shared with startIPv4().
615 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800616 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800617 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800618 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800619 mStaticIpv4ServerAddr = null;
620 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800621 }
622
markchien74a4fa92019-09-09 20:50:49 +0800623 private boolean configureIPv4(boolean enabled) {
624 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
625
markchienc9daba32020-02-12 00:19:21 +0800626 if (enabled) {
markchiena2ffad82020-09-22 15:50:43 +0800627 mIpv4Address = requestIpv4Address(true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800628 }
629
630 if (mIpv4Address == null) {
631 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800632 return false;
markchien74a4fa92019-09-09 20:50:49 +0800633 }
634
markchien69681d62021-11-15 23:58:05 +0800635 if (shouldNotConfigureBluetoothInterface()) {
636 // Interface was already configured elsewhere, only start DHCP.
markchienc9daba32020-02-12 00:19:21 +0800637 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
638 }
639
640 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
641
markchien12c5bb82020-01-07 14:43:17 +0800642 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800643 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900644 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200645 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
646 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900647 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800648 // It is unclear whether the Bluetooth or USB stacks will manage their own
649 // state.
650 setIfaceUp = null;
651 } else {
652 setIfaceUp = enabled;
653 }
654 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
655 mLog.e("Error configuring interface");
656 if (!enabled) stopDhcp();
657 return false;
658 }
markchien74a4fa92019-09-09 20:50:49 +0800659
markchien74a4fa92019-09-09 20:50:49 +0800660 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800661 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900662 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800663 } else {
markchien12c5bb82020-01-07 14:43:17 +0800664 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900665 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800666 }
markchien245352e2020-02-27 20:27:18 +0800667 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800668 }
669
markchien69681d62021-11-15 23:58:05 +0800670 private boolean shouldNotConfigureBluetoothInterface() {
671 // Before T, bluetooth tethering configures the interface elsewhere.
672 return (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) && !SdkLevel.isAtLeastT();
673 }
674
markchiena2ffad82020-09-22 15:50:43 +0800675 private LinkAddress requestIpv4Address(final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800676 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800677
markchien69681d62021-11-15 23:58:05 +0800678 if (shouldNotConfigureBluetoothInterface()) return new LinkAddress(BLUETOOTH_IFACE_ADDR);
markchienc9daba32020-02-12 00:19:21 +0800679
markchiena2ffad82020-09-22 15:50:43 +0800680 return mPrivateAddressCoordinator.requestDownstreamAddress(this, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900681 }
682
markchien74a4fa92019-09-09 20:50:49 +0800683 private boolean startIPv6() {
684 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
685 if (mInterfaceParams == null) {
686 mLog.e("Failed to find InterfaceParams");
687 stopIPv6();
688 return false;
689 }
690
691 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
692 if (!mRaDaemon.start()) {
693 stopIPv6();
694 return false;
695 }
696
markchien932df542021-08-12 13:56:43 +0800697 if (SdkLevel.isAtLeastS()) {
Tyler Wear90e40632020-03-13 11:38:38 -0700698 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
699 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
700 }
701
markchien74a4fa92019-09-09 20:50:49 +0800702 return true;
703 }
704
705 private void stopIPv6() {
706 mInterfaceParams = null;
707 setRaParams(null);
708
709 if (mRaDaemon != null) {
710 mRaDaemon.stop();
711 mRaDaemon = null;
712 }
Tyler Wear90e40632020-03-13 11:38:38 -0700713
714 if (mDadProxy != null) {
715 mDadProxy.stop();
716 mDadProxy = null;
717 }
markchien74a4fa92019-09-09 20:50:49 +0800718 }
719
720 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
721 // LinkProperties. These have extraneous data filtered out and only the
722 // necessary prefixes included (per its prefix distribution policy).
723 //
724 // TODO: Evaluate using a data structure than is more directly suited to
725 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800726 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800727 if (mRaDaemon == null) return;
728
729 // Avoid unnecessary work on spurious updates.
730 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
731 return;
732 }
733
734 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700735 String upstreamIface = null;
736 InterfaceParams upstreamIfaceParams = null;
737 int upstreamIfIndex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800738
739 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700740 upstreamIface = v6only.getInterfaceName();
741 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
742 if (upstreamIfaceParams != null) {
743 upstreamIfIndex = upstreamIfaceParams.index;
744 }
markchien74a4fa92019-09-09 20:50:49 +0800745 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700746 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800747 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
748
markchiend63c4f32020-05-21 17:38:28 +0800749 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800750
751 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
752 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
753
754 final IpPrefix prefix = new IpPrefix(
755 linkAddr.getAddress(), linkAddr.getPrefixLength());
756 params.prefixes.add(prefix);
757
758 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
759 if (dnsServer != null) {
760 params.dnses.add(dnsServer);
761 }
762 }
763 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900764
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900765 // Add upstream index to name mapping. See the comment of the interface mapping update in
766 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
767 // timing issue. It prevents that the IPv6 capability is updated later than
768 // CMD_TETHER_CONNECTION_CHANGED.
769 mBpfCoordinator.addUpstreamNameToLookupTable(upstreamIfIndex, upstreamIface);
770
markchien74a4fa92019-09-09 20:50:49 +0800771 // If v6only is null, we pass in null to setRaParams(), which handles
772 // deprecation of any existing RA data.
773
774 setRaParams(params);
markchien7dc1b4d2021-07-13 17:12:56 +0800775 // Be aware that updateIpv6ForwardingRules use mLastIPv6LinkProperties, so this line should
776 // be eariler than updateIpv6ForwardingRules.
777 // TODO: avoid this dependencies and move this logic into BpfCoordinator.
markchien74a4fa92019-09-09 20:50:49 +0800778 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900779
Tyler Wear90e40632020-03-13 11:38:38 -0700780 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfIndex, null);
781 mLastIPv6UpstreamIfindex = upstreamIfIndex;
782 if (mDadProxy != null) {
783 mDadProxy.setUpstreamIface(upstreamIfaceParams);
784 }
markchien74a4fa92019-09-09 20:50:49 +0800785 }
786
Xiao Ma4455d6b2020-04-09 10:13:44 +0900787 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900788 final int removalFailures = NetdUtils.removeRoutesFromLocalNetwork(
Xiao Ma4455d6b2020-04-09 10:13:44 +0900789 mNetd, toBeRemoved);
790 if (removalFailures > 0) {
791 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
792 removalFailures));
793 }
794
795 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
796 }
797
798 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
799 try {
800 // It's safe to call networkAddInterface() even if
801 // the interface is already in the local_network.
802 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
803 try {
804 // Add routes from local network. Note that adding routes that
805 // already exist does not cause an error (EEXIST is silently ignored).
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900806 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900807 } catch (IllegalStateException e) {
808 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
809 return;
810 }
811 } catch (ServiceSpecificException | RemoteException e) {
812 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
813 return;
814 }
815
816 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
817 }
818
markchien74a4fa92019-09-09 20:50:49 +0800819 private void configureLocalIPv6Routes(
820 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
821 // [1] Remove the routes that are deprecated.
822 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900823 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800824 }
825
826 // [2] Add only the routes that have not previously been added.
827 if (newPrefixes != null && !newPrefixes.isEmpty()) {
828 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
829 if (mLastRaParams != null) {
830 addedPrefixes.removeAll(mLastRaParams.prefixes);
831 }
832
833 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900834 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800835 }
836 }
837 }
838
839 private void configureLocalIPv6Dns(
840 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
841 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
842 if (mNetd == null) {
843 if (newDnses != null) newDnses.clear();
844 mLog.e("No netd service instance available; not setting local IPv6 addresses");
845 return;
846 }
847
848 // [1] Remove deprecated local DNS IP addresses.
849 if (!deprecatedDnses.isEmpty()) {
850 for (Inet6Address dns : deprecatedDnses) {
851 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
852 mLog.e("Failed to remove local dns IP " + dns);
853 }
854
855 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
856 }
857 }
858
859 // [2] Add only the local DNS IP addresses that have not previously been added.
860 if (newDnses != null && !newDnses.isEmpty()) {
861 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
862 if (mLastRaParams != null) {
863 addedDnses.removeAll(mLastRaParams.dnses);
864 }
865
866 for (Inet6Address dns : addedDnses) {
867 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
868 mLog.e("Failed to add local dns IP " + dns);
869 newDnses.remove(dns);
870 }
871
872 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
873 }
874 }
875
876 try {
877 mNetd.tetherApplyDnsInterfaces();
878 } catch (ServiceSpecificException | RemoteException e) {
879 mLog.e("Failed to update local DNS caching server");
880 if (newDnses != null) newDnses.clear();
881 }
882 }
883
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900884 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800885 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
886 // offload is disabled. Add this check just in case.
887 // TODO: Perhaps remove this protection check.
888 if (!mUsingBpfOffload) return;
889
Hungming Chen269c0882020-05-06 14:57:35 +0800890 mBpfCoordinator.tetherOffloadRuleAdd(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900891 }
892
Hungming Chen269c0882020-05-06 14:57:35 +0800893 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800894 // TODO: Perhaps remove this protection check.
Hungming Chen269c0882020-05-06 14:57:35 +0800895 // See the related comment in #addIpv6ForwardingRule.
Hungming Chen3d8fa882020-04-12 14:27:18 +0800896 if (!mUsingBpfOffload) return;
897
Hungming Chen269c0882020-05-06 14:57:35 +0800898 mBpfCoordinator.tetherOffloadRuleRemove(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900899 }
900
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900901 private void clearIpv6ForwardingRules() {
Hungming Chen269c0882020-05-06 14:57:35 +0800902 if (!mUsingBpfOffload) return;
903
904 mBpfCoordinator.tetherOffloadRuleClear(this);
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900905 }
906
Hungming Chen269c0882020-05-06 14:57:35 +0800907 private void updateIpv6ForwardingRule(int newIfindex) {
908 // TODO: Perhaps remove this protection check.
909 // See the related comment in #addIpv6ForwardingRule.
910 if (!mUsingBpfOffload) return;
911
912 mBpfCoordinator.tetherOffloadRuleUpdate(this, newIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900913 }
914
markchien7dc1b4d2021-07-13 17:12:56 +0800915 private boolean isIpv6VcnNetworkInterface() {
916 if (mLastIPv6LinkProperties == null) return false;
917
918 return isVcnInterface(mLastIPv6LinkProperties.getInterfaceName());
919 }
920
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900921 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
922 // changes or if a neighbor event is received.
923 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
924 NeighborEvent e) {
markchien7dc1b4d2021-07-13 17:12:56 +0800925 // If no longer have an upstream or it is virtual network, clear forwarding rules and do
926 // nothing else.
927 // TODO: Rather than always clear rules, ensure whether ipv6 ever enable first.
928 if (upstreamIfindex == 0 || isIpv6VcnNetworkInterface()) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900929 clearIpv6ForwardingRules();
930 return;
931 }
932
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900933 // If the upstream interface has changed, remove all rules and re-add them with the new
934 // upstream interface.
935 if (prevUpstreamIfindex != upstreamIfindex) {
Hungming Chen269c0882020-05-06 14:57:35 +0800936 updateIpv6ForwardingRule(upstreamIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900937 }
938
939 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900940 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900941 if (e == null) return;
942 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
943 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
944 return;
945 }
946
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900947 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
948 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
949 // add rules with a null MAC, only delete them.
950 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900951 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900952 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900953 if (e.isValid()) {
954 addIpv6ForwardingRule(rule);
955 } else {
Hungming Chen269c0882020-05-06 14:57:35 +0800956 removeIpv6ForwardingRule(rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900957 }
958 }
959
Hungming Chend71c06e2020-12-21 19:39:49 +0800960 // TODO: consider moving into BpfCoordinator.
961 private void updateClientInfoIpv4(NeighborEvent e) {
962 // TODO: Perhaps remove this protection check.
963 // See the related comment in #addIpv6ForwardingRule.
964 if (!mUsingBpfOffload) return;
965
966 if (e == null) return;
967 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
968 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
969 return;
970 }
971
972 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
973 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
974 // IpServer never add clients with a null MAC, only delete them.
975 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
976 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
977 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
978 if (e.isValid()) {
979 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
980 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +0800981 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
982 }
983 }
984
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900985 private void handleNeighborEvent(NeighborEvent e) {
986 if (mInterfaceParams != null
987 && mInterfaceParams.index == e.ifindex
988 && mInterfaceParams.hasMacAddress) {
989 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
Hungming Chend71c06e2020-12-21 19:39:49 +0800990 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900991 }
992 }
993
Xiao Ma4455d6b2020-04-09 10:13:44 +0900994 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
995 if (!currentPrefix.contains(mIpv4Address.getAddress())
996 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
997 Log.e(TAG, "Invalid prefix: " + currentPrefix);
998 return;
999 }
1000
1001 final LinkAddress deprecatedLinkAddress = mIpv4Address;
markchiena2ffad82020-09-22 15:50:43 +08001002 mIpv4Address = requestIpv4Address(false);
markchienc9daba32020-02-12 00:19:21 +08001003 if (mIpv4Address == null) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001004 mLog.e("Fail to request a new downstream prefix");
1005 return;
1006 }
markchienc9daba32020-02-12 00:19:21 +08001007 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
Xiao Ma4455d6b2020-04-09 10:13:44 +09001008
1009 // Add new IPv4 address on the interface.
1010 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1011 mLog.e("Failed to add new IP " + srvAddr);
1012 return;
1013 }
1014
1015 // Remove deprecated routes from local network.
1016 removeRoutesFromLocalNetwork(
1017 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1018 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1019
1020 // Add new routes to local network.
1021 addRoutesToLocalNetwork(
1022 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1023 mLinkProperties.addLinkAddress(mIpv4Address);
1024
1025 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1026 // listen on the interface configured with new IPv4 address, that results DNS validation
1027 // failure of downstream client even if appropriate routes have been configured.
1028 try {
1029 mNetd.tetherApplyDnsInterfaces();
1030 } catch (ServiceSpecificException | RemoteException e) {
1031 mLog.e("Failed to update local DNS caching server");
1032 return;
1033 }
1034 sendLinkProperties();
1035
1036 // Notify DHCP server that new prefix/route has been applied on IpServer.
1037 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1038 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1039 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1040 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1041 try {
1042 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1043 @Override
1044 public void callback(int statusCode) {
1045 if (statusCode != STATUS_SUCCESS) {
1046 mLog.e("Error updating DHCP serving params: " + statusCode);
1047 }
1048 }
1049 });
1050 } catch (RemoteException e) {
1051 mLog.e("Error updating DHCP serving params", e);
1052 }
1053 }
1054
markchiend63c4f32020-05-21 17:38:28 +08001055 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001056 try {
1057 int upstreamHopLimit = Integer.parseUnsignedInt(
1058 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001059 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001060 // Cap the hop limit to 255.
1061 return (byte) Integer.min(upstreamHopLimit, 255);
1062 } catch (Exception e) {
1063 mLog.e("Failed to find upstream interface hop limit", e);
1064 }
1065 return RaParams.DEFAULT_HOPLIMIT;
1066 }
1067
1068 private void setRaParams(RaParams newParams) {
1069 if (mRaDaemon != null) {
1070 final RaParams deprecatedParams =
1071 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1072
1073 configureLocalIPv6Routes(deprecatedParams.prefixes,
1074 (newParams != null) ? newParams.prefixes : null);
1075
1076 configureLocalIPv6Dns(deprecatedParams.dnses,
1077 (newParams != null) ? newParams.dnses : null);
1078
1079 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1080 }
1081
1082 mLastRaParams = newParams;
1083 }
1084
markchien21021ef2021-06-01 10:58:04 +08001085 private void maybeLogMessage(State state, int what) {
1086 switch (what) {
1087 // Suppress some CMD_* to avoid log flooding.
1088 case CMD_IPV6_TETHER_UPDATE:
1089 case CMD_NEIGHBOR_EVENT:
1090 break;
1091 default:
1092 mLog.log(state.getName() + " got "
1093 + sMagicDecoderRing.get(what, Integer.toString(what)));
1094 }
markchien74a4fa92019-09-09 20:50:49 +08001095 }
1096
1097 private void sendInterfaceState(int newInterfaceState) {
1098 mServingMode = newInterfaceState;
1099 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1100 sendLinkProperties();
1101 }
1102
1103 private void sendLinkProperties() {
1104 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1105 }
1106
1107 private void resetLinkProperties() {
1108 mLinkProperties.clear();
1109 mLinkProperties.setInterfaceName(mIfaceName);
1110 }
1111
markchienf053e4b2020-03-16 21:49:48 +08001112 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001113 // Ignore static address configuration if they are invalid or null. In theory, static
1114 // addresses should not be invalid here because TetheringManager do not allow caller to
1115 // specify invalid static address configuration.
1116 if (request == null || request.localIPv4Address == null
1117 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1118 request.localIPv4Address, request.staticClientAddress)) {
1119 return;
1120 }
markchienf053e4b2020-03-16 21:49:48 +08001121
1122 mStaticIpv4ServerAddr = request.localIPv4Address;
1123 mStaticIpv4ClientAddr = request.staticClientAddress;
1124 }
1125
markchien74a4fa92019-09-09 20:50:49 +08001126 class InitialState extends State {
1127 @Override
1128 public void enter() {
1129 sendInterfaceState(STATE_AVAILABLE);
1130 }
1131
1132 @Override
1133 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001134 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001135 switch (message.what) {
1136 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +08001137 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001138 switch (message.arg1) {
1139 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001140 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001141 transitionTo(mLocalHotspotState);
1142 break;
1143 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001144 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001145 transitionTo(mTetheredState);
1146 break;
1147 default:
1148 mLog.e("Invalid tethering interface serving state specified.");
1149 }
1150 break;
1151 case CMD_INTERFACE_DOWN:
1152 transitionTo(mUnavailableState);
1153 break;
markchien74a4fa92019-09-09 20:50:49 +08001154 default:
1155 return NOT_HANDLED;
1156 }
1157 return HANDLED;
1158 }
1159 }
1160
Hungming Chen46c30b12020-10-15 17:25:36 +08001161 private void startConntrackMonitoring() {
1162 mBpfCoordinator.startMonitoring(this);
1163 }
1164
1165 private void stopConntrackMonitoring() {
1166 mBpfCoordinator.stopMonitoring(this);
1167 }
1168
markchien74a4fa92019-09-09 20:50:49 +08001169 class BaseServingState extends State {
1170 @Override
1171 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001172 startConntrackMonitoring();
1173
markchien74a4fa92019-09-09 20:50:49 +08001174 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001175 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001176 return;
1177 }
1178
1179 try {
markchienc9daba32020-02-12 00:19:21 +08001180 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001181 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001182 mLog.e("Error Tethering", e);
markchien9b4d7572019-12-25 19:40:32 +08001183 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001184 return;
1185 }
1186
1187 if (!startIPv6()) {
1188 mLog.e("Failed to startIPv6");
1189 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1190 return;
1191 }
1192 }
1193
1194 @Override
1195 public void exit() {
1196 // Note that at this point, we're leaving the tethered state. We can fail any
1197 // of these operations, but it doesn't really change that we have to try them
1198 // all in sequence.
1199 stopIPv6();
1200
1201 try {
markchien12c5bb82020-01-07 14:43:17 +08001202 NetdUtils.untetherInterface(mNetd, mIfaceName);
1203 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001204 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001205 mLog.e("Failed to untether interface: " + e);
1206 }
1207
1208 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001209 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001210
1211 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001212
1213 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1214 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001215 }
1216
1217 @Override
1218 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001219 switch (message.what) {
1220 case CMD_TETHER_UNREQUESTED:
1221 transitionTo(mInitialState);
1222 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1223 break;
1224 case CMD_INTERFACE_DOWN:
1225 transitionTo(mUnavailableState);
1226 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1227 break;
1228 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001229 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001230 sendLinkProperties();
1231 break;
1232 case CMD_IP_FORWARDING_ENABLE_ERROR:
1233 case CMD_IP_FORWARDING_DISABLE_ERROR:
1234 case CMD_START_TETHERING_ERROR:
1235 case CMD_STOP_TETHERING_ERROR:
1236 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien8146b562020-03-19 13:37:43 +08001237 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001238 transitionTo(mInitialState);
1239 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001240 case CMD_NEW_PREFIX_REQUEST:
1241 handleNewPrefixRequest((IpPrefix) message.obj);
1242 break;
markchienc9daba32020-02-12 00:19:21 +08001243 case CMD_NOTIFY_PREFIX_CONFLICT:
1244 mLog.i("restart tethering: " + mInterfaceType);
1245 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1246 transitionTo(mWaitingForRestartState);
1247 break;
markchien74a4fa92019-09-09 20:50:49 +08001248 default:
1249 return false;
1250 }
1251 return true;
1252 }
1253 }
1254
1255 // Handling errors in BaseServingState.enter() by transitioning is
1256 // problematic because transitioning during a multi-state jump yields
1257 // a Log.wtf(). Ultimately, there should be only one ServingState,
1258 // and forwarding and NAT rules should be handled by a coordinating
1259 // functional element outside of IpServer.
1260 class LocalHotspotState extends BaseServingState {
1261 @Override
1262 public void enter() {
1263 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001264 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001265 transitionTo(mInitialState);
1266 }
1267
1268 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1269 sendInterfaceState(STATE_LOCAL_ONLY);
1270 }
1271
1272 @Override
1273 public boolean processMessage(Message message) {
1274 if (super.processMessage(message)) return true;
1275
markchien21021ef2021-06-01 10:58:04 +08001276 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001277 switch (message.what) {
1278 case CMD_TETHER_REQUESTED:
1279 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1280 break;
1281 case CMD_TETHER_CONNECTION_CHANGED:
1282 // Ignored in local hotspot state.
1283 break;
1284 default:
1285 return false;
1286 }
1287 return true;
1288 }
1289 }
1290
1291 // Handling errors in BaseServingState.enter() by transitioning is
1292 // problematic because transitioning during a multi-state jump yields
1293 // a Log.wtf(). Ultimately, there should be only one ServingState,
1294 // and forwarding and NAT rules should be handled by a coordinating
1295 // functional element outside of IpServer.
1296 class TetheredState extends BaseServingState {
1297 @Override
1298 public void enter() {
1299 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001300 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001301 transitionTo(mInitialState);
1302 }
1303
1304 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1305 sendInterfaceState(STATE_TETHERED);
1306 }
1307
1308 @Override
1309 public void exit() {
1310 cleanupUpstream();
1311 super.exit();
1312 }
1313
Hungming Chena6e78692021-02-08 17:15:35 +08001314 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1315 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1316 // and behaviour. While upstream is switching from offload supported interface to
1317 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1318 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1319 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1320 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1321 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1322 // in the state machine. Once there is any case out whish is not covered by previous cases,
1323 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001324 private void cleanupUpstream() {
1325 if (mUpstreamIfaceSet == null) return;
1326
1327 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1328 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001329 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001330 }
1331
1332 private void cleanupUpstreamInterface(String upstreamIface) {
1333 // Note that we don't care about errors here.
1334 // Sometimes interfaces are gone before we get
1335 // to remove their rules, which generates errors.
1336 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001337 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001338 try {
markchien12c5bb82020-01-07 14:43:17 +08001339 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1340 } catch (RemoteException | ServiceSpecificException e) {
1341 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001342 }
1343 try {
markchien12c5bb82020-01-07 14:43:17 +08001344 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1345 } catch (RemoteException | ServiceSpecificException e) {
1346 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001347 }
1348 }
1349
1350 @Override
1351 public boolean processMessage(Message message) {
1352 if (super.processMessage(message)) return true;
1353
markchien21021ef2021-06-01 10:58:04 +08001354 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001355 switch (message.what) {
1356 case CMD_TETHER_REQUESTED:
1357 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1358 break;
1359 case CMD_TETHER_CONNECTION_CHANGED:
1360 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1361 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1362 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1363 break;
1364 }
1365
1366 if (newUpstreamIfaceSet == null) {
1367 cleanupUpstream();
1368 break;
1369 }
1370
1371 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1372 cleanupUpstreamInterface(removed);
1373 }
1374
1375 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1376 // This makes the call to cleanupUpstream() in the error
1377 // path for any interface neatly cleanup all the interfaces.
1378 mUpstreamIfaceSet = newUpstreamIfaceSet;
1379
1380 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001381 // Add upstream index to name mapping for the tether stats usage in the
1382 // coordinator. Although this mapping could be added by both class
1383 // Tethering and IpServer, adding mapping from IpServer guarantees that
1384 // the mapping is added before adding forwarding rules. That is because
1385 // there are different state machines in both classes. It is hard to
1386 // guarantee the link property update order between multiple state machines.
1387 // Note that both IPv4 and IPv6 interface may be added because
1388 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1389 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1390 // capability may be updated later. In that case, IPv6 interface mapping is
1391 // updated in updateUpstreamIPv6LinkProperties.
1392 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1393 final InterfaceParams upstreamIfaceParams =
1394 mDeps.getInterfaceParams(ifname);
1395 if (upstreamIfaceParams != null) {
1396 mBpfCoordinator.addUpstreamNameToLookupTable(
1397 upstreamIfaceParams.index, ifname);
1398 }
1399 }
1400
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001401 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001402 try {
markchien12c5bb82020-01-07 14:43:17 +08001403 mNetd.tetherAddForward(mIfaceName, ifname);
1404 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1405 } catch (RemoteException | ServiceSpecificException e) {
1406 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001407 cleanupUpstream();
markchien8146b562020-03-19 13:37:43 +08001408 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001409 transitionTo(mInitialState);
1410 return true;
1411 }
1412 }
1413 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001414 case CMD_NEIGHBOR_EVENT:
1415 handleNeighborEvent((NeighborEvent) message.obj);
1416 break;
markchien74a4fa92019-09-09 20:50:49 +08001417 default:
1418 return false;
1419 }
1420 return true;
1421 }
1422
1423 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1424 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1425 if (mUpstreamIfaceSet != null && newIfaces != null) {
1426 return mUpstreamIfaceSet.equals(newIfaces);
1427 }
1428 return false;
1429 }
1430
1431 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1432 if (mUpstreamIfaceSet == null) return new HashSet<>();
1433
1434 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1435 removed.removeAll(newIfaces.ifnames);
1436 return removed;
1437 }
1438
1439 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1440 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1441 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1442 return added;
1443 }
1444 }
1445
1446 /**
1447 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001448 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001449 * specific state machine from its list of possible recipients of
1450 * tethering requests. The state machine itself will hang around until
1451 * the garbage collector finds it.
1452 */
1453 class UnavailableState extends State {
1454 @Override
1455 public void enter() {
h.zhangd244bd02020-06-14 14:46:54 +08001456 mIpNeighborMonitor.stop();
markchien9b4d7572019-12-25 19:40:32 +08001457 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001458 sendInterfaceState(STATE_UNAVAILABLE);
1459 }
1460 }
1461
markchienc9daba32020-02-12 00:19:21 +08001462 class WaitingForRestartState extends State {
1463 @Override
1464 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001465 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001466 switch (message.what) {
1467 case CMD_TETHER_UNREQUESTED:
1468 transitionTo(mInitialState);
1469 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1470 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1471 break;
1472 case CMD_INTERFACE_DOWN:
1473 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001474 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001475 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1476 break;
1477 default:
1478 return false;
1479 }
1480 return true;
1481 }
1482 }
1483
markchien74a4fa92019-09-09 20:50:49 +08001484 // Accumulate routes representing "prefixes to be assigned to the local
1485 // interface", for subsequent modification of local_network routing.
1486 private static ArrayList<RouteInfo> getLocalRoutesFor(
1487 String ifname, HashSet<IpPrefix> prefixes) {
1488 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1489 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001490 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001491 }
1492 return localRoutes;
1493 }
1494
1495 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1496 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1497 final byte[] dnsBytes = localPrefix.getRawAddress();
1498 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1499 try {
1500 return Inet6Address.getByAddress(null, dnsBytes, 0);
1501 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001502 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001503 return null;
1504 }
1505 }
1506
1507 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1508 final byte random = (byte) (new Random()).nextInt();
1509 for (int value : excluded) {
1510 if (random == value) return dflt;
1511 }
1512 return random;
1513 }
1514}