blob: 438b592832545fddc9f1670db861fafc3bee3685 [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
markchien74a4fa92019-09-09 20:50:49 +0800381 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
382 public void stop() {
383 sendMessage(CMD_INTERFACE_DOWN);
384 }
385
386 /**
387 * Tethering is canceled. IpServer state machine will be available and wait for
388 * next tethering request.
389 */
390 public void unwanted() {
391 sendMessage(CMD_TETHER_UNREQUESTED);
392 }
393
394 /** Internals. */
395
396 private boolean startIPv4() {
397 return configureIPv4(true);
398 }
399
400 /**
401 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
402 * handler.
403 *
404 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
405 * with different implementations of the callback, to differentiate handling of success/error in
406 * each call.
407 */
408 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
409 @Override
410 public void onStatusAvailable(int statusCode) {
411 getHandler().post(() -> callback(statusCode));
412 }
413
414 public abstract void callback(int statusCode);
415
416 @Override
417 public int getInterfaceVersion() {
418 return this.VERSION;
419 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900420
421 @Override
422 public String getInterfaceHash() {
423 return this.HASH;
424 }
markchien74a4fa92019-09-09 20:50:49 +0800425 }
426
427 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
428 private final int mStartIndex;
429
430 private DhcpServerCallbacksImpl(int startIndex) {
431 mStartIndex = startIndex;
432 }
433
434 @Override
435 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
436 getHandler().post(() -> {
437 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
438 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800439 // This start request is obsolete. Explicitly stop the DHCP server to shut
440 // down its thread. When the |server| binder token goes out of scope, the
441 // garbage collector will finalize it, which causes the network stack process
442 // garbage collector to collect the server itself.
443 try {
444 server.stop(null);
445 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800446 return;
447 }
448
449 if (statusCode != STATUS_SUCCESS) {
450 mLog.e("Error obtaining DHCP server: " + statusCode);
451 handleError();
452 return;
453 }
454
455 mDhcpServer = server;
456 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900457 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800458 @Override
459 public void callback(int startStatusCode) {
460 if (startStatusCode != STATUS_SUCCESS) {
461 mLog.e("Error starting DHCP server: " + startStatusCode);
462 handleError();
463 }
464 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900465 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800466 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800467 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800468 }
469 });
470 }
471
472 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800473 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800474 transitionTo(mInitialState);
475 }
476 }
477
Xiao Ma4455d6b2020-04-09 10:13:44 +0900478 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900479 @Override
480 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
481 final ArrayList<TetheredClient> leases = new ArrayList<>();
482 for (DhcpLeaseParcelable lease : leaseParcelables) {
483 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900484 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
485 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
486 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900487
488 final MacAddress macAddress;
489 try {
490 macAddress = MacAddress.fromBytes(lease.hwAddr);
491 } catch (IllegalArgumentException e) {
492 Log.wtf(TAG, "Invalid address received from DhcpServer: "
493 + Arrays.toString(lease.hwAddr));
494 return;
495 }
496
497 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900498 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900499 leases.add(new TetheredClient(
500 macAddress,
501 Collections.singletonList(addressInfo),
502 mInterfaceType));
503 }
504
505 getHandler().post(() -> {
506 mDhcpLeases = leases;
507 mCallback.dhcpLeasesChanged();
508 });
509 }
510
511 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900512 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
513 Objects.requireNonNull(currentPrefix);
514 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900515 }
516
517 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900518 public int getInterfaceVersion() {
519 return this.VERSION;
520 }
521
522 @Override
523 public String getInterfaceHash() throws RemoteException {
524 return this.HASH;
525 }
526 }
527
Xiao Ma4455d6b2020-04-09 10:13:44 +0900528 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
529 Objects.requireNonNull(ipv4Address);
530 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
531 }
532
533 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
534 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
535 @Nullable Inet4Address clientAddr) {
536 final boolean changePrefixOnDecline =
537 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
markchienfb65dfe2022-02-25 23:14:58 +0800538 final int subnetPrefixLength = mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
539 ? mP2pLeasesSubnetPrefixLength : 0 /* default value */;
540
Xiao Ma4455d6b2020-04-09 10:13:44 +0900541 return new DhcpServingParamsParcelExt()
542 .setDefaultRouters(defaultRouter)
543 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
544 .setDnsServers(dnsServer)
545 .setServerAddr(serverAddr)
546 .setMetered(true)
547 .setSingleClientAddr(clientAddr)
markchienfb65dfe2022-02-25 23:14:58 +0800548 .setChangePrefixOnDecline(changePrefixOnDecline)
549 .setLeasesSubnetPrefixLength(subnetPrefixLength);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900550 // TODO: also advertise link MTU
551 }
552
markchien245352e2020-02-27 20:27:18 +0800553 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800554 if (mUsingLegacyDhcp) {
555 return true;
556 }
markchien245352e2020-02-27 20:27:18 +0800557
558 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800559 final Inet4Address clientAddr = clientLinkAddr == null ? null :
560 (Inet4Address) clientLinkAddr.getAddress();
561
Xiao Ma4455d6b2020-04-09 10:13:44 +0900562 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
563 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800564 mDhcpServerStartIndex++;
565 mDeps.makeDhcpServer(
566 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
567 return true;
568 }
569
570 private void stopDhcp() {
571 // Make all previous start requests obsolete so servers are not started later
572 mDhcpServerStartIndex++;
573
574 if (mDhcpServer != null) {
575 try {
576 mDhcpServer.stop(new OnHandlerStatusCallback() {
577 @Override
578 public void callback(int statusCode) {
579 if (statusCode != STATUS_SUCCESS) {
580 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800581 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800582 // Not much more we can do here
583 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900584 mDhcpLeases.clear();
585 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800586 }
587 });
588 mDhcpServer = null;
589 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900590 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800591 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800592 }
593 }
594 }
595
markchien245352e2020-02-27 20:27:18 +0800596 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
597 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800598 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800599 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800600 } else {
601 stopDhcp();
602 return true;
603 }
604 }
605
606 private void stopIPv4() {
607 configureIPv4(false);
608 // NOTE: All of configureIPv4() will be refactored out of existence
609 // into calls to InterfaceController, shared with startIPv4().
610 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800611 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800612 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800613 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800614 mStaticIpv4ServerAddr = null;
615 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800616 }
617
markchien74a4fa92019-09-09 20:50:49 +0800618 private boolean configureIPv4(boolean enabled) {
619 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
620
markchienc9daba32020-02-12 00:19:21 +0800621 if (enabled) {
markchiena2ffad82020-09-22 15:50:43 +0800622 mIpv4Address = requestIpv4Address(true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800623 }
624
625 if (mIpv4Address == null) {
626 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800627 return false;
markchien74a4fa92019-09-09 20:50:49 +0800628 }
629
markchien69681d62021-11-15 23:58:05 +0800630 if (shouldNotConfigureBluetoothInterface()) {
631 // Interface was already configured elsewhere, only start DHCP.
markchienc9daba32020-02-12 00:19:21 +0800632 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
633 }
634
635 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
636
markchien12c5bb82020-01-07 14:43:17 +0800637 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800638 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900639 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200640 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
641 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900642 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800643 // It is unclear whether the Bluetooth or USB stacks will manage their own
644 // state.
645 setIfaceUp = null;
646 } else {
647 setIfaceUp = enabled;
648 }
649 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
650 mLog.e("Error configuring interface");
651 if (!enabled) stopDhcp();
652 return false;
653 }
markchien74a4fa92019-09-09 20:50:49 +0800654
markchien74a4fa92019-09-09 20:50:49 +0800655 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800656 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900657 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800658 } else {
markchien12c5bb82020-01-07 14:43:17 +0800659 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900660 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800661 }
markchien245352e2020-02-27 20:27:18 +0800662 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800663 }
664
markchien69681d62021-11-15 23:58:05 +0800665 private boolean shouldNotConfigureBluetoothInterface() {
666 // Before T, bluetooth tethering configures the interface elsewhere.
667 return (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) && !SdkLevel.isAtLeastT();
668 }
669
markchiena2ffad82020-09-22 15:50:43 +0800670 private LinkAddress requestIpv4Address(final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800671 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800672
markchien69681d62021-11-15 23:58:05 +0800673 if (shouldNotConfigureBluetoothInterface()) return new LinkAddress(BLUETOOTH_IFACE_ADDR);
markchienc9daba32020-02-12 00:19:21 +0800674
markchiena2ffad82020-09-22 15:50:43 +0800675 return mPrivateAddressCoordinator.requestDownstreamAddress(this, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900676 }
677
markchien74a4fa92019-09-09 20:50:49 +0800678 private boolean startIPv6() {
679 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
680 if (mInterfaceParams == null) {
681 mLog.e("Failed to find InterfaceParams");
682 stopIPv6();
683 return false;
684 }
685
686 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
687 if (!mRaDaemon.start()) {
688 stopIPv6();
689 return false;
690 }
691
markchien932df542021-08-12 13:56:43 +0800692 if (SdkLevel.isAtLeastS()) {
Tyler Wear90e40632020-03-13 11:38:38 -0700693 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
694 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
695 }
696
markchien74a4fa92019-09-09 20:50:49 +0800697 return true;
698 }
699
700 private void stopIPv6() {
701 mInterfaceParams = null;
702 setRaParams(null);
703
704 if (mRaDaemon != null) {
705 mRaDaemon.stop();
706 mRaDaemon = null;
707 }
Tyler Wear90e40632020-03-13 11:38:38 -0700708
709 if (mDadProxy != null) {
710 mDadProxy.stop();
711 mDadProxy = null;
712 }
markchien74a4fa92019-09-09 20:50:49 +0800713 }
714
715 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
716 // LinkProperties. These have extraneous data filtered out and only the
717 // necessary prefixes included (per its prefix distribution policy).
718 //
719 // TODO: Evaluate using a data structure than is more directly suited to
720 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800721 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800722 if (mRaDaemon == null) return;
723
724 // Avoid unnecessary work on spurious updates.
725 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
726 return;
727 }
728
729 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700730 String upstreamIface = null;
731 InterfaceParams upstreamIfaceParams = null;
732 int upstreamIfIndex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800733
734 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700735 upstreamIface = v6only.getInterfaceName();
736 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
737 if (upstreamIfaceParams != null) {
738 upstreamIfIndex = upstreamIfaceParams.index;
739 }
markchien74a4fa92019-09-09 20:50:49 +0800740 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700741 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800742 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
743
markchiend63c4f32020-05-21 17:38:28 +0800744 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800745
746 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
747 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
748
749 final IpPrefix prefix = new IpPrefix(
750 linkAddr.getAddress(), linkAddr.getPrefixLength());
751 params.prefixes.add(prefix);
752
753 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
754 if (dnsServer != null) {
755 params.dnses.add(dnsServer);
756 }
757 }
758 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900759
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900760 // Add upstream index to name mapping. See the comment of the interface mapping update in
761 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
762 // timing issue. It prevents that the IPv6 capability is updated later than
763 // CMD_TETHER_CONNECTION_CHANGED.
764 mBpfCoordinator.addUpstreamNameToLookupTable(upstreamIfIndex, upstreamIface);
765
markchien74a4fa92019-09-09 20:50:49 +0800766 // If v6only is null, we pass in null to setRaParams(), which handles
767 // deprecation of any existing RA data.
768
769 setRaParams(params);
markchien7dc1b4d2021-07-13 17:12:56 +0800770 // Be aware that updateIpv6ForwardingRules use mLastIPv6LinkProperties, so this line should
771 // be eariler than updateIpv6ForwardingRules.
772 // TODO: avoid this dependencies and move this logic into BpfCoordinator.
markchien74a4fa92019-09-09 20:50:49 +0800773 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900774
Tyler Wear90e40632020-03-13 11:38:38 -0700775 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfIndex, null);
776 mLastIPv6UpstreamIfindex = upstreamIfIndex;
777 if (mDadProxy != null) {
778 mDadProxy.setUpstreamIface(upstreamIfaceParams);
779 }
markchien74a4fa92019-09-09 20:50:49 +0800780 }
781
Xiao Ma4455d6b2020-04-09 10:13:44 +0900782 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900783 final int removalFailures = NetdUtils.removeRoutesFromLocalNetwork(
Xiao Ma4455d6b2020-04-09 10:13:44 +0900784 mNetd, toBeRemoved);
785 if (removalFailures > 0) {
786 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
787 removalFailures));
788 }
789
790 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
791 }
792
793 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
794 try {
795 // It's safe to call networkAddInterface() even if
796 // the interface is already in the local_network.
797 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
798 try {
799 // Add routes from local network. Note that adding routes that
800 // already exist does not cause an error (EEXIST is silently ignored).
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900801 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900802 } catch (IllegalStateException e) {
803 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
804 return;
805 }
806 } catch (ServiceSpecificException | RemoteException e) {
807 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
808 return;
809 }
810
811 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
812 }
813
markchien74a4fa92019-09-09 20:50:49 +0800814 private void configureLocalIPv6Routes(
815 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
816 // [1] Remove the routes that are deprecated.
817 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900818 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800819 }
820
821 // [2] Add only the routes that have not previously been added.
822 if (newPrefixes != null && !newPrefixes.isEmpty()) {
823 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
824 if (mLastRaParams != null) {
825 addedPrefixes.removeAll(mLastRaParams.prefixes);
826 }
827
828 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900829 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800830 }
831 }
832 }
833
834 private void configureLocalIPv6Dns(
835 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
836 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
837 if (mNetd == null) {
838 if (newDnses != null) newDnses.clear();
839 mLog.e("No netd service instance available; not setting local IPv6 addresses");
840 return;
841 }
842
843 // [1] Remove deprecated local DNS IP addresses.
844 if (!deprecatedDnses.isEmpty()) {
845 for (Inet6Address dns : deprecatedDnses) {
846 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
847 mLog.e("Failed to remove local dns IP " + dns);
848 }
849
850 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
851 }
852 }
853
854 // [2] Add only the local DNS IP addresses that have not previously been added.
855 if (newDnses != null && !newDnses.isEmpty()) {
856 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
857 if (mLastRaParams != null) {
858 addedDnses.removeAll(mLastRaParams.dnses);
859 }
860
861 for (Inet6Address dns : addedDnses) {
862 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
863 mLog.e("Failed to add local dns IP " + dns);
864 newDnses.remove(dns);
865 }
866
867 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
868 }
869 }
870
871 try {
872 mNetd.tetherApplyDnsInterfaces();
873 } catch (ServiceSpecificException | RemoteException e) {
874 mLog.e("Failed to update local DNS caching server");
875 if (newDnses != null) newDnses.clear();
876 }
877 }
878
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900879 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800880 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
881 // offload is disabled. Add this check just in case.
882 // TODO: Perhaps remove this protection check.
883 if (!mUsingBpfOffload) return;
884
Hungming Chen269c0882020-05-06 14:57:35 +0800885 mBpfCoordinator.tetherOffloadRuleAdd(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900886 }
887
Hungming Chen269c0882020-05-06 14:57:35 +0800888 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800889 // TODO: Perhaps remove this protection check.
Hungming Chen269c0882020-05-06 14:57:35 +0800890 // See the related comment in #addIpv6ForwardingRule.
Hungming Chen3d8fa882020-04-12 14:27:18 +0800891 if (!mUsingBpfOffload) return;
892
Hungming Chen269c0882020-05-06 14:57:35 +0800893 mBpfCoordinator.tetherOffloadRuleRemove(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900894 }
895
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900896 private void clearIpv6ForwardingRules() {
Hungming Chen269c0882020-05-06 14:57:35 +0800897 if (!mUsingBpfOffload) return;
898
899 mBpfCoordinator.tetherOffloadRuleClear(this);
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900900 }
901
Hungming Chen269c0882020-05-06 14:57:35 +0800902 private void updateIpv6ForwardingRule(int newIfindex) {
903 // TODO: Perhaps remove this protection check.
904 // See the related comment in #addIpv6ForwardingRule.
905 if (!mUsingBpfOffload) return;
906
907 mBpfCoordinator.tetherOffloadRuleUpdate(this, newIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900908 }
909
markchien7dc1b4d2021-07-13 17:12:56 +0800910 private boolean isIpv6VcnNetworkInterface() {
911 if (mLastIPv6LinkProperties == null) return false;
912
913 return isVcnInterface(mLastIPv6LinkProperties.getInterfaceName());
914 }
915
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900916 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
917 // changes or if a neighbor event is received.
918 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
919 NeighborEvent e) {
markchien7dc1b4d2021-07-13 17:12:56 +0800920 // If no longer have an upstream or it is virtual network, clear forwarding rules and do
921 // nothing else.
922 // TODO: Rather than always clear rules, ensure whether ipv6 ever enable first.
923 if (upstreamIfindex == 0 || isIpv6VcnNetworkInterface()) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900924 clearIpv6ForwardingRules();
925 return;
926 }
927
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900928 // If the upstream interface has changed, remove all rules and re-add them with the new
929 // upstream interface.
930 if (prevUpstreamIfindex != upstreamIfindex) {
Hungming Chen269c0882020-05-06 14:57:35 +0800931 updateIpv6ForwardingRule(upstreamIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900932 }
933
934 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900935 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900936 if (e == null) return;
937 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
938 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
939 return;
940 }
941
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900942 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
943 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
944 // add rules with a null MAC, only delete them.
945 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900946 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900947 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900948 if (e.isValid()) {
949 addIpv6ForwardingRule(rule);
950 } else {
Hungming Chen269c0882020-05-06 14:57:35 +0800951 removeIpv6ForwardingRule(rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900952 }
953 }
954
Hungming Chend71c06e2020-12-21 19:39:49 +0800955 // TODO: consider moving into BpfCoordinator.
956 private void updateClientInfoIpv4(NeighborEvent e) {
957 // TODO: Perhaps remove this protection check.
958 // See the related comment in #addIpv6ForwardingRule.
959 if (!mUsingBpfOffload) return;
960
961 if (e == null) return;
962 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
963 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
964 return;
965 }
966
967 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
968 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
969 // IpServer never add clients with a null MAC, only delete them.
970 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
971 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
972 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
973 if (e.isValid()) {
974 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
975 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +0800976 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
977 }
978 }
979
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900980 private void handleNeighborEvent(NeighborEvent e) {
981 if (mInterfaceParams != null
982 && mInterfaceParams.index == e.ifindex
983 && mInterfaceParams.hasMacAddress) {
984 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
Hungming Chend71c06e2020-12-21 19:39:49 +0800985 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900986 }
987 }
988
Xiao Ma4455d6b2020-04-09 10:13:44 +0900989 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
990 if (!currentPrefix.contains(mIpv4Address.getAddress())
991 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
992 Log.e(TAG, "Invalid prefix: " + currentPrefix);
993 return;
994 }
995
996 final LinkAddress deprecatedLinkAddress = mIpv4Address;
markchiena2ffad82020-09-22 15:50:43 +0800997 mIpv4Address = requestIpv4Address(false);
markchienc9daba32020-02-12 00:19:21 +0800998 if (mIpv4Address == null) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900999 mLog.e("Fail to request a new downstream prefix");
1000 return;
1001 }
markchienc9daba32020-02-12 00:19:21 +08001002 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
Xiao Ma4455d6b2020-04-09 10:13:44 +09001003
1004 // Add new IPv4 address on the interface.
1005 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1006 mLog.e("Failed to add new IP " + srvAddr);
1007 return;
1008 }
1009
1010 // Remove deprecated routes from local network.
1011 removeRoutesFromLocalNetwork(
1012 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1013 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1014
1015 // Add new routes to local network.
1016 addRoutesToLocalNetwork(
1017 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1018 mLinkProperties.addLinkAddress(mIpv4Address);
1019
1020 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1021 // listen on the interface configured with new IPv4 address, that results DNS validation
1022 // failure of downstream client even if appropriate routes have been configured.
1023 try {
1024 mNetd.tetherApplyDnsInterfaces();
1025 } catch (ServiceSpecificException | RemoteException e) {
1026 mLog.e("Failed to update local DNS caching server");
1027 return;
1028 }
1029 sendLinkProperties();
1030
1031 // Notify DHCP server that new prefix/route has been applied on IpServer.
1032 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1033 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1034 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1035 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1036 try {
1037 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1038 @Override
1039 public void callback(int statusCode) {
1040 if (statusCode != STATUS_SUCCESS) {
1041 mLog.e("Error updating DHCP serving params: " + statusCode);
1042 }
1043 }
1044 });
1045 } catch (RemoteException e) {
1046 mLog.e("Error updating DHCP serving params", e);
1047 }
1048 }
1049
markchiend63c4f32020-05-21 17:38:28 +08001050 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001051 try {
1052 int upstreamHopLimit = Integer.parseUnsignedInt(
1053 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001054 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001055 // Cap the hop limit to 255.
1056 return (byte) Integer.min(upstreamHopLimit, 255);
1057 } catch (Exception e) {
1058 mLog.e("Failed to find upstream interface hop limit", e);
1059 }
1060 return RaParams.DEFAULT_HOPLIMIT;
1061 }
1062
1063 private void setRaParams(RaParams newParams) {
1064 if (mRaDaemon != null) {
1065 final RaParams deprecatedParams =
1066 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1067
1068 configureLocalIPv6Routes(deprecatedParams.prefixes,
1069 (newParams != null) ? newParams.prefixes : null);
1070
1071 configureLocalIPv6Dns(deprecatedParams.dnses,
1072 (newParams != null) ? newParams.dnses : null);
1073
1074 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1075 }
1076
1077 mLastRaParams = newParams;
1078 }
1079
markchien21021ef2021-06-01 10:58:04 +08001080 private void maybeLogMessage(State state, int what) {
1081 switch (what) {
1082 // Suppress some CMD_* to avoid log flooding.
1083 case CMD_IPV6_TETHER_UPDATE:
1084 case CMD_NEIGHBOR_EVENT:
1085 break;
1086 default:
1087 mLog.log(state.getName() + " got "
1088 + sMagicDecoderRing.get(what, Integer.toString(what)));
1089 }
markchien74a4fa92019-09-09 20:50:49 +08001090 }
1091
1092 private void sendInterfaceState(int newInterfaceState) {
1093 mServingMode = newInterfaceState;
1094 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1095 sendLinkProperties();
1096 }
1097
1098 private void sendLinkProperties() {
1099 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1100 }
1101
1102 private void resetLinkProperties() {
1103 mLinkProperties.clear();
1104 mLinkProperties.setInterfaceName(mIfaceName);
1105 }
1106
markchienf053e4b2020-03-16 21:49:48 +08001107 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001108 // Ignore static address configuration if they are invalid or null. In theory, static
1109 // addresses should not be invalid here because TetheringManager do not allow caller to
1110 // specify invalid static address configuration.
1111 if (request == null || request.localIPv4Address == null
1112 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1113 request.localIPv4Address, request.staticClientAddress)) {
1114 return;
1115 }
markchienf053e4b2020-03-16 21:49:48 +08001116
1117 mStaticIpv4ServerAddr = request.localIPv4Address;
1118 mStaticIpv4ClientAddr = request.staticClientAddress;
1119 }
1120
markchien74a4fa92019-09-09 20:50:49 +08001121 class InitialState extends State {
1122 @Override
1123 public void enter() {
1124 sendInterfaceState(STATE_AVAILABLE);
1125 }
1126
1127 @Override
1128 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001129 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001130 switch (message.what) {
1131 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +08001132 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001133 switch (message.arg1) {
1134 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001135 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001136 transitionTo(mLocalHotspotState);
1137 break;
1138 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001139 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001140 transitionTo(mTetheredState);
1141 break;
1142 default:
1143 mLog.e("Invalid tethering interface serving state specified.");
1144 }
1145 break;
1146 case CMD_INTERFACE_DOWN:
1147 transitionTo(mUnavailableState);
1148 break;
1149 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001150 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001151 break;
1152 default:
1153 return NOT_HANDLED;
1154 }
1155 return HANDLED;
1156 }
1157 }
1158
Hungming Chen46c30b12020-10-15 17:25:36 +08001159 private void startConntrackMonitoring() {
1160 mBpfCoordinator.startMonitoring(this);
1161 }
1162
1163 private void stopConntrackMonitoring() {
1164 mBpfCoordinator.stopMonitoring(this);
1165 }
1166
markchien74a4fa92019-09-09 20:50:49 +08001167 class BaseServingState extends State {
1168 @Override
1169 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001170 startConntrackMonitoring();
1171
markchien74a4fa92019-09-09 20:50:49 +08001172 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001173 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001174 return;
1175 }
1176
1177 try {
markchienc9daba32020-02-12 00:19:21 +08001178 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001179 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001180 mLog.e("Error Tethering", e);
markchien9b4d7572019-12-25 19:40:32 +08001181 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001182 return;
1183 }
1184
1185 if (!startIPv6()) {
1186 mLog.e("Failed to startIPv6");
1187 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1188 return;
1189 }
1190 }
1191
1192 @Override
1193 public void exit() {
1194 // Note that at this point, we're leaving the tethered state. We can fail any
1195 // of these operations, but it doesn't really change that we have to try them
1196 // all in sequence.
1197 stopIPv6();
1198
1199 try {
markchien12c5bb82020-01-07 14:43:17 +08001200 NetdUtils.untetherInterface(mNetd, mIfaceName);
1201 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001202 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001203 mLog.e("Failed to untether interface: " + e);
1204 }
1205
1206 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001207 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001208
1209 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001210
1211 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1212 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001213 }
1214
1215 @Override
1216 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001217 switch (message.what) {
1218 case CMD_TETHER_UNREQUESTED:
1219 transitionTo(mInitialState);
1220 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1221 break;
1222 case CMD_INTERFACE_DOWN:
1223 transitionTo(mUnavailableState);
1224 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1225 break;
1226 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001227 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001228 sendLinkProperties();
1229 break;
1230 case CMD_IP_FORWARDING_ENABLE_ERROR:
1231 case CMD_IP_FORWARDING_DISABLE_ERROR:
1232 case CMD_START_TETHERING_ERROR:
1233 case CMD_STOP_TETHERING_ERROR:
1234 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien8146b562020-03-19 13:37:43 +08001235 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001236 transitionTo(mInitialState);
1237 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001238 case CMD_NEW_PREFIX_REQUEST:
1239 handleNewPrefixRequest((IpPrefix) message.obj);
1240 break;
markchienc9daba32020-02-12 00:19:21 +08001241 case CMD_NOTIFY_PREFIX_CONFLICT:
1242 mLog.i("restart tethering: " + mInterfaceType);
1243 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1244 transitionTo(mWaitingForRestartState);
1245 break;
markchien74a4fa92019-09-09 20:50:49 +08001246 default:
1247 return false;
1248 }
1249 return true;
1250 }
1251 }
1252
1253 // Handling errors in BaseServingState.enter() by transitioning is
1254 // problematic because transitioning during a multi-state jump yields
1255 // a Log.wtf(). Ultimately, there should be only one ServingState,
1256 // and forwarding and NAT rules should be handled by a coordinating
1257 // functional element outside of IpServer.
1258 class LocalHotspotState extends BaseServingState {
1259 @Override
1260 public void enter() {
1261 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001262 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001263 transitionTo(mInitialState);
1264 }
1265
1266 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1267 sendInterfaceState(STATE_LOCAL_ONLY);
1268 }
1269
1270 @Override
1271 public boolean processMessage(Message message) {
1272 if (super.processMessage(message)) return true;
1273
markchien21021ef2021-06-01 10:58:04 +08001274 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001275 switch (message.what) {
1276 case CMD_TETHER_REQUESTED:
1277 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1278 break;
1279 case CMD_TETHER_CONNECTION_CHANGED:
1280 // Ignored in local hotspot state.
1281 break;
1282 default:
1283 return false;
1284 }
1285 return true;
1286 }
1287 }
1288
1289 // Handling errors in BaseServingState.enter() by transitioning is
1290 // problematic because transitioning during a multi-state jump yields
1291 // a Log.wtf(). Ultimately, there should be only one ServingState,
1292 // and forwarding and NAT rules should be handled by a coordinating
1293 // functional element outside of IpServer.
1294 class TetheredState extends BaseServingState {
1295 @Override
1296 public void enter() {
1297 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001298 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001299 transitionTo(mInitialState);
1300 }
1301
1302 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1303 sendInterfaceState(STATE_TETHERED);
1304 }
1305
1306 @Override
1307 public void exit() {
1308 cleanupUpstream();
1309 super.exit();
1310 }
1311
Hungming Chena6e78692021-02-08 17:15:35 +08001312 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1313 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1314 // and behaviour. While upstream is switching from offload supported interface to
1315 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1316 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1317 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1318 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1319 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1320 // in the state machine. Once there is any case out whish is not covered by previous cases,
1321 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001322 private void cleanupUpstream() {
1323 if (mUpstreamIfaceSet == null) return;
1324
1325 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1326 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001327 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001328 }
1329
1330 private void cleanupUpstreamInterface(String upstreamIface) {
1331 // Note that we don't care about errors here.
1332 // Sometimes interfaces are gone before we get
1333 // to remove their rules, which generates errors.
1334 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001335 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001336 try {
markchien12c5bb82020-01-07 14:43:17 +08001337 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1338 } catch (RemoteException | ServiceSpecificException e) {
1339 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001340 }
1341 try {
markchien12c5bb82020-01-07 14:43:17 +08001342 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1343 } catch (RemoteException | ServiceSpecificException e) {
1344 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001345 }
1346 }
1347
1348 @Override
1349 public boolean processMessage(Message message) {
1350 if (super.processMessage(message)) return true;
1351
markchien21021ef2021-06-01 10:58:04 +08001352 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001353 switch (message.what) {
1354 case CMD_TETHER_REQUESTED:
1355 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1356 break;
1357 case CMD_TETHER_CONNECTION_CHANGED:
1358 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1359 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1360 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1361 break;
1362 }
1363
1364 if (newUpstreamIfaceSet == null) {
1365 cleanupUpstream();
1366 break;
1367 }
1368
1369 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1370 cleanupUpstreamInterface(removed);
1371 }
1372
1373 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1374 // This makes the call to cleanupUpstream() in the error
1375 // path for any interface neatly cleanup all the interfaces.
1376 mUpstreamIfaceSet = newUpstreamIfaceSet;
1377
1378 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001379 // Add upstream index to name mapping for the tether stats usage in the
1380 // coordinator. Although this mapping could be added by both class
1381 // Tethering and IpServer, adding mapping from IpServer guarantees that
1382 // the mapping is added before adding forwarding rules. That is because
1383 // there are different state machines in both classes. It is hard to
1384 // guarantee the link property update order between multiple state machines.
1385 // Note that both IPv4 and IPv6 interface may be added because
1386 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1387 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1388 // capability may be updated later. In that case, IPv6 interface mapping is
1389 // updated in updateUpstreamIPv6LinkProperties.
1390 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1391 final InterfaceParams upstreamIfaceParams =
1392 mDeps.getInterfaceParams(ifname);
1393 if (upstreamIfaceParams != null) {
1394 mBpfCoordinator.addUpstreamNameToLookupTable(
1395 upstreamIfaceParams.index, ifname);
1396 }
1397 }
1398
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001399 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001400 try {
markchien12c5bb82020-01-07 14:43:17 +08001401 mNetd.tetherAddForward(mIfaceName, ifname);
1402 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1403 } catch (RemoteException | ServiceSpecificException e) {
1404 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001405 cleanupUpstream();
markchien8146b562020-03-19 13:37:43 +08001406 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001407 transitionTo(mInitialState);
1408 return true;
1409 }
1410 }
1411 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001412 case CMD_NEIGHBOR_EVENT:
1413 handleNeighborEvent((NeighborEvent) message.obj);
1414 break;
markchien74a4fa92019-09-09 20:50:49 +08001415 default:
1416 return false;
1417 }
1418 return true;
1419 }
1420
1421 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1422 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1423 if (mUpstreamIfaceSet != null && newIfaces != null) {
1424 return mUpstreamIfaceSet.equals(newIfaces);
1425 }
1426 return false;
1427 }
1428
1429 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1430 if (mUpstreamIfaceSet == null) return new HashSet<>();
1431
1432 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1433 removed.removeAll(newIfaces.ifnames);
1434 return removed;
1435 }
1436
1437 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1438 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1439 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1440 return added;
1441 }
1442 }
1443
1444 /**
1445 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001446 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001447 * specific state machine from its list of possible recipients of
1448 * tethering requests. The state machine itself will hang around until
1449 * the garbage collector finds it.
1450 */
1451 class UnavailableState extends State {
1452 @Override
1453 public void enter() {
h.zhangd244bd02020-06-14 14:46:54 +08001454 mIpNeighborMonitor.stop();
markchien9b4d7572019-12-25 19:40:32 +08001455 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001456 sendInterfaceState(STATE_UNAVAILABLE);
1457 }
1458 }
1459
markchienc9daba32020-02-12 00:19:21 +08001460 class WaitingForRestartState extends State {
1461 @Override
1462 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001463 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001464 switch (message.what) {
1465 case CMD_TETHER_UNREQUESTED:
1466 transitionTo(mInitialState);
1467 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1468 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1469 break;
1470 case CMD_INTERFACE_DOWN:
1471 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001472 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001473 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1474 break;
1475 default:
1476 return false;
1477 }
1478 return true;
1479 }
1480 }
1481
markchien74a4fa92019-09-09 20:50:49 +08001482 // Accumulate routes representing "prefixes to be assigned to the local
1483 // interface", for subsequent modification of local_network routing.
1484 private static ArrayList<RouteInfo> getLocalRoutesFor(
1485 String ifname, HashSet<IpPrefix> prefixes) {
1486 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1487 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001488 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001489 }
1490 return localRoutes;
1491 }
1492
1493 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1494 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1495 final byte[] dnsBytes = localPrefix.getRawAddress();
1496 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1497 try {
1498 return Inet6Address.getByAddress(null, dnsBytes, 0);
1499 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001500 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001501 return null;
1502 }
1503 }
1504
1505 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1506 final byte random = (byte) (new Random()).nextInt();
1507 for (int value : excluded) {
1508 if (random == value) return dflt;
1509 }
1510 return random;
1511 }
1512}