blob: acd2625b1900a5d2e99132e3ee0aded677fdf1d3 [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;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090047import android.net.ip.IpNeighborMonitor.NeighborEvent;
markchien74a4fa92019-09-09 20:50:49 +080048import android.net.ip.RouterAdvertisementDaemon.RaParams;
markchien74a4fa92019-09-09 20:50:49 +080049import android.net.util.SharedLog;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090050import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080051import android.os.Looper;
52import android.os.Message;
53import android.os.RemoteException;
54import android.os.ServiceSpecificException;
55import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080056import android.util.SparseArray;
57
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090058import androidx.annotation.NonNull;
Xiao Ma4455d6b2020-04-09 10:13:44 +090059import androidx.annotation.Nullable;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090060
markchien74a4fa92019-09-09 20:50:49 +080061import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080062import com.android.internal.util.State;
63import com.android.internal.util.StateMachine;
markchien932df542021-08-12 13:56:43 +080064import com.android.modules.utils.build.SdkLevel;
Patrick Rohr9f371f02022-03-04 15:14:27 +010065import com.android.net.module.util.InterfaceParams;
Chalard Jeanadcec9e2021-10-29 15:57:22 +090066import com.android.net.module.util.NetdUtils;
Hungming Chen68f1c2a2020-03-12 21:24:01 +080067import com.android.networkstack.tethering.BpfCoordinator;
Hungming Chend71c06e2020-12-21 19:39:49 +080068import com.android.networkstack.tethering.BpfCoordinator.ClientInfo;
Hungming Chenb150b872020-05-23 22:54:49 +080069import com.android.networkstack.tethering.BpfCoordinator.Ipv6ForwardingRule;
markchienc9daba32020-02-12 00:19:21 +080070import com.android.networkstack.tethering.PrivateAddressCoordinator;
markchienb961d3d2022-02-26 00:39:06 +080071import com.android.networkstack.tethering.TetheringConfiguration;
markchiend02f9af2021-11-04 11:26:03 +080072import com.android.networkstack.tethering.util.InterfaceSet;
73import com.android.networkstack.tethering.util.PrefixUtils;
markchien74a4fa92019-09-09 20:50:49 +080074
75import java.net.Inet4Address;
76import java.net.Inet6Address;
markchien74a4fa92019-09-09 20:50:49 +080077import java.net.UnknownHostException;
78import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090079import java.util.Arrays;
80import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080081import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090082import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080083import java.util.Objects;
84import java.util.Random;
85import java.util.Set;
86
87/**
88 * Provides the interface to IP-layer serving functionality for a given network
89 * interface, e.g. for tethering or "local-only hotspot" mode.
90 *
91 * @hide
92 */
93public class IpServer extends StateMachine {
94 public static final int STATE_UNAVAILABLE = 0;
95 public static final int STATE_AVAILABLE = 1;
96 public static final int STATE_TETHERED = 2;
97 public static final int STATE_LOCAL_ONLY = 3;
98
99 /** Get string name of |state|.*/
100 public static String getStateString(int state) {
101 switch (state) {
102 case STATE_UNAVAILABLE: return "UNAVAILABLE";
103 case STATE_AVAILABLE: return "AVAILABLE";
104 case STATE_TETHERED: return "TETHERED";
105 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
106 }
107 return "UNKNOWN: " + state;
108 }
109
110 private static final byte DOUG_ADAMS = (byte) 42;
111
markchien74a4fa92019-09-09 20:50:49 +0800112 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800113 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800114
115 // TODO: have this configurable
116 private static final int DHCP_LEASE_TIME_SECS = 3600;
117
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900118 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
119
markchien74a4fa92019-09-09 20:50:49 +0800120 private static final String TAG = "IpServer";
121 private static final boolean DBG = false;
122 private static final boolean VDBG = false;
123 private static final Class[] sMessageClasses = {
124 IpServer.class
125 };
126 private static final SparseArray<String> sMagicDecoderRing =
127 MessageUtils.findMessageNames(sMessageClasses);
128
129 /** IpServer callback. */
130 public static class Callback {
131 /**
132 * Notify that |who| has changed its tethering state.
133 *
134 * @param who the calling instance of IpServer
135 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800136 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800137 */
markchien9d353822019-12-16 20:15:20 +0800138 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800139
140 /**
141 * Notify that |who| has new LinkProperties.
142 *
143 * @param who the calling instance of IpServer
144 * @param newLp the new LinkProperties to report
145 */
markchien9d353822019-12-16 20:15:20 +0800146 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900147
148 /**
149 * Notify that the DHCP leases changed in one of the IpServers.
150 */
151 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800152
153 /**
154 * Request Tethering change.
155 *
156 * @param tetheringType the downstream type of this IpServer.
157 * @param enabled enable or disable tethering.
158 */
159 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800160 }
161
162 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800163 public abstract static class Dependencies {
Tyler Wear90e40632020-03-13 11:38:38 -0700164 /**
165 * Create a DadProxy instance to be used by IpServer.
166 * To support multiple tethered interfaces concurrently DAD Proxy
167 * needs to be supported per IpServer instead of per upstream.
168 */
169 public DadProxy getDadProxy(Handler handler, InterfaceParams ifParams) {
170 return new DadProxy(handler, ifParams);
171 }
172
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900173 /** Create an IpNeighborMonitor to be used by this IpServer */
174 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
175 IpNeighborMonitor.NeighborEventConsumer consumer) {
176 return new IpNeighborMonitor(handler, log, consumer);
177 }
178
markchien74a4fa92019-09-09 20:50:49 +0800179 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
180 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
181 return new RouterAdvertisementDaemon(ifParams);
182 }
183
184 /** Get |ifName|'s interface information.*/
185 public InterfaceParams getInterfaceParams(String ifName) {
186 return InterfaceParams.getByName(ifName);
187 }
188
markchien9d353822019-12-16 20:15:20 +0800189 /** Create a DhcpServer instance to be used by IpServer. */
190 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
191 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800192 }
193
markchien74a4fa92019-09-09 20:50:49 +0800194 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800195 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800196 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800197 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800198 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800199 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800200 // notification from the {@link Tethering.TetherMainSM} that it had trouble enabling IP
201 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800202 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800203 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble disabling IP
204 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800205 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800206 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble starting
207 // tethering
markchien6cf0e552019-12-06 15:24:53 +0800208 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800209 // notification from the {@link Tethering.TetherMainSM} that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800210 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800211 // notification from the {@link Tethering.TetherMainSM} that it had trouble setting the DNS
212 // forwarders
markchien6cf0e552019-12-06 15:24:53 +0800213 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800214 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800215 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800216 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800217 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900218 // new neighbor cache entry on our interface
219 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900220 // request from DHCP server that it wants to have a new prefix
221 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800222 // request from PrivateAddressCoordinator to restart tethering.
223 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
markchien74a4fa92019-09-09 20:50:49 +0800224
225 private final State mInitialState;
226 private final State mLocalHotspotState;
227 private final State mTetheredState;
228 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800229 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800230
231 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800232 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800233 @NonNull
234 private final BpfCoordinator mBpfCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800235 private final Callback mCallback;
236 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800237 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800238
239 private final String mIfaceName;
240 private final int mInterfaceType;
241 private final LinkProperties mLinkProperties;
242 private final boolean mUsingLegacyDhcp;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800243 private final boolean mUsingBpfOffload;
markchien74a4fa92019-09-09 20:50:49 +0800244
245 private final Dependencies mDeps;
246
247 private int mLastError;
248 private int mServingMode;
249 private InterfaceSet mUpstreamIfaceSet; // may change over time
250 private InterfaceParams mInterfaceParams;
251 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
252 // properties are those selected by the IPv6TetheringCoordinator and relayed
253 // to us. By comparison, mLinkProperties contains the addresses and directly
254 // connected routes that have been formed from these properties iff. we have
255 // succeeded in configuring them and are able to announce them within Router
256 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
257 private LinkProperties mLastIPv6LinkProperties;
258 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700259 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800260
261 // To be accessed only on the handler thread
262 private int mDhcpServerStartIndex = 0;
263 private IDhcpServer mDhcpServer;
264 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800265
266 private LinkAddress mStaticIpv4ServerAddr;
267 private LinkAddress mStaticIpv4ClientAddr;
268
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900269 @NonNull
270 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800271
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900272 private int mLastIPv6UpstreamIfindex = 0;
273
274 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
275 public void accept(NeighborEvent e) {
276 sendMessage(CMD_NEIGHBOR_EVENT, e);
277 }
278 }
279
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900280 private final IpNeighborMonitor mIpNeighborMonitor;
281
markchienc9daba32020-02-12 00:19:21 +0800282 private LinkAddress mIpv4Address;
283
Hungming Chen5bc3af92020-05-12 19:15:24 +0800284 // TODO: Add a dependency object to pass the data members or variables from the tethering
285 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800286 public IpServer(
287 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800288 INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
markchienb961d3d2022-02-26 00:39:06 +0800289 TetheringConfiguration config, PrivateAddressCoordinator addressCoordinator,
290 Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800291 super(ifaceName, looper);
292 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800293 mNetd = netd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800294 mBpfCoordinator = coordinator;
markchien74a4fa92019-09-09 20:50:49 +0800295 mCallback = callback;
296 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
297 mIfaceName = ifaceName;
298 mInterfaceType = interfaceType;
299 mLinkProperties = new LinkProperties();
markchienb961d3d2022-02-26 00:39:06 +0800300 mUsingLegacyDhcp = config.useLegacyDhcpServer();
301 mUsingBpfOffload = config.isBpfOffloadEnabled();
markchienc9daba32020-02-12 00:19:21 +0800302 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800303 mDeps = deps;
304 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800305 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800306 mServingMode = STATE_AVAILABLE;
307
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900308 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
309 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800310
Hungming Chen5bc3af92020-05-12 19:15:24 +0800311 // IP neighbor monitor monitors the neighbor events for adding/removing offload
Hungming Chen3d8fa882020-04-12 14:27:18 +0800312 // forwarding rules per client. If BPF offload is not supported, don't start listening
Hungming Chen5bc3af92020-05-12 19:15:24 +0800313 // for neighbor events. See updateIpv6ForwardingRules, addIpv6ForwardingRule,
Hungming Chen3d8fa882020-04-12 14:27:18 +0800314 // removeIpv6ForwardingRule.
Hungming Chen5bc3af92020-05-12 19:15:24 +0800315 if (mUsingBpfOffload && !mIpNeighborMonitor.start()) {
316 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900317 }
318
markchien74a4fa92019-09-09 20:50:49 +0800319 mInitialState = new InitialState();
320 mLocalHotspotState = new LocalHotspotState();
321 mTetheredState = new TetheredState();
322 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800323 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800324 addState(mInitialState);
325 addState(mLocalHotspotState);
326 addState(mTetheredState);
markchienc9daba32020-02-12 00:19:21 +0800327 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800328 addState(mUnavailableState);
329
330 setInitialState(mInitialState);
331 }
332
333 /** Interface name which IpServer served.*/
334 public String interfaceName() {
335 return mIfaceName;
336 }
337
338 /**
markchien9b4d7572019-12-25 19:40:32 +0800339 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800340 */
341 public int interfaceType() {
342 return mInterfaceType;
343 }
344
345 /** Last error from this IpServer. */
346 public int lastError() {
347 return mLastError;
348 }
349
350 /** Serving mode is the current state of IpServer state machine. */
351 public int servingMode() {
352 return mServingMode;
353 }
354
355 /** The properties of the network link which IpServer is serving. */
356 public LinkProperties linkProperties() {
357 return new LinkProperties(mLinkProperties);
358 }
359
markchienc9daba32020-02-12 00:19:21 +0800360 /** The address which IpServer is using. */
361 public LinkAddress getAddress() {
362 return mIpv4Address;
363 }
364
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900365 /**
366 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
367 * thread.
368 */
369 public List<TetheredClient> getAllLeases() {
370 return Collections.unmodifiableList(mDhcpLeases);
371 }
372
markchien74a4fa92019-09-09 20:50:49 +0800373 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
374 public void stop() {
375 sendMessage(CMD_INTERFACE_DOWN);
376 }
377
378 /**
379 * Tethering is canceled. IpServer state machine will be available and wait for
380 * next tethering request.
381 */
382 public void unwanted() {
383 sendMessage(CMD_TETHER_UNREQUESTED);
384 }
385
386 /** Internals. */
387
388 private boolean startIPv4() {
389 return configureIPv4(true);
390 }
391
392 /**
393 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
394 * handler.
395 *
396 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
397 * with different implementations of the callback, to differentiate handling of success/error in
398 * each call.
399 */
400 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
401 @Override
402 public void onStatusAvailable(int statusCode) {
403 getHandler().post(() -> callback(statusCode));
404 }
405
406 public abstract void callback(int statusCode);
407
408 @Override
409 public int getInterfaceVersion() {
410 return this.VERSION;
411 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900412
413 @Override
414 public String getInterfaceHash() {
415 return this.HASH;
416 }
markchien74a4fa92019-09-09 20:50:49 +0800417 }
418
419 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
420 private final int mStartIndex;
421
422 private DhcpServerCallbacksImpl(int startIndex) {
423 mStartIndex = startIndex;
424 }
425
426 @Override
427 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
428 getHandler().post(() -> {
429 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
430 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800431 // This start request is obsolete. Explicitly stop the DHCP server to shut
432 // down its thread. When the |server| binder token goes out of scope, the
433 // garbage collector will finalize it, which causes the network stack process
434 // garbage collector to collect the server itself.
435 try {
436 server.stop(null);
437 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800438 return;
439 }
440
441 if (statusCode != STATUS_SUCCESS) {
442 mLog.e("Error obtaining DHCP server: " + statusCode);
443 handleError();
444 return;
445 }
446
447 mDhcpServer = server;
448 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900449 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800450 @Override
451 public void callback(int startStatusCode) {
452 if (startStatusCode != STATUS_SUCCESS) {
453 mLog.e("Error starting DHCP server: " + startStatusCode);
454 handleError();
455 }
456 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900457 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800458 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800459 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800460 }
461 });
462 }
463
464 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800465 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800466 transitionTo(mInitialState);
467 }
468 }
469
Xiao Ma4455d6b2020-04-09 10:13:44 +0900470 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900471 @Override
472 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
473 final ArrayList<TetheredClient> leases = new ArrayList<>();
474 for (DhcpLeaseParcelable lease : leaseParcelables) {
475 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900476 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
477 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
478 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900479
480 final MacAddress macAddress;
481 try {
482 macAddress = MacAddress.fromBytes(lease.hwAddr);
483 } catch (IllegalArgumentException e) {
484 Log.wtf(TAG, "Invalid address received from DhcpServer: "
485 + Arrays.toString(lease.hwAddr));
486 return;
487 }
488
489 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900490 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900491 leases.add(new TetheredClient(
492 macAddress,
493 Collections.singletonList(addressInfo),
494 mInterfaceType));
495 }
496
497 getHandler().post(() -> {
498 mDhcpLeases = leases;
499 mCallback.dhcpLeasesChanged();
500 });
501 }
502
503 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900504 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
505 Objects.requireNonNull(currentPrefix);
506 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900507 }
508
509 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900510 public int getInterfaceVersion() {
511 return this.VERSION;
512 }
513
514 @Override
515 public String getInterfaceHash() throws RemoteException {
516 return this.HASH;
517 }
518 }
519
Xiao Ma4455d6b2020-04-09 10:13:44 +0900520 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
521 Objects.requireNonNull(ipv4Address);
522 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
523 }
524
525 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
526 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
527 @Nullable Inet4Address clientAddr) {
528 final boolean changePrefixOnDecline =
529 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
530 return new DhcpServingParamsParcelExt()
531 .setDefaultRouters(defaultRouter)
532 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
533 .setDnsServers(dnsServer)
534 .setServerAddr(serverAddr)
535 .setMetered(true)
536 .setSingleClientAddr(clientAddr)
537 .setChangePrefixOnDecline(changePrefixOnDecline);
538 // TODO: also advertise link MTU
539 }
540
markchien245352e2020-02-27 20:27:18 +0800541 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800542 if (mUsingLegacyDhcp) {
543 return true;
544 }
markchien245352e2020-02-27 20:27:18 +0800545
546 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800547 final Inet4Address clientAddr = clientLinkAddr == null ? null :
548 (Inet4Address) clientLinkAddr.getAddress();
549
Xiao Ma4455d6b2020-04-09 10:13:44 +0900550 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
551 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800552 mDhcpServerStartIndex++;
553 mDeps.makeDhcpServer(
554 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
555 return true;
556 }
557
558 private void stopDhcp() {
559 // Make all previous start requests obsolete so servers are not started later
560 mDhcpServerStartIndex++;
561
562 if (mDhcpServer != null) {
563 try {
564 mDhcpServer.stop(new OnHandlerStatusCallback() {
565 @Override
566 public void callback(int statusCode) {
567 if (statusCode != STATUS_SUCCESS) {
568 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800569 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800570 // Not much more we can do here
571 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900572 mDhcpLeases.clear();
573 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800574 }
575 });
576 mDhcpServer = null;
577 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900578 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800579 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800580 }
581 }
582 }
583
markchien245352e2020-02-27 20:27:18 +0800584 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
585 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800586 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800587 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800588 } else {
589 stopDhcp();
590 return true;
591 }
592 }
593
594 private void stopIPv4() {
595 configureIPv4(false);
596 // NOTE: All of configureIPv4() will be refactored out of existence
597 // into calls to InterfaceController, shared with startIPv4().
598 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800599 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800600 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800601 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800602 mStaticIpv4ServerAddr = null;
603 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800604 }
605
markchien74a4fa92019-09-09 20:50:49 +0800606 private boolean configureIPv4(boolean enabled) {
607 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
608
markchienc9daba32020-02-12 00:19:21 +0800609 if (enabled) {
markchiena2ffad82020-09-22 15:50:43 +0800610 mIpv4Address = requestIpv4Address(true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800611 }
612
613 if (mIpv4Address == null) {
614 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800615 return false;
markchien74a4fa92019-09-09 20:50:49 +0800616 }
617
markchien69681d62021-11-15 23:58:05 +0800618 if (shouldNotConfigureBluetoothInterface()) {
619 // Interface was already configured elsewhere, only start DHCP.
markchienc9daba32020-02-12 00:19:21 +0800620 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
621 }
622
623 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
624
markchien12c5bb82020-01-07 14:43:17 +0800625 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800626 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900627 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200628 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
629 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900630 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800631 // It is unclear whether the Bluetooth or USB stacks will manage their own
632 // state.
633 setIfaceUp = null;
634 } else {
635 setIfaceUp = enabled;
636 }
637 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
638 mLog.e("Error configuring interface");
639 if (!enabled) stopDhcp();
640 return false;
641 }
markchien74a4fa92019-09-09 20:50:49 +0800642
markchien74a4fa92019-09-09 20:50:49 +0800643 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800644 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900645 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800646 } else {
markchien12c5bb82020-01-07 14:43:17 +0800647 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900648 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800649 }
markchien245352e2020-02-27 20:27:18 +0800650 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800651 }
652
markchien69681d62021-11-15 23:58:05 +0800653 private boolean shouldNotConfigureBluetoothInterface() {
654 // Before T, bluetooth tethering configures the interface elsewhere.
655 return (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) && !SdkLevel.isAtLeastT();
656 }
657
markchiena2ffad82020-09-22 15:50:43 +0800658 private LinkAddress requestIpv4Address(final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800659 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800660
markchien69681d62021-11-15 23:58:05 +0800661 if (shouldNotConfigureBluetoothInterface()) return new LinkAddress(BLUETOOTH_IFACE_ADDR);
markchienc9daba32020-02-12 00:19:21 +0800662
markchiena2ffad82020-09-22 15:50:43 +0800663 return mPrivateAddressCoordinator.requestDownstreamAddress(this, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900664 }
665
markchien74a4fa92019-09-09 20:50:49 +0800666 private boolean startIPv6() {
667 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
668 if (mInterfaceParams == null) {
669 mLog.e("Failed to find InterfaceParams");
670 stopIPv6();
671 return false;
672 }
673
674 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
675 if (!mRaDaemon.start()) {
676 stopIPv6();
677 return false;
678 }
679
markchien932df542021-08-12 13:56:43 +0800680 if (SdkLevel.isAtLeastS()) {
Tyler Wear90e40632020-03-13 11:38:38 -0700681 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
682 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
683 }
684
markchien74a4fa92019-09-09 20:50:49 +0800685 return true;
686 }
687
688 private void stopIPv6() {
689 mInterfaceParams = null;
690 setRaParams(null);
691
692 if (mRaDaemon != null) {
693 mRaDaemon.stop();
694 mRaDaemon = null;
695 }
Tyler Wear90e40632020-03-13 11:38:38 -0700696
697 if (mDadProxy != null) {
698 mDadProxy.stop();
699 mDadProxy = null;
700 }
markchien74a4fa92019-09-09 20:50:49 +0800701 }
702
703 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
704 // LinkProperties. These have extraneous data filtered out and only the
705 // necessary prefixes included (per its prefix distribution policy).
706 //
707 // TODO: Evaluate using a data structure than is more directly suited to
708 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800709 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800710 if (mRaDaemon == null) return;
711
712 // Avoid unnecessary work on spurious updates.
713 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
714 return;
715 }
716
717 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700718 String upstreamIface = null;
719 InterfaceParams upstreamIfaceParams = null;
720 int upstreamIfIndex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800721
722 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700723 upstreamIface = v6only.getInterfaceName();
724 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
725 if (upstreamIfaceParams != null) {
726 upstreamIfIndex = upstreamIfaceParams.index;
727 }
markchien74a4fa92019-09-09 20:50:49 +0800728 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700729 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800730 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
731
markchiend63c4f32020-05-21 17:38:28 +0800732 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800733
734 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
735 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
736
737 final IpPrefix prefix = new IpPrefix(
738 linkAddr.getAddress(), linkAddr.getPrefixLength());
739 params.prefixes.add(prefix);
740
741 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
742 if (dnsServer != null) {
743 params.dnses.add(dnsServer);
744 }
745 }
746 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900747
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900748 // Add upstream index to name mapping. See the comment of the interface mapping update in
749 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
750 // timing issue. It prevents that the IPv6 capability is updated later than
751 // CMD_TETHER_CONNECTION_CHANGED.
752 mBpfCoordinator.addUpstreamNameToLookupTable(upstreamIfIndex, upstreamIface);
753
markchien74a4fa92019-09-09 20:50:49 +0800754 // If v6only is null, we pass in null to setRaParams(), which handles
755 // deprecation of any existing RA data.
756
757 setRaParams(params);
markchien7dc1b4d2021-07-13 17:12:56 +0800758 // Be aware that updateIpv6ForwardingRules use mLastIPv6LinkProperties, so this line should
759 // be eariler than updateIpv6ForwardingRules.
760 // TODO: avoid this dependencies and move this logic into BpfCoordinator.
markchien74a4fa92019-09-09 20:50:49 +0800761 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900762
Tyler Wear90e40632020-03-13 11:38:38 -0700763 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfIndex, null);
764 mLastIPv6UpstreamIfindex = upstreamIfIndex;
765 if (mDadProxy != null) {
766 mDadProxy.setUpstreamIface(upstreamIfaceParams);
767 }
markchien74a4fa92019-09-09 20:50:49 +0800768 }
769
Xiao Ma4455d6b2020-04-09 10:13:44 +0900770 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900771 final int removalFailures = NetdUtils.removeRoutesFromLocalNetwork(
Xiao Ma4455d6b2020-04-09 10:13:44 +0900772 mNetd, toBeRemoved);
773 if (removalFailures > 0) {
774 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
775 removalFailures));
776 }
777
778 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
779 }
780
781 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
782 try {
783 // It's safe to call networkAddInterface() even if
784 // the interface is already in the local_network.
785 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
786 try {
787 // Add routes from local network. Note that adding routes that
788 // already exist does not cause an error (EEXIST is silently ignored).
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900789 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900790 } catch (IllegalStateException e) {
791 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
792 return;
793 }
794 } catch (ServiceSpecificException | RemoteException e) {
795 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
796 return;
797 }
798
799 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
800 }
801
markchien74a4fa92019-09-09 20:50:49 +0800802 private void configureLocalIPv6Routes(
803 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
804 // [1] Remove the routes that are deprecated.
805 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900806 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800807 }
808
809 // [2] Add only the routes that have not previously been added.
810 if (newPrefixes != null && !newPrefixes.isEmpty()) {
811 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
812 if (mLastRaParams != null) {
813 addedPrefixes.removeAll(mLastRaParams.prefixes);
814 }
815
816 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900817 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800818 }
819 }
820 }
821
822 private void configureLocalIPv6Dns(
823 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
824 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
825 if (mNetd == null) {
826 if (newDnses != null) newDnses.clear();
827 mLog.e("No netd service instance available; not setting local IPv6 addresses");
828 return;
829 }
830
831 // [1] Remove deprecated local DNS IP addresses.
832 if (!deprecatedDnses.isEmpty()) {
833 for (Inet6Address dns : deprecatedDnses) {
834 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
835 mLog.e("Failed to remove local dns IP " + dns);
836 }
837
838 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
839 }
840 }
841
842 // [2] Add only the local DNS IP addresses that have not previously been added.
843 if (newDnses != null && !newDnses.isEmpty()) {
844 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
845 if (mLastRaParams != null) {
846 addedDnses.removeAll(mLastRaParams.dnses);
847 }
848
849 for (Inet6Address dns : addedDnses) {
850 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
851 mLog.e("Failed to add local dns IP " + dns);
852 newDnses.remove(dns);
853 }
854
855 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
856 }
857 }
858
859 try {
860 mNetd.tetherApplyDnsInterfaces();
861 } catch (ServiceSpecificException | RemoteException e) {
862 mLog.e("Failed to update local DNS caching server");
863 if (newDnses != null) newDnses.clear();
864 }
865 }
866
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900867 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800868 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
869 // offload is disabled. Add this check just in case.
870 // TODO: Perhaps remove this protection check.
871 if (!mUsingBpfOffload) return;
872
Hungming Chen269c0882020-05-06 14:57:35 +0800873 mBpfCoordinator.tetherOffloadRuleAdd(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900874 }
875
Hungming Chen269c0882020-05-06 14:57:35 +0800876 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800877 // TODO: Perhaps remove this protection check.
Hungming Chen269c0882020-05-06 14:57:35 +0800878 // See the related comment in #addIpv6ForwardingRule.
Hungming Chen3d8fa882020-04-12 14:27:18 +0800879 if (!mUsingBpfOffload) return;
880
Hungming Chen269c0882020-05-06 14:57:35 +0800881 mBpfCoordinator.tetherOffloadRuleRemove(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900882 }
883
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900884 private void clearIpv6ForwardingRules() {
Hungming Chen269c0882020-05-06 14:57:35 +0800885 if (!mUsingBpfOffload) return;
886
887 mBpfCoordinator.tetherOffloadRuleClear(this);
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900888 }
889
Hungming Chen269c0882020-05-06 14:57:35 +0800890 private void updateIpv6ForwardingRule(int newIfindex) {
891 // TODO: Perhaps remove this protection check.
892 // See the related comment in #addIpv6ForwardingRule.
893 if (!mUsingBpfOffload) return;
894
895 mBpfCoordinator.tetherOffloadRuleUpdate(this, newIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900896 }
897
markchien7dc1b4d2021-07-13 17:12:56 +0800898 private boolean isIpv6VcnNetworkInterface() {
899 if (mLastIPv6LinkProperties == null) return false;
900
901 return isVcnInterface(mLastIPv6LinkProperties.getInterfaceName());
902 }
903
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900904 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
905 // changes or if a neighbor event is received.
906 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
907 NeighborEvent e) {
markchien7dc1b4d2021-07-13 17:12:56 +0800908 // If no longer have an upstream or it is virtual network, clear forwarding rules and do
909 // nothing else.
910 // TODO: Rather than always clear rules, ensure whether ipv6 ever enable first.
911 if (upstreamIfindex == 0 || isIpv6VcnNetworkInterface()) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900912 clearIpv6ForwardingRules();
913 return;
914 }
915
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900916 // If the upstream interface has changed, remove all rules and re-add them with the new
917 // upstream interface.
918 if (prevUpstreamIfindex != upstreamIfindex) {
Hungming Chen269c0882020-05-06 14:57:35 +0800919 updateIpv6ForwardingRule(upstreamIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900920 }
921
922 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900923 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900924 if (e == null) return;
925 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
926 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
927 return;
928 }
929
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900930 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
931 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
932 // add rules with a null MAC, only delete them.
933 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900934 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900935 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900936 if (e.isValid()) {
937 addIpv6ForwardingRule(rule);
938 } else {
Hungming Chen269c0882020-05-06 14:57:35 +0800939 removeIpv6ForwardingRule(rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900940 }
941 }
942
Hungming Chend71c06e2020-12-21 19:39:49 +0800943 // TODO: consider moving into BpfCoordinator.
944 private void updateClientInfoIpv4(NeighborEvent e) {
945 // TODO: Perhaps remove this protection check.
946 // See the related comment in #addIpv6ForwardingRule.
947 if (!mUsingBpfOffload) return;
948
949 if (e == null) return;
950 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
951 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
952 return;
953 }
954
955 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
956 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
957 // IpServer never add clients with a null MAC, only delete them.
958 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
959 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
960 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
961 if (e.isValid()) {
962 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
963 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +0800964 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
965 }
966 }
967
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900968 private void handleNeighborEvent(NeighborEvent e) {
969 if (mInterfaceParams != null
970 && mInterfaceParams.index == e.ifindex
971 && mInterfaceParams.hasMacAddress) {
972 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
Hungming Chend71c06e2020-12-21 19:39:49 +0800973 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900974 }
975 }
976
Xiao Ma4455d6b2020-04-09 10:13:44 +0900977 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
978 if (!currentPrefix.contains(mIpv4Address.getAddress())
979 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
980 Log.e(TAG, "Invalid prefix: " + currentPrefix);
981 return;
982 }
983
984 final LinkAddress deprecatedLinkAddress = mIpv4Address;
markchiena2ffad82020-09-22 15:50:43 +0800985 mIpv4Address = requestIpv4Address(false);
markchienc9daba32020-02-12 00:19:21 +0800986 if (mIpv4Address == null) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900987 mLog.e("Fail to request a new downstream prefix");
988 return;
989 }
markchienc9daba32020-02-12 00:19:21 +0800990 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
Xiao Ma4455d6b2020-04-09 10:13:44 +0900991
992 // Add new IPv4 address on the interface.
993 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
994 mLog.e("Failed to add new IP " + srvAddr);
995 return;
996 }
997
998 // Remove deprecated routes from local network.
999 removeRoutesFromLocalNetwork(
1000 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1001 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1002
1003 // Add new routes to local network.
1004 addRoutesToLocalNetwork(
1005 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1006 mLinkProperties.addLinkAddress(mIpv4Address);
1007
1008 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1009 // listen on the interface configured with new IPv4 address, that results DNS validation
1010 // failure of downstream client even if appropriate routes have been configured.
1011 try {
1012 mNetd.tetherApplyDnsInterfaces();
1013 } catch (ServiceSpecificException | RemoteException e) {
1014 mLog.e("Failed to update local DNS caching server");
1015 return;
1016 }
1017 sendLinkProperties();
1018
1019 // Notify DHCP server that new prefix/route has been applied on IpServer.
1020 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1021 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1022 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1023 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1024 try {
1025 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1026 @Override
1027 public void callback(int statusCode) {
1028 if (statusCode != STATUS_SUCCESS) {
1029 mLog.e("Error updating DHCP serving params: " + statusCode);
1030 }
1031 }
1032 });
1033 } catch (RemoteException e) {
1034 mLog.e("Error updating DHCP serving params", e);
1035 }
1036 }
1037
markchiend63c4f32020-05-21 17:38:28 +08001038 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001039 try {
1040 int upstreamHopLimit = Integer.parseUnsignedInt(
1041 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001042 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001043 // Cap the hop limit to 255.
1044 return (byte) Integer.min(upstreamHopLimit, 255);
1045 } catch (Exception e) {
1046 mLog.e("Failed to find upstream interface hop limit", e);
1047 }
1048 return RaParams.DEFAULT_HOPLIMIT;
1049 }
1050
1051 private void setRaParams(RaParams newParams) {
1052 if (mRaDaemon != null) {
1053 final RaParams deprecatedParams =
1054 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1055
1056 configureLocalIPv6Routes(deprecatedParams.prefixes,
1057 (newParams != null) ? newParams.prefixes : null);
1058
1059 configureLocalIPv6Dns(deprecatedParams.dnses,
1060 (newParams != null) ? newParams.dnses : null);
1061
1062 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1063 }
1064
1065 mLastRaParams = newParams;
1066 }
1067
markchien21021ef2021-06-01 10:58:04 +08001068 private void maybeLogMessage(State state, int what) {
1069 switch (what) {
1070 // Suppress some CMD_* to avoid log flooding.
1071 case CMD_IPV6_TETHER_UPDATE:
1072 case CMD_NEIGHBOR_EVENT:
1073 break;
1074 default:
1075 mLog.log(state.getName() + " got "
1076 + sMagicDecoderRing.get(what, Integer.toString(what)));
1077 }
markchien74a4fa92019-09-09 20:50:49 +08001078 }
1079
1080 private void sendInterfaceState(int newInterfaceState) {
1081 mServingMode = newInterfaceState;
1082 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1083 sendLinkProperties();
1084 }
1085
1086 private void sendLinkProperties() {
1087 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1088 }
1089
1090 private void resetLinkProperties() {
1091 mLinkProperties.clear();
1092 mLinkProperties.setInterfaceName(mIfaceName);
1093 }
1094
markchienf053e4b2020-03-16 21:49:48 +08001095 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001096 // Ignore static address configuration if they are invalid or null. In theory, static
1097 // addresses should not be invalid here because TetheringManager do not allow caller to
1098 // specify invalid static address configuration.
1099 if (request == null || request.localIPv4Address == null
1100 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1101 request.localIPv4Address, request.staticClientAddress)) {
1102 return;
1103 }
markchienf053e4b2020-03-16 21:49:48 +08001104
1105 mStaticIpv4ServerAddr = request.localIPv4Address;
1106 mStaticIpv4ClientAddr = request.staticClientAddress;
1107 }
1108
markchien74a4fa92019-09-09 20:50:49 +08001109 class InitialState extends State {
1110 @Override
1111 public void enter() {
1112 sendInterfaceState(STATE_AVAILABLE);
1113 }
1114
1115 @Override
1116 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001117 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001118 switch (message.what) {
1119 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +08001120 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001121 switch (message.arg1) {
1122 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001123 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001124 transitionTo(mLocalHotspotState);
1125 break;
1126 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001127 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001128 transitionTo(mTetheredState);
1129 break;
1130 default:
1131 mLog.e("Invalid tethering interface serving state specified.");
1132 }
1133 break;
1134 case CMD_INTERFACE_DOWN:
1135 transitionTo(mUnavailableState);
1136 break;
1137 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001138 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001139 break;
1140 default:
1141 return NOT_HANDLED;
1142 }
1143 return HANDLED;
1144 }
1145 }
1146
Hungming Chen46c30b12020-10-15 17:25:36 +08001147 private void startConntrackMonitoring() {
1148 mBpfCoordinator.startMonitoring(this);
1149 }
1150
1151 private void stopConntrackMonitoring() {
1152 mBpfCoordinator.stopMonitoring(this);
1153 }
1154
markchien74a4fa92019-09-09 20:50:49 +08001155 class BaseServingState extends State {
1156 @Override
1157 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001158 startConntrackMonitoring();
1159
markchien74a4fa92019-09-09 20:50:49 +08001160 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001161 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001162 return;
1163 }
1164
1165 try {
markchienc9daba32020-02-12 00:19:21 +08001166 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001167 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001168 mLog.e("Error Tethering", e);
markchien9b4d7572019-12-25 19:40:32 +08001169 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001170 return;
1171 }
1172
1173 if (!startIPv6()) {
1174 mLog.e("Failed to startIPv6");
1175 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1176 return;
1177 }
1178 }
1179
1180 @Override
1181 public void exit() {
1182 // Note that at this point, we're leaving the tethered state. We can fail any
1183 // of these operations, but it doesn't really change that we have to try them
1184 // all in sequence.
1185 stopIPv6();
1186
1187 try {
markchien12c5bb82020-01-07 14:43:17 +08001188 NetdUtils.untetherInterface(mNetd, mIfaceName);
1189 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001190 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001191 mLog.e("Failed to untether interface: " + e);
1192 }
1193
1194 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001195 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001196
1197 resetLinkProperties();
1198 }
1199
1200 @Override
1201 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001202 switch (message.what) {
1203 case CMD_TETHER_UNREQUESTED:
1204 transitionTo(mInitialState);
1205 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1206 break;
1207 case CMD_INTERFACE_DOWN:
1208 transitionTo(mUnavailableState);
1209 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1210 break;
1211 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001212 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001213 sendLinkProperties();
1214 break;
1215 case CMD_IP_FORWARDING_ENABLE_ERROR:
1216 case CMD_IP_FORWARDING_DISABLE_ERROR:
1217 case CMD_START_TETHERING_ERROR:
1218 case CMD_STOP_TETHERING_ERROR:
1219 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien8146b562020-03-19 13:37:43 +08001220 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001221 transitionTo(mInitialState);
1222 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001223 case CMD_NEW_PREFIX_REQUEST:
1224 handleNewPrefixRequest((IpPrefix) message.obj);
1225 break;
markchienc9daba32020-02-12 00:19:21 +08001226 case CMD_NOTIFY_PREFIX_CONFLICT:
1227 mLog.i("restart tethering: " + mInterfaceType);
1228 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1229 transitionTo(mWaitingForRestartState);
1230 break;
markchien74a4fa92019-09-09 20:50:49 +08001231 default:
1232 return false;
1233 }
1234 return true;
1235 }
1236 }
1237
1238 // Handling errors in BaseServingState.enter() by transitioning is
1239 // problematic because transitioning during a multi-state jump yields
1240 // a Log.wtf(). Ultimately, there should be only one ServingState,
1241 // and forwarding and NAT rules should be handled by a coordinating
1242 // functional element outside of IpServer.
1243 class LocalHotspotState extends BaseServingState {
1244 @Override
1245 public void enter() {
1246 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001247 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001248 transitionTo(mInitialState);
1249 }
1250
1251 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1252 sendInterfaceState(STATE_LOCAL_ONLY);
1253 }
1254
1255 @Override
1256 public boolean processMessage(Message message) {
1257 if (super.processMessage(message)) return true;
1258
markchien21021ef2021-06-01 10:58:04 +08001259 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001260 switch (message.what) {
1261 case CMD_TETHER_REQUESTED:
1262 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1263 break;
1264 case CMD_TETHER_CONNECTION_CHANGED:
1265 // Ignored in local hotspot state.
1266 break;
1267 default:
1268 return false;
1269 }
1270 return true;
1271 }
1272 }
1273
1274 // Handling errors in BaseServingState.enter() by transitioning is
1275 // problematic because transitioning during a multi-state jump yields
1276 // a Log.wtf(). Ultimately, there should be only one ServingState,
1277 // and forwarding and NAT rules should be handled by a coordinating
1278 // functional element outside of IpServer.
1279 class TetheredState extends BaseServingState {
1280 @Override
1281 public void enter() {
1282 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001283 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001284 transitionTo(mInitialState);
1285 }
1286
1287 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1288 sendInterfaceState(STATE_TETHERED);
1289 }
1290
1291 @Override
1292 public void exit() {
1293 cleanupUpstream();
1294 super.exit();
1295 }
1296
Hungming Chena6e78692021-02-08 17:15:35 +08001297 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1298 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1299 // and behaviour. While upstream is switching from offload supported interface to
1300 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1301 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1302 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1303 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1304 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1305 // in the state machine. Once there is any case out whish is not covered by previous cases,
1306 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001307 private void cleanupUpstream() {
1308 if (mUpstreamIfaceSet == null) return;
1309
1310 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1311 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001312 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001313 }
1314
1315 private void cleanupUpstreamInterface(String upstreamIface) {
1316 // Note that we don't care about errors here.
1317 // Sometimes interfaces are gone before we get
1318 // to remove their rules, which generates errors.
1319 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001320 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001321 try {
markchien12c5bb82020-01-07 14:43:17 +08001322 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1323 } catch (RemoteException | ServiceSpecificException e) {
1324 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001325 }
1326 try {
markchien12c5bb82020-01-07 14:43:17 +08001327 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1328 } catch (RemoteException | ServiceSpecificException e) {
1329 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001330 }
1331 }
1332
1333 @Override
1334 public boolean processMessage(Message message) {
1335 if (super.processMessage(message)) return true;
1336
markchien21021ef2021-06-01 10:58:04 +08001337 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001338 switch (message.what) {
1339 case CMD_TETHER_REQUESTED:
1340 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1341 break;
1342 case CMD_TETHER_CONNECTION_CHANGED:
1343 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1344 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1345 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1346 break;
1347 }
1348
1349 if (newUpstreamIfaceSet == null) {
1350 cleanupUpstream();
1351 break;
1352 }
1353
1354 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1355 cleanupUpstreamInterface(removed);
1356 }
1357
1358 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1359 // This makes the call to cleanupUpstream() in the error
1360 // path for any interface neatly cleanup all the interfaces.
1361 mUpstreamIfaceSet = newUpstreamIfaceSet;
1362
1363 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001364 // Add upstream index to name mapping for the tether stats usage in the
1365 // coordinator. Although this mapping could be added by both class
1366 // Tethering and IpServer, adding mapping from IpServer guarantees that
1367 // the mapping is added before adding forwarding rules. That is because
1368 // there are different state machines in both classes. It is hard to
1369 // guarantee the link property update order between multiple state machines.
1370 // Note that both IPv4 and IPv6 interface may be added because
1371 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1372 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1373 // capability may be updated later. In that case, IPv6 interface mapping is
1374 // updated in updateUpstreamIPv6LinkProperties.
1375 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1376 final InterfaceParams upstreamIfaceParams =
1377 mDeps.getInterfaceParams(ifname);
1378 if (upstreamIfaceParams != null) {
1379 mBpfCoordinator.addUpstreamNameToLookupTable(
1380 upstreamIfaceParams.index, ifname);
1381 }
1382 }
1383
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001384 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001385 try {
markchien12c5bb82020-01-07 14:43:17 +08001386 mNetd.tetherAddForward(mIfaceName, ifname);
1387 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1388 } catch (RemoteException | ServiceSpecificException e) {
1389 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001390 cleanupUpstream();
markchien8146b562020-03-19 13:37:43 +08001391 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001392 transitionTo(mInitialState);
1393 return true;
1394 }
1395 }
1396 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001397 case CMD_NEIGHBOR_EVENT:
1398 handleNeighborEvent((NeighborEvent) message.obj);
1399 break;
markchien74a4fa92019-09-09 20:50:49 +08001400 default:
1401 return false;
1402 }
1403 return true;
1404 }
1405
1406 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1407 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1408 if (mUpstreamIfaceSet != null && newIfaces != null) {
1409 return mUpstreamIfaceSet.equals(newIfaces);
1410 }
1411 return false;
1412 }
1413
1414 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1415 if (mUpstreamIfaceSet == null) return new HashSet<>();
1416
1417 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1418 removed.removeAll(newIfaces.ifnames);
1419 return removed;
1420 }
1421
1422 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1423 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1424 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1425 return added;
1426 }
1427 }
1428
1429 /**
1430 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001431 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001432 * specific state machine from its list of possible recipients of
1433 * tethering requests. The state machine itself will hang around until
1434 * the garbage collector finds it.
1435 */
1436 class UnavailableState extends State {
1437 @Override
1438 public void enter() {
h.zhangd244bd02020-06-14 14:46:54 +08001439 mIpNeighborMonitor.stop();
markchien9b4d7572019-12-25 19:40:32 +08001440 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001441 sendInterfaceState(STATE_UNAVAILABLE);
1442 }
1443 }
1444
markchienc9daba32020-02-12 00:19:21 +08001445 class WaitingForRestartState extends State {
1446 @Override
1447 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001448 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001449 switch (message.what) {
1450 case CMD_TETHER_UNREQUESTED:
1451 transitionTo(mInitialState);
1452 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1453 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1454 break;
1455 case CMD_INTERFACE_DOWN:
1456 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001457 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001458 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1459 break;
1460 default:
1461 return false;
1462 }
1463 return true;
1464 }
1465 }
1466
markchien74a4fa92019-09-09 20:50:49 +08001467 // Accumulate routes representing "prefixes to be assigned to the local
1468 // interface", for subsequent modification of local_network routing.
1469 private static ArrayList<RouteInfo> getLocalRoutesFor(
1470 String ifname, HashSet<IpPrefix> prefixes) {
1471 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1472 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001473 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001474 }
1475 return localRoutes;
1476 }
1477
1478 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1479 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1480 final byte[] dnsBytes = localPrefix.getRawAddress();
1481 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1482 try {
1483 return Inet6Address.getByAddress(null, dnsBytes, 0);
1484 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001485 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001486 return null;
1487 }
1488 }
1489
1490 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1491 final byte random = (byte) (new Random()).nextInt();
1492 for (int value : excluded) {
1493 if (random == value) return dflt;
1494 }
1495 return random;
1496 }
1497}