blob: da7ca56463ed8d53314f5bd97605900a54e60af4 [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;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090049import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080050import android.os.Looper;
51import android.os.Message;
52import android.os.RemoteException;
53import android.os.ServiceSpecificException;
54import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080055import android.util.SparseArray;
56
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090057import androidx.annotation.NonNull;
Xiao Ma4455d6b2020-04-09 10:13:44 +090058import androidx.annotation.Nullable;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090059
markchien74a4fa92019-09-09 20:50:49 +080060import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080061import com.android.internal.util.State;
62import com.android.internal.util.StateMachine;
markchien932df542021-08-12 13:56:43 +080063import com.android.modules.utils.build.SdkLevel;
Patrick Rohr9f371f02022-03-04 15:14:27 +010064import com.android.net.module.util.InterfaceParams;
Chalard Jeanadcec9e2021-10-29 15:57:22 +090065import com.android.net.module.util.NetdUtils;
Patrick Rohrb873e252022-06-16 16:38:43 -070066import com.android.net.module.util.SharedLog;
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;
Wayne Ma6cd440f2022-03-14 18:04:33 +080072import com.android.networkstack.tethering.metrics.TetheringMetrics;
markchiend02f9af2021-11-04 11:26:03 +080073import com.android.networkstack.tethering.util.InterfaceSet;
74import com.android.networkstack.tethering.util.PrefixUtils;
markchien74a4fa92019-09-09 20:50:49 +080075
76import java.net.Inet4Address;
77import java.net.Inet6Address;
markchien74a4fa92019-09-09 20:50:49 +080078import java.net.UnknownHostException;
79import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090080import java.util.Arrays;
81import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080082import java.util.HashSet;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090083import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080084import java.util.Objects;
85import java.util.Random;
86import java.util.Set;
87
88/**
89 * Provides the interface to IP-layer serving functionality for a given network
90 * interface, e.g. for tethering or "local-only hotspot" mode.
91 *
92 * @hide
93 */
94public class IpServer extends StateMachine {
95 public static final int STATE_UNAVAILABLE = 0;
96 public static final int STATE_AVAILABLE = 1;
97 public static final int STATE_TETHERED = 2;
98 public static final int STATE_LOCAL_ONLY = 3;
99
100 /** Get string name of |state|.*/
101 public static String getStateString(int state) {
102 switch (state) {
103 case STATE_UNAVAILABLE: return "UNAVAILABLE";
104 case STATE_AVAILABLE: return "AVAILABLE";
105 case STATE_TETHERED: return "TETHERED";
106 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
107 }
108 return "UNKNOWN: " + state;
109 }
110
111 private static final byte DOUG_ADAMS = (byte) 42;
112
markchien74a4fa92019-09-09 20:50:49 +0800113 // TODO: have PanService use some visible version of this constant
markchienc9daba32020-02-12 00:19:21 +0800114 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1/24";
markchien74a4fa92019-09-09 20:50:49 +0800115
116 // TODO: have this configurable
117 private static final int DHCP_LEASE_TIME_SECS = 3600;
118
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900119 private static final MacAddress NULL_MAC_ADDRESS = MacAddress.fromString("00:00:00:00:00:00");
120
markchien74a4fa92019-09-09 20:50:49 +0800121 private static final String TAG = "IpServer";
122 private static final boolean DBG = false;
123 private static final boolean VDBG = false;
124 private static final Class[] sMessageClasses = {
125 IpServer.class
126 };
127 private static final SparseArray<String> sMagicDecoderRing =
128 MessageUtils.findMessageNames(sMessageClasses);
129
130 /** IpServer callback. */
131 public static class Callback {
132 /**
133 * Notify that |who| has changed its tethering state.
134 *
135 * @param who the calling instance of IpServer
136 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800137 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800138 */
markchien9d353822019-12-16 20:15:20 +0800139 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800140
141 /**
142 * Notify that |who| has new LinkProperties.
143 *
144 * @param who the calling instance of IpServer
145 * @param newLp the new LinkProperties to report
146 */
markchien9d353822019-12-16 20:15:20 +0800147 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900148
149 /**
150 * Notify that the DHCP leases changed in one of the IpServers.
151 */
152 public void dhcpLeasesChanged() { }
markchienc9daba32020-02-12 00:19:21 +0800153
154 /**
155 * Request Tethering change.
156 *
157 * @param tetheringType the downstream type of this IpServer.
158 * @param enabled enable or disable tethering.
159 */
160 public void requestEnableTethering(int tetheringType, boolean enabled) { }
markchien74a4fa92019-09-09 20:50:49 +0800161 }
162
163 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800164 public abstract static class Dependencies {
Tyler Wear90e40632020-03-13 11:38:38 -0700165 /**
166 * Create a DadProxy instance to be used by IpServer.
167 * To support multiple tethered interfaces concurrently DAD Proxy
168 * needs to be supported per IpServer instead of per upstream.
169 */
170 public DadProxy getDadProxy(Handler handler, InterfaceParams ifParams) {
171 return new DadProxy(handler, ifParams);
172 }
173
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900174 /** Create an IpNeighborMonitor to be used by this IpServer */
175 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
176 IpNeighborMonitor.NeighborEventConsumer consumer) {
177 return new IpNeighborMonitor(handler, log, consumer);
178 }
179
markchien74a4fa92019-09-09 20:50:49 +0800180 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
181 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
182 return new RouterAdvertisementDaemon(ifParams);
183 }
184
185 /** Get |ifName|'s interface information.*/
186 public InterfaceParams getInterfaceParams(String ifName) {
187 return InterfaceParams.getByName(ifName);
188 }
189
markchien9d353822019-12-16 20:15:20 +0800190 /** Create a DhcpServer instance to be used by IpServer. */
191 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
192 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800193 }
194
markchien74a4fa92019-09-09 20:50:49 +0800195 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800196 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800197 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800198 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800199 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800200 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800201 // notification from the {@link Tethering.TetherMainSM} that it had trouble enabling IP
202 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800203 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800204 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble disabling IP
205 // Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800206 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800207 // notification from the {@link Tethering.TetherMainSM} SM that it had trouble starting
208 // tethering
markchien6cf0e552019-12-06 15:24:53 +0800209 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800210 // notification from the {@link Tethering.TetherMainSM} that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800211 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
Chiachang Wang14aaefc2020-07-29 12:05:04 +0800212 // notification from the {@link Tethering.TetherMainSM} that it had trouble setting the DNS
213 // forwarders
markchien6cf0e552019-12-06 15:24:53 +0800214 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800215 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800216 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800217 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800218 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900219 // new neighbor cache entry on our interface
220 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
Xiao Ma4455d6b2020-04-09 10:13:44 +0900221 // request from DHCP server that it wants to have a new prefix
222 public static final int CMD_NEW_PREFIX_REQUEST = BASE_IPSERVER + 12;
markchienc9daba32020-02-12 00:19:21 +0800223 // request from PrivateAddressCoordinator to restart tethering.
224 public static final int CMD_NOTIFY_PREFIX_CONFLICT = BASE_IPSERVER + 13;
markchien74a4fa92019-09-09 20:50:49 +0800225
226 private final State mInitialState;
227 private final State mLocalHotspotState;
228 private final State mTetheredState;
229 private final State mUnavailableState;
markchienc9daba32020-02-12 00:19:21 +0800230 private final State mWaitingForRestartState;
markchien74a4fa92019-09-09 20:50:49 +0800231
232 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800233 private final INetd mNetd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800234 @NonNull
235 private final BpfCoordinator mBpfCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800236 private final Callback mCallback;
237 private final InterfaceController mInterfaceCtrl;
markchienc9daba32020-02-12 00:19:21 +0800238 private final PrivateAddressCoordinator mPrivateAddressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800239
240 private final String mIfaceName;
241 private final int mInterfaceType;
242 private final LinkProperties mLinkProperties;
243 private final boolean mUsingLegacyDhcp;
Hungming Chen3d8fa882020-04-12 14:27:18 +0800244 private final boolean mUsingBpfOffload;
markchienfb65dfe2022-02-25 23:14:58 +0800245 private final int mP2pLeasesSubnetPrefixLength;
markchien74a4fa92019-09-09 20:50:49 +0800246
247 private final Dependencies mDeps;
248
249 private int mLastError;
250 private int mServingMode;
251 private InterfaceSet mUpstreamIfaceSet; // may change over time
252 private InterfaceParams mInterfaceParams;
253 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
254 // properties are those selected by the IPv6TetheringCoordinator and relayed
255 // to us. By comparison, mLinkProperties contains the addresses and directly
256 // connected routes that have been formed from these properties iff. we have
257 // succeeded in configuring them and are able to announce them within Router
258 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
259 private LinkProperties mLastIPv6LinkProperties;
260 private RouterAdvertisementDaemon mRaDaemon;
Tyler Wear90e40632020-03-13 11:38:38 -0700261 private DadProxy mDadProxy;
markchien74a4fa92019-09-09 20:50:49 +0800262
263 // To be accessed only on the handler thread
264 private int mDhcpServerStartIndex = 0;
265 private IDhcpServer mDhcpServer;
266 private RaParams mLastRaParams;
markchienf053e4b2020-03-16 21:49:48 +0800267
268 private LinkAddress mStaticIpv4ServerAddr;
269 private LinkAddress mStaticIpv4ClientAddr;
270
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900271 @NonNull
272 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800273
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900274 private int mLastIPv6UpstreamIfindex = 0;
275
276 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
277 public void accept(NeighborEvent e) {
278 sendMessage(CMD_NEIGHBOR_EVENT, e);
279 }
280 }
281
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900282 private final IpNeighborMonitor mIpNeighborMonitor;
283
markchienc9daba32020-02-12 00:19:21 +0800284 private LinkAddress mIpv4Address;
285
Wayne Ma6cd440f2022-03-14 18:04:33 +0800286 private final TetheringMetrics mTetheringMetrics;
287
Hungming Chen5bc3af92020-05-12 19:15:24 +0800288 // TODO: Add a dependency object to pass the data members or variables from the tethering
289 // object. It helps to reduce the arguments of the constructor.
markchien74a4fa92019-09-09 20:50:49 +0800290 public IpServer(
291 String ifaceName, Looper looper, int interfaceType, SharedLog log,
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800292 INetd netd, @NonNull BpfCoordinator coordinator, Callback callback,
markchienb961d3d2022-02-26 00:39:06 +0800293 TetheringConfiguration config, PrivateAddressCoordinator addressCoordinator,
Wayne Ma6cd440f2022-03-14 18:04:33 +0800294 TetheringMetrics tetheringMetrics, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800295 super(ifaceName, looper);
296 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800297 mNetd = netd;
Hungming Chen68f1c2a2020-03-12 21:24:01 +0800298 mBpfCoordinator = coordinator;
markchien74a4fa92019-09-09 20:50:49 +0800299 mCallback = callback;
300 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
301 mIfaceName = ifaceName;
302 mInterfaceType = interfaceType;
303 mLinkProperties = new LinkProperties();
markchienb961d3d2022-02-26 00:39:06 +0800304 mUsingLegacyDhcp = config.useLegacyDhcpServer();
305 mUsingBpfOffload = config.isBpfOffloadEnabled();
markchienfb65dfe2022-02-25 23:14:58 +0800306 mP2pLeasesSubnetPrefixLength = config.getP2pLeasesSubnetPrefixLength();
markchienc9daba32020-02-12 00:19:21 +0800307 mPrivateAddressCoordinator = addressCoordinator;
markchien74a4fa92019-09-09 20:50:49 +0800308 mDeps = deps;
Wayne Ma6cd440f2022-03-14 18:04:33 +0800309 mTetheringMetrics = tetheringMetrics;
markchien74a4fa92019-09-09 20:50:49 +0800310 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800311 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800312 mServingMode = STATE_AVAILABLE;
313
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900314 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
315 new MyNeighborEventConsumer());
Hungming Chen3d8fa882020-04-12 14:27:18 +0800316
Hungming Chen5bc3af92020-05-12 19:15:24 +0800317 // IP neighbor monitor monitors the neighbor events for adding/removing offload
Hungming Chen3d8fa882020-04-12 14:27:18 +0800318 // forwarding rules per client. If BPF offload is not supported, don't start listening
Hungming Chen5bc3af92020-05-12 19:15:24 +0800319 // for neighbor events. See updateIpv6ForwardingRules, addIpv6ForwardingRule,
Hungming Chen3d8fa882020-04-12 14:27:18 +0800320 // removeIpv6ForwardingRule.
Hungming Chen5bc3af92020-05-12 19:15:24 +0800321 if (mUsingBpfOffload && !mIpNeighborMonitor.start()) {
322 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900323 }
324
markchien74a4fa92019-09-09 20:50:49 +0800325 mInitialState = new InitialState();
326 mLocalHotspotState = new LocalHotspotState();
327 mTetheredState = new TetheredState();
328 mUnavailableState = new UnavailableState();
markchienc9daba32020-02-12 00:19:21 +0800329 mWaitingForRestartState = new WaitingForRestartState();
markchien74a4fa92019-09-09 20:50:49 +0800330 addState(mInitialState);
331 addState(mLocalHotspotState);
332 addState(mTetheredState);
markchienc9daba32020-02-12 00:19:21 +0800333 addState(mWaitingForRestartState, mTetheredState);
markchien74a4fa92019-09-09 20:50:49 +0800334 addState(mUnavailableState);
335
336 setInitialState(mInitialState);
337 }
338
339 /** Interface name which IpServer served.*/
340 public String interfaceName() {
341 return mIfaceName;
342 }
343
344 /**
markchien9b4d7572019-12-25 19:40:32 +0800345 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800346 */
347 public int interfaceType() {
348 return mInterfaceType;
349 }
350
351 /** Last error from this IpServer. */
352 public int lastError() {
353 return mLastError;
354 }
355
356 /** Serving mode is the current state of IpServer state machine. */
357 public int servingMode() {
358 return mServingMode;
359 }
360
361 /** The properties of the network link which IpServer is serving. */
362 public LinkProperties linkProperties() {
363 return new LinkProperties(mLinkProperties);
364 }
365
markchienc9daba32020-02-12 00:19:21 +0800366 /** The address which IpServer is using. */
367 public LinkAddress getAddress() {
368 return mIpv4Address;
369 }
370
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900371 /**
372 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
373 * thread.
374 */
375 public List<TetheredClient> getAllLeases() {
376 return Collections.unmodifiableList(mDhcpLeases);
377 }
378
markchien74a4fa92019-09-09 20:50:49 +0800379 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
380 public void stop() {
381 sendMessage(CMD_INTERFACE_DOWN);
382 }
383
384 /**
385 * Tethering is canceled. IpServer state machine will be available and wait for
386 * next tethering request.
387 */
388 public void unwanted() {
389 sendMessage(CMD_TETHER_UNREQUESTED);
390 }
391
392 /** Internals. */
393
394 private boolean startIPv4() {
395 return configureIPv4(true);
396 }
397
398 /**
399 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
400 * handler.
401 *
402 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
403 * with different implementations of the callback, to differentiate handling of success/error in
404 * each call.
405 */
406 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
407 @Override
408 public void onStatusAvailable(int statusCode) {
409 getHandler().post(() -> callback(statusCode));
410 }
411
412 public abstract void callback(int statusCode);
413
414 @Override
415 public int getInterfaceVersion() {
416 return this.VERSION;
417 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900418
419 @Override
420 public String getInterfaceHash() {
421 return this.HASH;
422 }
markchien74a4fa92019-09-09 20:50:49 +0800423 }
424
425 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
426 private final int mStartIndex;
427
428 private DhcpServerCallbacksImpl(int startIndex) {
429 mStartIndex = startIndex;
430 }
431
432 @Override
433 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
434 getHandler().post(() -> {
435 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
436 if (mStartIndex != mDhcpServerStartIndex) {
markchienaf2670f2020-07-22 21:28:48 +0800437 // This start request is obsolete. Explicitly stop the DHCP server to shut
438 // down its thread. When the |server| binder token goes out of scope, the
439 // garbage collector will finalize it, which causes the network stack process
440 // garbage collector to collect the server itself.
441 try {
442 server.stop(null);
443 } catch (RemoteException e) { }
markchien74a4fa92019-09-09 20:50:49 +0800444 return;
445 }
446
447 if (statusCode != STATUS_SUCCESS) {
448 mLog.e("Error obtaining DHCP server: " + statusCode);
449 handleError();
450 return;
451 }
452
453 mDhcpServer = server;
454 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900455 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800456 @Override
457 public void callback(int startStatusCode) {
458 if (startStatusCode != STATUS_SUCCESS) {
459 mLog.e("Error starting DHCP server: " + startStatusCode);
460 handleError();
461 }
462 }
Xiao Ma4455d6b2020-04-09 10:13:44 +0900463 }, new DhcpEventCallback());
markchien74a4fa92019-09-09 20:50:49 +0800464 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800465 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800466 }
467 });
468 }
469
470 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800471 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800472 transitionTo(mInitialState);
473 }
474 }
475
Xiao Ma4455d6b2020-04-09 10:13:44 +0900476 private class DhcpEventCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900477 @Override
478 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
479 final ArrayList<TetheredClient> leases = new ArrayList<>();
480 for (DhcpLeaseParcelable lease : leaseParcelables) {
481 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900482 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
483 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
484 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900485
486 final MacAddress macAddress;
487 try {
488 macAddress = MacAddress.fromBytes(lease.hwAddr);
489 } catch (IllegalArgumentException e) {
490 Log.wtf(TAG, "Invalid address received from DhcpServer: "
491 + Arrays.toString(lease.hwAddr));
492 return;
493 }
494
495 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900496 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900497 leases.add(new TetheredClient(
498 macAddress,
499 Collections.singletonList(addressInfo),
500 mInterfaceType));
501 }
502
503 getHandler().post(() -> {
504 mDhcpLeases = leases;
505 mCallback.dhcpLeasesChanged();
506 });
507 }
508
509 @Override
Xiao Ma4455d6b2020-04-09 10:13:44 +0900510 public void onNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
511 Objects.requireNonNull(currentPrefix);
512 sendMessage(CMD_NEW_PREFIX_REQUEST, currentPrefix);
Xiao Ma49889dd2020-04-03 17:01:33 +0900513 }
514
515 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900516 public int getInterfaceVersion() {
517 return this.VERSION;
518 }
519
520 @Override
521 public String getInterfaceHash() throws RemoteException {
522 return this.HASH;
523 }
524 }
525
Xiao Ma4455d6b2020-04-09 10:13:44 +0900526 private RouteInfo getDirectConnectedRoute(@NonNull final LinkAddress ipv4Address) {
527 Objects.requireNonNull(ipv4Address);
528 return new RouteInfo(PrefixUtils.asIpPrefix(ipv4Address), null, mIfaceName, RTN_UNICAST);
529 }
530
531 private DhcpServingParamsParcel makeServingParams(@NonNull final Inet4Address defaultRouter,
532 @NonNull final Inet4Address dnsServer, @NonNull LinkAddress serverAddr,
533 @Nullable Inet4Address clientAddr) {
534 final boolean changePrefixOnDecline =
535 (mInterfaceType == TetheringManager.TETHERING_NCM && clientAddr == null);
markchienfb65dfe2022-02-25 23:14:58 +0800536 final int subnetPrefixLength = mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
537 ? mP2pLeasesSubnetPrefixLength : 0 /* default value */;
538
Xiao Ma4455d6b2020-04-09 10:13:44 +0900539 return new DhcpServingParamsParcelExt()
540 .setDefaultRouters(defaultRouter)
541 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
542 .setDnsServers(dnsServer)
543 .setServerAddr(serverAddr)
544 .setMetered(true)
545 .setSingleClientAddr(clientAddr)
markchienfb65dfe2022-02-25 23:14:58 +0800546 .setChangePrefixOnDecline(changePrefixOnDecline)
547 .setLeasesSubnetPrefixLength(subnetPrefixLength);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900548 // TODO: also advertise link MTU
549 }
550
markchien245352e2020-02-27 20:27:18 +0800551 private boolean startDhcp(final LinkAddress serverLinkAddr, final LinkAddress clientLinkAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800552 if (mUsingLegacyDhcp) {
553 return true;
554 }
markchien245352e2020-02-27 20:27:18 +0800555
556 final Inet4Address addr = (Inet4Address) serverLinkAddr.getAddress();
markchien245352e2020-02-27 20:27:18 +0800557 final Inet4Address clientAddr = clientLinkAddr == null ? null :
558 (Inet4Address) clientLinkAddr.getAddress();
559
Xiao Ma4455d6b2020-04-09 10:13:44 +0900560 final DhcpServingParamsParcel params = makeServingParams(addr /* defaultRouter */,
561 addr /* dnsServer */, serverLinkAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800562 mDhcpServerStartIndex++;
563 mDeps.makeDhcpServer(
564 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
565 return true;
566 }
567
568 private void stopDhcp() {
569 // Make all previous start requests obsolete so servers are not started later
570 mDhcpServerStartIndex++;
571
572 if (mDhcpServer != null) {
573 try {
574 mDhcpServer.stop(new OnHandlerStatusCallback() {
575 @Override
576 public void callback(int statusCode) {
577 if (statusCode != STATUS_SUCCESS) {
578 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800579 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800580 // Not much more we can do here
581 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900582 mDhcpLeases.clear();
583 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800584 }
585 });
586 mDhcpServer = null;
587 } catch (RemoteException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900588 mLog.e("Error stopping DHCP server", e);
markchien12c5bb82020-01-07 14:43:17 +0800589 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800590 }
591 }
592 }
593
markchien245352e2020-02-27 20:27:18 +0800594 private boolean configureDhcp(boolean enable, final LinkAddress serverAddr,
595 final LinkAddress clientAddr) {
markchien74a4fa92019-09-09 20:50:49 +0800596 if (enable) {
markchien245352e2020-02-27 20:27:18 +0800597 return startDhcp(serverAddr, clientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800598 } else {
599 stopDhcp();
600 return true;
601 }
602 }
603
604 private void stopIPv4() {
605 configureIPv4(false);
606 // NOTE: All of configureIPv4() will be refactored out of existence
607 // into calls to InterfaceController, shared with startIPv4().
608 mInterfaceCtrl.clearIPv4Address();
markchienc9daba32020-02-12 00:19:21 +0800609 mPrivateAddressCoordinator.releaseDownstream(this);
Hungming Chena6e78692021-02-08 17:15:35 +0800610 mBpfCoordinator.tetherOffloadClientClear(this);
markchien12c5bb82020-01-07 14:43:17 +0800611 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800612 mStaticIpv4ServerAddr = null;
613 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800614 }
615
markchien74a4fa92019-09-09 20:50:49 +0800616 private boolean configureIPv4(boolean enabled) {
617 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
618
markchienc9daba32020-02-12 00:19:21 +0800619 if (enabled) {
markchiena2ffad82020-09-22 15:50:43 +0800620 mIpv4Address = requestIpv4Address(true /* useLastAddress */);
markchienc9daba32020-02-12 00:19:21 +0800621 }
622
623 if (mIpv4Address == null) {
624 mLog.e("No available ipv4 address");
markchien12c5bb82020-01-07 14:43:17 +0800625 return false;
markchien74a4fa92019-09-09 20:50:49 +0800626 }
627
markchien69681d62021-11-15 23:58:05 +0800628 if (shouldNotConfigureBluetoothInterface()) {
629 // Interface was already configured elsewhere, only start DHCP.
markchienc9daba32020-02-12 00:19:21 +0800630 return configureDhcp(enabled, mIpv4Address, null /* clientAddress */);
631 }
632
633 final IpPrefix ipv4Prefix = asIpPrefix(mIpv4Address);
634
markchien12c5bb82020-01-07 14:43:17 +0800635 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800636 if (mInterfaceType == TetheringManager.TETHERING_WIFI
Milim Lee98078162020-05-26 03:11:29 +0900637 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P
Dedy Lansky6896f612019-11-21 00:36:14 +0200638 || mInterfaceType == TetheringManager.TETHERING_ETHERNET
639 || mInterfaceType == TetheringManager.TETHERING_WIGIG) {
Milim Lee98078162020-05-26 03:11:29 +0900640 // The WiFi and Ethernet stack has ownership of the interface up/down state.
markchien12c5bb82020-01-07 14:43:17 +0800641 // It is unclear whether the Bluetooth or USB stacks will manage their own
642 // state.
643 setIfaceUp = null;
644 } else {
645 setIfaceUp = enabled;
646 }
647 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
648 mLog.e("Error configuring interface");
649 if (!enabled) stopDhcp();
650 return false;
651 }
markchien74a4fa92019-09-09 20:50:49 +0800652
markchien74a4fa92019-09-09 20:50:49 +0800653 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800654 mLinkProperties.addLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900655 mLinkProperties.addRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800656 } else {
markchien12c5bb82020-01-07 14:43:17 +0800657 mLinkProperties.removeLinkAddress(mIpv4Address);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900658 mLinkProperties.removeRoute(getDirectConnectedRoute(mIpv4Address));
markchien74a4fa92019-09-09 20:50:49 +0800659 }
markchien245352e2020-02-27 20:27:18 +0800660 return configureDhcp(enabled, mIpv4Address, mStaticIpv4ClientAddr);
markchien74a4fa92019-09-09 20:50:49 +0800661 }
662
markchien69681d62021-11-15 23:58:05 +0800663 private boolean shouldNotConfigureBluetoothInterface() {
664 // Before T, bluetooth tethering configures the interface elsewhere.
665 return (mInterfaceType == TetheringManager.TETHERING_BLUETOOTH) && !SdkLevel.isAtLeastT();
666 }
667
markchiena2ffad82020-09-22 15:50:43 +0800668 private LinkAddress requestIpv4Address(final boolean useLastAddress) {
markchienc9daba32020-02-12 00:19:21 +0800669 if (mStaticIpv4ServerAddr != null) return mStaticIpv4ServerAddr;
markchien74a4fa92019-09-09 20:50:49 +0800670
markchien69681d62021-11-15 23:58:05 +0800671 if (shouldNotConfigureBluetoothInterface()) return new LinkAddress(BLUETOOTH_IFACE_ADDR);
markchienc9daba32020-02-12 00:19:21 +0800672
markchiena2ffad82020-09-22 15:50:43 +0800673 return mPrivateAddressCoordinator.requestDownstreamAddress(this, useLastAddress);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900674 }
675
markchien74a4fa92019-09-09 20:50:49 +0800676 private boolean startIPv6() {
677 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
678 if (mInterfaceParams == null) {
679 mLog.e("Failed to find InterfaceParams");
680 stopIPv6();
681 return false;
682 }
683
684 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
685 if (!mRaDaemon.start()) {
686 stopIPv6();
687 return false;
688 }
689
markchien932df542021-08-12 13:56:43 +0800690 if (SdkLevel.isAtLeastS()) {
Tyler Wear90e40632020-03-13 11:38:38 -0700691 // DAD Proxy starts forwarding packets after IPv6 upstream is present.
692 mDadProxy = mDeps.getDadProxy(getHandler(), mInterfaceParams);
693 }
694
markchien74a4fa92019-09-09 20:50:49 +0800695 return true;
696 }
697
698 private void stopIPv6() {
699 mInterfaceParams = null;
700 setRaParams(null);
701
702 if (mRaDaemon != null) {
703 mRaDaemon.stop();
704 mRaDaemon = null;
705 }
Tyler Wear90e40632020-03-13 11:38:38 -0700706
707 if (mDadProxy != null) {
708 mDadProxy.stop();
709 mDadProxy = null;
710 }
markchien74a4fa92019-09-09 20:50:49 +0800711 }
712
713 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
714 // LinkProperties. These have extraneous data filtered out and only the
715 // necessary prefixes included (per its prefix distribution policy).
716 //
717 // TODO: Evaluate using a data structure than is more directly suited to
718 // communicating only the relevant information.
markchiend63c4f32020-05-21 17:38:28 +0800719 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only, int ttlAdjustment) {
markchien74a4fa92019-09-09 20:50:49 +0800720 if (mRaDaemon == null) return;
721
722 // Avoid unnecessary work on spurious updates.
723 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
724 return;
725 }
726
727 RaParams params = null;
Tyler Wear90e40632020-03-13 11:38:38 -0700728 String upstreamIface = null;
729 InterfaceParams upstreamIfaceParams = null;
730 int upstreamIfIndex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800731
732 if (v6only != null) {
Tyler Wear90e40632020-03-13 11:38:38 -0700733 upstreamIface = v6only.getInterfaceName();
734 upstreamIfaceParams = mDeps.getInterfaceParams(upstreamIface);
735 if (upstreamIfaceParams != null) {
736 upstreamIfIndex = upstreamIfaceParams.index;
737 }
markchien74a4fa92019-09-09 20:50:49 +0800738 params = new RaParams();
Maciej Żenczykowskif99d2a12020-05-28 03:21:31 -0700739 params.mtu = v6only.getMtu();
markchien74a4fa92019-09-09 20:50:49 +0800740 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
741
markchiend63c4f32020-05-21 17:38:28 +0800742 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface, ttlAdjustment);
markchien74a4fa92019-09-09 20:50:49 +0800743
744 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
745 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
746
747 final IpPrefix prefix = new IpPrefix(
748 linkAddr.getAddress(), linkAddr.getPrefixLength());
749 params.prefixes.add(prefix);
750
751 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
752 if (dnsServer != null) {
753 params.dnses.add(dnsServer);
754 }
755 }
756 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900757
Lorenzo Colittidc6715c2021-02-09 23:12:37 +0900758 // Add upstream index to name mapping. See the comment of the interface mapping update in
759 // CMD_TETHER_CONNECTION_CHANGED. Adding the mapping update here to the avoid potential
760 // timing issue. It prevents that the IPv6 capability is updated later than
761 // CMD_TETHER_CONNECTION_CHANGED.
762 mBpfCoordinator.addUpstreamNameToLookupTable(upstreamIfIndex, upstreamIface);
763
markchien74a4fa92019-09-09 20:50:49 +0800764 // If v6only is null, we pass in null to setRaParams(), which handles
765 // deprecation of any existing RA data.
766
767 setRaParams(params);
markchien7dc1b4d2021-07-13 17:12:56 +0800768 // Be aware that updateIpv6ForwardingRules use mLastIPv6LinkProperties, so this line should
769 // be eariler than updateIpv6ForwardingRules.
770 // TODO: avoid this dependencies and move this logic into BpfCoordinator.
markchien74a4fa92019-09-09 20:50:49 +0800771 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900772
Tyler Wear90e40632020-03-13 11:38:38 -0700773 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfIndex, null);
774 mLastIPv6UpstreamIfindex = upstreamIfIndex;
775 if (mDadProxy != null) {
776 mDadProxy.setUpstreamIface(upstreamIfaceParams);
777 }
markchien74a4fa92019-09-09 20:50:49 +0800778 }
779
Xiao Ma4455d6b2020-04-09 10:13:44 +0900780 private void removeRoutesFromLocalNetwork(@NonNull final List<RouteInfo> toBeRemoved) {
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900781 final int removalFailures = NetdUtils.removeRoutesFromLocalNetwork(
Xiao Ma4455d6b2020-04-09 10:13:44 +0900782 mNetd, toBeRemoved);
783 if (removalFailures > 0) {
784 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
785 removalFailures));
786 }
787
788 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
789 }
790
791 private void addRoutesToLocalNetwork(@NonNull final List<RouteInfo> toBeAdded) {
792 try {
793 // It's safe to call networkAddInterface() even if
794 // the interface is already in the local_network.
795 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
796 try {
797 // Add routes from local network. Note that adding routes that
798 // already exist does not cause an error (EEXIST is silently ignored).
Chalard Jeanadcec9e2021-10-29 15:57:22 +0900799 NetdUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
Xiao Ma4455d6b2020-04-09 10:13:44 +0900800 } catch (IllegalStateException e) {
801 mLog.e("Failed to add IPv4/v6 routes to local table: " + e);
802 return;
803 }
804 } catch (ServiceSpecificException | RemoteException e) {
805 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
806 return;
807 }
808
809 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
810 }
811
markchien74a4fa92019-09-09 20:50:49 +0800812 private void configureLocalIPv6Routes(
813 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
814 // [1] Remove the routes that are deprecated.
815 if (!deprecatedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900816 removeRoutesFromLocalNetwork(getLocalRoutesFor(mIfaceName, deprecatedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800817 }
818
819 // [2] Add only the routes that have not previously been added.
820 if (newPrefixes != null && !newPrefixes.isEmpty()) {
821 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
822 if (mLastRaParams != null) {
823 addedPrefixes.removeAll(mLastRaParams.prefixes);
824 }
825
826 if (!addedPrefixes.isEmpty()) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900827 addRoutesToLocalNetwork(getLocalRoutesFor(mIfaceName, addedPrefixes));
markchien74a4fa92019-09-09 20:50:49 +0800828 }
829 }
830 }
831
832 private void configureLocalIPv6Dns(
833 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
834 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
835 if (mNetd == null) {
836 if (newDnses != null) newDnses.clear();
837 mLog.e("No netd service instance available; not setting local IPv6 addresses");
838 return;
839 }
840
841 // [1] Remove deprecated local DNS IP addresses.
842 if (!deprecatedDnses.isEmpty()) {
843 for (Inet6Address dns : deprecatedDnses) {
844 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
845 mLog.e("Failed to remove local dns IP " + dns);
846 }
847
848 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
849 }
850 }
851
852 // [2] Add only the local DNS IP addresses that have not previously been added.
853 if (newDnses != null && !newDnses.isEmpty()) {
854 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
855 if (mLastRaParams != null) {
856 addedDnses.removeAll(mLastRaParams.dnses);
857 }
858
859 for (Inet6Address dns : addedDnses) {
860 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
861 mLog.e("Failed to add local dns IP " + dns);
862 newDnses.remove(dns);
863 }
864
865 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
866 }
867 }
868
869 try {
870 mNetd.tetherApplyDnsInterfaces();
871 } catch (ServiceSpecificException | RemoteException e) {
872 mLog.e("Failed to update local DNS caching server");
873 if (newDnses != null) newDnses.clear();
874 }
875 }
876
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900877 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800878 // Theoretically, we don't need this check because IP neighbor monitor doesn't start if BPF
879 // offload is disabled. Add this check just in case.
880 // TODO: Perhaps remove this protection check.
881 if (!mUsingBpfOffload) return;
882
Hungming Chen269c0882020-05-06 14:57:35 +0800883 mBpfCoordinator.tetherOffloadRuleAdd(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900884 }
885
Hungming Chen269c0882020-05-06 14:57:35 +0800886 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule) {
Hungming Chen3d8fa882020-04-12 14:27:18 +0800887 // TODO: Perhaps remove this protection check.
Hungming Chen269c0882020-05-06 14:57:35 +0800888 // See the related comment in #addIpv6ForwardingRule.
Hungming Chen3d8fa882020-04-12 14:27:18 +0800889 if (!mUsingBpfOffload) return;
890
Hungming Chen269c0882020-05-06 14:57:35 +0800891 mBpfCoordinator.tetherOffloadRuleRemove(this, rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900892 }
893
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900894 private void clearIpv6ForwardingRules() {
Hungming Chen269c0882020-05-06 14:57:35 +0800895 if (!mUsingBpfOffload) return;
896
897 mBpfCoordinator.tetherOffloadRuleClear(this);
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900898 }
899
Hungming Chen269c0882020-05-06 14:57:35 +0800900 private void updateIpv6ForwardingRule(int newIfindex) {
901 // TODO: Perhaps remove this protection check.
902 // See the related comment in #addIpv6ForwardingRule.
903 if (!mUsingBpfOffload) return;
904
905 mBpfCoordinator.tetherOffloadRuleUpdate(this, newIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900906 }
907
markchien7dc1b4d2021-07-13 17:12:56 +0800908 private boolean isIpv6VcnNetworkInterface() {
909 if (mLastIPv6LinkProperties == null) return false;
910
911 return isVcnInterface(mLastIPv6LinkProperties.getInterfaceName());
912 }
913
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900914 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
915 // changes or if a neighbor event is received.
916 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
917 NeighborEvent e) {
markchien7dc1b4d2021-07-13 17:12:56 +0800918 // If no longer have an upstream or it is virtual network, clear forwarding rules and do
919 // nothing else.
920 // TODO: Rather than always clear rules, ensure whether ipv6 ever enable first.
921 if (upstreamIfindex == 0 || isIpv6VcnNetworkInterface()) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900922 clearIpv6ForwardingRules();
923 return;
924 }
925
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900926 // If the upstream interface has changed, remove all rules and re-add them with the new
927 // upstream interface.
928 if (prevUpstreamIfindex != upstreamIfindex) {
Hungming Chen269c0882020-05-06 14:57:35 +0800929 updateIpv6ForwardingRule(upstreamIfindex);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900930 }
931
932 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900933 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900934 if (e == null) return;
935 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
936 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
937 return;
938 }
939
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900940 // When deleting rules, we still need to pass a non-null MAC, even though it's ignored.
941 // Do this here instead of in the Ipv6ForwardingRule constructor to ensure that we never
942 // add rules with a null MAC, only delete them.
943 MacAddress dstMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900944 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti330a9b92020-04-14 14:57:30 +0900945 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr, dstMac);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900946 if (e.isValid()) {
947 addIpv6ForwardingRule(rule);
948 } else {
Hungming Chen269c0882020-05-06 14:57:35 +0800949 removeIpv6ForwardingRule(rule);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900950 }
951 }
952
Hungming Chend71c06e2020-12-21 19:39:49 +0800953 // TODO: consider moving into BpfCoordinator.
954 private void updateClientInfoIpv4(NeighborEvent e) {
955 // TODO: Perhaps remove this protection check.
956 // See the related comment in #addIpv6ForwardingRule.
957 if (!mUsingBpfOffload) return;
958
959 if (e == null) return;
960 if (!(e.ip instanceof Inet4Address) || e.ip.isMulticastAddress()
961 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
962 return;
963 }
964
965 // When deleting clients, IpServer still need to pass a non-null MAC, even though it's
966 // ignored. Do this here instead of in the ClientInfo constructor to ensure that
967 // IpServer never add clients with a null MAC, only delete them.
968 final MacAddress clientMac = e.isValid() ? e.macAddr : NULL_MAC_ADDRESS;
969 final ClientInfo clientInfo = new ClientInfo(mInterfaceParams.index,
970 mInterfaceParams.macAddr, (Inet4Address) e.ip, clientMac);
971 if (e.isValid()) {
972 mBpfCoordinator.tetherOffloadClientAdd(this, clientInfo);
973 } else {
Hungming Chend71c06e2020-12-21 19:39:49 +0800974 mBpfCoordinator.tetherOffloadClientRemove(this, clientInfo);
975 }
976 }
977
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900978 private void handleNeighborEvent(NeighborEvent e) {
979 if (mInterfaceParams != null
980 && mInterfaceParams.index == e.ifindex
981 && mInterfaceParams.hasMacAddress) {
982 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
Hungming Chend71c06e2020-12-21 19:39:49 +0800983 updateClientInfoIpv4(e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900984 }
985 }
986
Xiao Ma4455d6b2020-04-09 10:13:44 +0900987 private void handleNewPrefixRequest(@NonNull final IpPrefix currentPrefix) {
988 if (!currentPrefix.contains(mIpv4Address.getAddress())
989 || currentPrefix.getPrefixLength() != mIpv4Address.getPrefixLength()) {
990 Log.e(TAG, "Invalid prefix: " + currentPrefix);
991 return;
992 }
993
994 final LinkAddress deprecatedLinkAddress = mIpv4Address;
markchiena2ffad82020-09-22 15:50:43 +0800995 mIpv4Address = requestIpv4Address(false);
markchienc9daba32020-02-12 00:19:21 +0800996 if (mIpv4Address == null) {
Xiao Ma4455d6b2020-04-09 10:13:44 +0900997 mLog.e("Fail to request a new downstream prefix");
998 return;
999 }
markchienc9daba32020-02-12 00:19:21 +08001000 final Inet4Address srvAddr = (Inet4Address) mIpv4Address.getAddress();
Xiao Ma4455d6b2020-04-09 10:13:44 +09001001
1002 // Add new IPv4 address on the interface.
1003 if (!mInterfaceCtrl.addAddress(srvAddr, currentPrefix.getPrefixLength())) {
1004 mLog.e("Failed to add new IP " + srvAddr);
1005 return;
1006 }
1007
1008 // Remove deprecated routes from local network.
1009 removeRoutesFromLocalNetwork(
1010 Collections.singletonList(getDirectConnectedRoute(deprecatedLinkAddress)));
1011 mLinkProperties.removeLinkAddress(deprecatedLinkAddress);
1012
1013 // Add new routes to local network.
1014 addRoutesToLocalNetwork(
1015 Collections.singletonList(getDirectConnectedRoute(mIpv4Address)));
1016 mLinkProperties.addLinkAddress(mIpv4Address);
1017
1018 // Update local DNS caching server with new IPv4 address, otherwise, dnsmasq doesn't
1019 // listen on the interface configured with new IPv4 address, that results DNS validation
1020 // failure of downstream client even if appropriate routes have been configured.
1021 try {
1022 mNetd.tetherApplyDnsInterfaces();
1023 } catch (ServiceSpecificException | RemoteException e) {
1024 mLog.e("Failed to update local DNS caching server");
1025 return;
1026 }
1027 sendLinkProperties();
1028
1029 // Notify DHCP server that new prefix/route has been applied on IpServer.
1030 final Inet4Address clientAddr = mStaticIpv4ClientAddr == null ? null :
1031 (Inet4Address) mStaticIpv4ClientAddr.getAddress();
1032 final DhcpServingParamsParcel params = makeServingParams(srvAddr /* defaultRouter */,
1033 srvAddr /* dnsServer */, mIpv4Address /* serverLinkAddress */, clientAddr);
1034 try {
1035 mDhcpServer.updateParams(params, new OnHandlerStatusCallback() {
1036 @Override
1037 public void callback(int statusCode) {
1038 if (statusCode != STATUS_SUCCESS) {
1039 mLog.e("Error updating DHCP serving params: " + statusCode);
1040 }
1041 }
1042 });
1043 } catch (RemoteException e) {
1044 mLog.e("Error updating DHCP serving params", e);
1045 }
1046 }
1047
markchiend63c4f32020-05-21 17:38:28 +08001048 private byte getHopLimit(String upstreamIface, int adjustTTL) {
markchien74a4fa92019-09-09 20:50:49 +08001049 try {
1050 int upstreamHopLimit = Integer.parseUnsignedInt(
1051 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
markchiend63c4f32020-05-21 17:38:28 +08001052 upstreamHopLimit = upstreamHopLimit + adjustTTL;
markchien74a4fa92019-09-09 20:50:49 +08001053 // Cap the hop limit to 255.
1054 return (byte) Integer.min(upstreamHopLimit, 255);
1055 } catch (Exception e) {
1056 mLog.e("Failed to find upstream interface hop limit", e);
1057 }
1058 return RaParams.DEFAULT_HOPLIMIT;
1059 }
1060
1061 private void setRaParams(RaParams newParams) {
1062 if (mRaDaemon != null) {
1063 final RaParams deprecatedParams =
1064 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
1065
1066 configureLocalIPv6Routes(deprecatedParams.prefixes,
1067 (newParams != null) ? newParams.prefixes : null);
1068
1069 configureLocalIPv6Dns(deprecatedParams.dnses,
1070 (newParams != null) ? newParams.dnses : null);
1071
1072 mRaDaemon.buildNewRa(deprecatedParams, newParams);
1073 }
1074
1075 mLastRaParams = newParams;
1076 }
1077
markchien21021ef2021-06-01 10:58:04 +08001078 private void maybeLogMessage(State state, int what) {
1079 switch (what) {
1080 // Suppress some CMD_* to avoid log flooding.
1081 case CMD_IPV6_TETHER_UPDATE:
1082 case CMD_NEIGHBOR_EVENT:
1083 break;
1084 default:
1085 mLog.log(state.getName() + " got "
1086 + sMagicDecoderRing.get(what, Integer.toString(what)));
1087 }
markchien74a4fa92019-09-09 20:50:49 +08001088 }
1089
1090 private void sendInterfaceState(int newInterfaceState) {
1091 mServingMode = newInterfaceState;
1092 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
1093 sendLinkProperties();
1094 }
1095
1096 private void sendLinkProperties() {
1097 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
1098 }
1099
1100 private void resetLinkProperties() {
1101 mLinkProperties.clear();
1102 mLinkProperties.setInterfaceName(mIfaceName);
1103 }
1104
markchienf053e4b2020-03-16 21:49:48 +08001105 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
markchien245352e2020-02-27 20:27:18 +08001106 // Ignore static address configuration if they are invalid or null. In theory, static
1107 // addresses should not be invalid here because TetheringManager do not allow caller to
1108 // specify invalid static address configuration.
1109 if (request == null || request.localIPv4Address == null
1110 || request.staticClientAddress == null || !checkStaticAddressConfiguration(
1111 request.localIPv4Address, request.staticClientAddress)) {
1112 return;
1113 }
markchienf053e4b2020-03-16 21:49:48 +08001114
1115 mStaticIpv4ServerAddr = request.localIPv4Address;
1116 mStaticIpv4ClientAddr = request.staticClientAddress;
1117 }
1118
markchien74a4fa92019-09-09 20:50:49 +08001119 class InitialState extends State {
1120 @Override
1121 public void enter() {
1122 sendInterfaceState(STATE_AVAILABLE);
1123 }
1124
1125 @Override
1126 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001127 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001128 switch (message.what) {
1129 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +08001130 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001131 switch (message.arg1) {
1132 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +08001133 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001134 transitionTo(mLocalHotspotState);
1135 break;
1136 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +08001137 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +08001138 transitionTo(mTetheredState);
1139 break;
1140 default:
1141 mLog.e("Invalid tethering interface serving state specified.");
1142 }
1143 break;
1144 case CMD_INTERFACE_DOWN:
1145 transitionTo(mUnavailableState);
1146 break;
1147 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001148 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001149 break;
1150 default:
1151 return NOT_HANDLED;
1152 }
1153 return HANDLED;
1154 }
1155 }
1156
Hungming Chen46c30b12020-10-15 17:25:36 +08001157 private void startConntrackMonitoring() {
1158 mBpfCoordinator.startMonitoring(this);
1159 }
1160
1161 private void stopConntrackMonitoring() {
1162 mBpfCoordinator.stopMonitoring(this);
1163 }
1164
markchien74a4fa92019-09-09 20:50:49 +08001165 class BaseServingState extends State {
1166 @Override
1167 public void enter() {
Hungming Chen46c30b12020-10-15 17:25:36 +08001168 startConntrackMonitoring();
1169
markchien74a4fa92019-09-09 20:50:49 +08001170 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001171 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001172 return;
1173 }
1174
1175 try {
markchienc9daba32020-02-12 00:19:21 +08001176 NetdUtils.tetherInterface(mNetd, mIfaceName, asIpPrefix(mIpv4Address));
markchien6c2b7cc2020-02-15 11:35:00 +08001177 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
Xiao Ma4455d6b2020-04-09 10:13:44 +09001178 mLog.e("Error Tethering", e);
markchien9b4d7572019-12-25 19:40:32 +08001179 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001180 return;
1181 }
1182
1183 if (!startIPv6()) {
1184 mLog.e("Failed to startIPv6");
1185 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1186 return;
1187 }
1188 }
1189
1190 @Override
1191 public void exit() {
1192 // Note that at this point, we're leaving the tethered state. We can fail any
1193 // of these operations, but it doesn't really change that we have to try them
1194 // all in sequence.
1195 stopIPv6();
1196
1197 try {
markchien12c5bb82020-01-07 14:43:17 +08001198 NetdUtils.untetherInterface(mNetd, mIfaceName);
1199 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001200 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001201 mLog.e("Failed to untether interface: " + e);
1202 }
1203
1204 stopIPv4();
Hungming Chen46c30b12020-10-15 17:25:36 +08001205 stopConntrackMonitoring();
markchien74a4fa92019-09-09 20:50:49 +08001206
1207 resetLinkProperties();
Wayne Ma6cd440f2022-03-14 18:04:33 +08001208
1209 mTetheringMetrics.updateErrorCode(mInterfaceType, mLastError);
1210 mTetheringMetrics.sendReport(mInterfaceType);
markchien74a4fa92019-09-09 20:50:49 +08001211 }
1212
1213 @Override
1214 public boolean processMessage(Message message) {
markchien74a4fa92019-09-09 20:50:49 +08001215 switch (message.what) {
1216 case CMD_TETHER_UNREQUESTED:
1217 transitionTo(mInitialState);
1218 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1219 break;
1220 case CMD_INTERFACE_DOWN:
1221 transitionTo(mUnavailableState);
1222 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1223 break;
1224 case CMD_IPV6_TETHER_UPDATE:
markchiend63c4f32020-05-21 17:38:28 +08001225 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj, message.arg1);
markchien74a4fa92019-09-09 20:50:49 +08001226 sendLinkProperties();
1227 break;
1228 case CMD_IP_FORWARDING_ENABLE_ERROR:
1229 case CMD_IP_FORWARDING_DISABLE_ERROR:
1230 case CMD_START_TETHERING_ERROR:
1231 case CMD_STOP_TETHERING_ERROR:
1232 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien8146b562020-03-19 13:37:43 +08001233 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001234 transitionTo(mInitialState);
1235 break;
Xiao Ma4455d6b2020-04-09 10:13:44 +09001236 case CMD_NEW_PREFIX_REQUEST:
1237 handleNewPrefixRequest((IpPrefix) message.obj);
1238 break;
markchienc9daba32020-02-12 00:19:21 +08001239 case CMD_NOTIFY_PREFIX_CONFLICT:
1240 mLog.i("restart tethering: " + mInterfaceType);
1241 mCallback.requestEnableTethering(mInterfaceType, false /* enabled */);
1242 transitionTo(mWaitingForRestartState);
1243 break;
markchien74a4fa92019-09-09 20:50:49 +08001244 default:
1245 return false;
1246 }
1247 return true;
1248 }
1249 }
1250
1251 // Handling errors in BaseServingState.enter() by transitioning is
1252 // problematic because transitioning during a multi-state jump yields
1253 // a Log.wtf(). Ultimately, there should be only one ServingState,
1254 // and forwarding and NAT rules should be handled by a coordinating
1255 // functional element outside of IpServer.
1256 class LocalHotspotState extends BaseServingState {
1257 @Override
1258 public void enter() {
1259 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001260 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001261 transitionTo(mInitialState);
1262 }
1263
1264 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1265 sendInterfaceState(STATE_LOCAL_ONLY);
1266 }
1267
1268 @Override
1269 public boolean processMessage(Message message) {
1270 if (super.processMessage(message)) return true;
1271
markchien21021ef2021-06-01 10:58:04 +08001272 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001273 switch (message.what) {
1274 case CMD_TETHER_REQUESTED:
1275 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1276 break;
1277 case CMD_TETHER_CONNECTION_CHANGED:
1278 // Ignored in local hotspot state.
1279 break;
1280 default:
1281 return false;
1282 }
1283 return true;
1284 }
1285 }
1286
1287 // Handling errors in BaseServingState.enter() by transitioning is
1288 // problematic because transitioning during a multi-state jump yields
1289 // a Log.wtf(). Ultimately, there should be only one ServingState,
1290 // and forwarding and NAT rules should be handled by a coordinating
1291 // functional element outside of IpServer.
1292 class TetheredState extends BaseServingState {
1293 @Override
1294 public void enter() {
1295 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001296 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001297 transitionTo(mInitialState);
1298 }
1299
1300 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1301 sendInterfaceState(STATE_TETHERED);
1302 }
1303
1304 @Override
1305 public void exit() {
1306 cleanupUpstream();
1307 super.exit();
1308 }
1309
Hungming Chena6e78692021-02-08 17:15:35 +08001310 // Note that IPv4 offload rules cleanup is implemented in BpfCoordinator while upstream
1311 // state is null or changed because IPv4 and IPv6 tethering have different code flow
1312 // and behaviour. While upstream is switching from offload supported interface to
1313 // offload non-supportted interface, event CMD_TETHER_CONNECTION_CHANGED calls
1314 // #cleanupUpstreamInterface but #cleanupUpstream because new UpstreamIfaceSet is not null.
1315 // This case won't happen in IPv6 tethering because IPv6 tethering upstream state is
1316 // reported by IPv6TetheringCoordinator. #cleanupUpstream is also called by unwirding
1317 // adding NAT failure. In that case, the IPv4 offload rules are removed by #stopIPv4
1318 // in the state machine. Once there is any case out whish is not covered by previous cases,
1319 // probably consider clearing rules in #cleanupUpstream as well.
markchien74a4fa92019-09-09 20:50:49 +08001320 private void cleanupUpstream() {
1321 if (mUpstreamIfaceSet == null) return;
1322
1323 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1324 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001325 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001326 }
1327
1328 private void cleanupUpstreamInterface(String upstreamIface) {
1329 // Note that we don't care about errors here.
1330 // Sometimes interfaces are gone before we get
1331 // to remove their rules, which generates errors.
1332 // Just do the best we can.
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001333 mBpfCoordinator.maybeDetachProgram(mIfaceName, upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +08001334 try {
markchien12c5bb82020-01-07 14:43:17 +08001335 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1336 } catch (RemoteException | ServiceSpecificException e) {
1337 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001338 }
1339 try {
markchien12c5bb82020-01-07 14:43:17 +08001340 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1341 } catch (RemoteException | ServiceSpecificException e) {
1342 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001343 }
1344 }
1345
1346 @Override
1347 public boolean processMessage(Message message) {
1348 if (super.processMessage(message)) return true;
1349
markchien21021ef2021-06-01 10:58:04 +08001350 maybeLogMessage(this, message.what);
markchien74a4fa92019-09-09 20:50:49 +08001351 switch (message.what) {
1352 case CMD_TETHER_REQUESTED:
1353 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1354 break;
1355 case CMD_TETHER_CONNECTION_CHANGED:
1356 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1357 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1358 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1359 break;
1360 }
1361
1362 if (newUpstreamIfaceSet == null) {
1363 cleanupUpstream();
1364 break;
1365 }
1366
1367 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1368 cleanupUpstreamInterface(removed);
1369 }
1370
1371 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1372 // This makes the call to cleanupUpstream() in the error
1373 // path for any interface neatly cleanup all the interfaces.
1374 mUpstreamIfaceSet = newUpstreamIfaceSet;
1375
1376 for (String ifname : added) {
Lorenzo Colittidc6715c2021-02-09 23:12:37 +09001377 // Add upstream index to name mapping for the tether stats usage in the
1378 // coordinator. Although this mapping could be added by both class
1379 // Tethering and IpServer, adding mapping from IpServer guarantees that
1380 // the mapping is added before adding forwarding rules. That is because
1381 // there are different state machines in both classes. It is hard to
1382 // guarantee the link property update order between multiple state machines.
1383 // Note that both IPv4 and IPv6 interface may be added because
1384 // Tethering::setUpstreamNetwork calls getTetheringInterfaces which merges
1385 // IPv4 and IPv6 interface name (if any) into an InterfaceSet. The IPv6
1386 // capability may be updated later. In that case, IPv6 interface mapping is
1387 // updated in updateUpstreamIPv6LinkProperties.
1388 if (!ifname.startsWith("v4-")) { // ignore clat interfaces
1389 final InterfaceParams upstreamIfaceParams =
1390 mDeps.getInterfaceParams(ifname);
1391 if (upstreamIfaceParams != null) {
1392 mBpfCoordinator.addUpstreamNameToLookupTable(
1393 upstreamIfaceParams.index, ifname);
1394 }
1395 }
1396
Hungming Chen3dbd4a12021-02-25 17:52:02 +08001397 mBpfCoordinator.maybeAttachProgram(mIfaceName, ifname);
markchien74a4fa92019-09-09 20:50:49 +08001398 try {
markchien12c5bb82020-01-07 14:43:17 +08001399 mNetd.tetherAddForward(mIfaceName, ifname);
1400 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1401 } catch (RemoteException | ServiceSpecificException e) {
1402 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001403 cleanupUpstream();
markchien8146b562020-03-19 13:37:43 +08001404 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001405 transitionTo(mInitialState);
1406 return true;
1407 }
1408 }
1409 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001410 case CMD_NEIGHBOR_EVENT:
1411 handleNeighborEvent((NeighborEvent) message.obj);
1412 break;
markchien74a4fa92019-09-09 20:50:49 +08001413 default:
1414 return false;
1415 }
1416 return true;
1417 }
1418
1419 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1420 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1421 if (mUpstreamIfaceSet != null && newIfaces != null) {
1422 return mUpstreamIfaceSet.equals(newIfaces);
1423 }
1424 return false;
1425 }
1426
1427 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1428 if (mUpstreamIfaceSet == null) return new HashSet<>();
1429
1430 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1431 removed.removeAll(newIfaces.ifnames);
1432 return removed;
1433 }
1434
1435 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1436 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1437 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1438 return added;
1439 }
1440 }
1441
1442 /**
1443 * This state is terminal for the per interface state machine. At this
Chiachang Wang14aaefc2020-07-29 12:05:04 +08001444 * point, the tethering main state machine should have removed this interface
markchien74a4fa92019-09-09 20:50:49 +08001445 * specific state machine from its list of possible recipients of
1446 * tethering requests. The state machine itself will hang around until
1447 * the garbage collector finds it.
1448 */
1449 class UnavailableState extends State {
1450 @Override
1451 public void enter() {
h.zhangd244bd02020-06-14 14:46:54 +08001452 mIpNeighborMonitor.stop();
markchien9b4d7572019-12-25 19:40:32 +08001453 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001454 sendInterfaceState(STATE_UNAVAILABLE);
1455 }
1456 }
1457
markchienc9daba32020-02-12 00:19:21 +08001458 class WaitingForRestartState extends State {
1459 @Override
1460 public boolean processMessage(Message message) {
markchien21021ef2021-06-01 10:58:04 +08001461 maybeLogMessage(this, message.what);
markchienc9daba32020-02-12 00:19:21 +08001462 switch (message.what) {
1463 case CMD_TETHER_UNREQUESTED:
1464 transitionTo(mInitialState);
1465 mLog.i("Untethered (unrequested) and restarting " + mIfaceName);
1466 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1467 break;
1468 case CMD_INTERFACE_DOWN:
1469 transitionTo(mUnavailableState);
Lorenzo Colitti8a36c292021-04-13 17:17:44 +09001470 mLog.i("Untethered (interface down) and restarting " + mIfaceName);
markchienc9daba32020-02-12 00:19:21 +08001471 mCallback.requestEnableTethering(mInterfaceType, true /* enabled */);
1472 break;
1473 default:
1474 return false;
1475 }
1476 return true;
1477 }
1478 }
1479
markchien74a4fa92019-09-09 20:50:49 +08001480 // Accumulate routes representing "prefixes to be assigned to the local
1481 // interface", for subsequent modification of local_network routing.
1482 private static ArrayList<RouteInfo> getLocalRoutesFor(
1483 String ifname, HashSet<IpPrefix> prefixes) {
1484 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1485 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001486 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001487 }
1488 return localRoutes;
1489 }
1490
1491 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1492 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1493 final byte[] dnsBytes = localPrefix.getRawAddress();
1494 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1495 try {
1496 return Inet6Address.getByAddress(null, dnsBytes, 0);
1497 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001498 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001499 return null;
1500 }
1501 }
1502
1503 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1504 final byte random = (byte) (new Random()).nextInt();
1505 for (int value : excluded) {
1506 if (random == value) return dflt;
1507 }
1508 return random;
1509 }
1510}