blob: 6c0c432d46dcd5d5164878fa805328e6a12840e3 [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
19import static android.net.InetAddresses.parseNumericAddress;
markchien6cf0e552019-12-06 15:24:53 +080020import static android.net.RouteInfo.RTN_UNICAST;
markchien74a4fa92019-09-09 20:50:49 +080021import static android.net.dhcp.IDhcpServer.STATUS_SUCCESS;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090022import static android.net.shared.Inet4AddressUtils.intToInet4AddressHTH;
markchien74a4fa92019-09-09 20:50:49 +080023import static android.net.util.NetworkConstants.FF;
24import static android.net.util.NetworkConstants.RFC7421_PREFIX_LENGTH;
25import static android.net.util.NetworkConstants.asByte;
markchien6cf0e552019-12-06 15:24:53 +080026import static android.net.util.TetheringMessageBase.BASE_IPSERVER;
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +090027import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080028
markchien74a4fa92019-09-09 20:50:49 +080029import android.net.INetd;
30import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080031import android.net.IpPrefix;
32import android.net.LinkAddress;
33import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090034import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080035import android.net.RouteInfo;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090036import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080037import android.net.TetheringManager;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090038import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080039import android.net.dhcp.DhcpServerCallbacks;
40import android.net.dhcp.DhcpServingParamsParcel;
41import android.net.dhcp.DhcpServingParamsParcelExt;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090042import android.net.dhcp.IDhcpLeaseCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080043import android.net.dhcp.IDhcpServer;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090044import android.net.ip.IpNeighborMonitor.NeighborEvent;
markchien74a4fa92019-09-09 20:50:49 +080045import android.net.ip.RouterAdvertisementDaemon.RaParams;
markchien12c5bb82020-01-07 14:43:17 +080046import android.net.shared.NetdUtils;
47import android.net.shared.RouteUtils;
markchien74a4fa92019-09-09 20:50:49 +080048import android.net.util.InterfaceParams;
49import android.net.util.InterfaceSet;
markchien74a4fa92019-09-09 20:50:49 +080050import android.net.util.SharedLog;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090051import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080052import android.os.Looper;
53import android.os.Message;
54import android.os.RemoteException;
55import android.os.ServiceSpecificException;
56import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080057import android.util.SparseArray;
58
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090059import androidx.annotation.NonNull;
60
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;
64
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090065import java.io.IOException;
markchien74a4fa92019-09-09 20:50:49 +080066import java.net.Inet4Address;
67import java.net.Inet6Address;
68import java.net.InetAddress;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090069import java.net.NetworkInterface;
markchien74a4fa92019-09-09 20:50:49 +080070import java.net.UnknownHostException;
71import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090072import java.util.Arrays;
73import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080074import java.util.HashSet;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090075import java.util.LinkedHashMap;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090076import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080077import java.util.Objects;
78import java.util.Random;
79import java.util.Set;
80
81/**
82 * Provides the interface to IP-layer serving functionality for a given network
83 * interface, e.g. for tethering or "local-only hotspot" mode.
84 *
85 * @hide
86 */
87public class IpServer extends StateMachine {
88 public static final int STATE_UNAVAILABLE = 0;
89 public static final int STATE_AVAILABLE = 1;
90 public static final int STATE_TETHERED = 2;
91 public static final int STATE_LOCAL_ONLY = 3;
92
93 /** Get string name of |state|.*/
94 public static String getStateString(int state) {
95 switch (state) {
96 case STATE_UNAVAILABLE: return "UNAVAILABLE";
97 case STATE_AVAILABLE: return "AVAILABLE";
98 case STATE_TETHERED: return "TETHERED";
99 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
100 }
101 return "UNKNOWN: " + state;
102 }
103
104 private static final byte DOUG_ADAMS = (byte) 42;
105
106 private static final String USB_NEAR_IFACE_ADDR = "192.168.42.129";
107 private static final int USB_PREFIX_LENGTH = 24;
108 private static final String WIFI_HOST_IFACE_ADDR = "192.168.43.1";
109 private static final int WIFI_HOST_IFACE_PREFIX_LENGTH = 24;
110 private static final String WIFI_P2P_IFACE_ADDR = "192.168.49.1";
111 private static final int WIFI_P2P_IFACE_PREFIX_LENGTH = 24;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900112 private static final String ETHERNET_IFACE_ADDR = "192.168.50.1";
113 private static final int ETHERNET_IFACE_PREFIX_LENGTH = 24;
markchien74a4fa92019-09-09 20:50:49 +0800114
115 // TODO: have PanService use some visible version of this constant
116 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1";
117 private static final int BLUETOOTH_DHCP_PREFIX_LENGTH = 24;
118
119 // TODO: have this configurable
120 private static final int DHCP_LEASE_TIME_SECS = 3600;
121
122 private static final String TAG = "IpServer";
123 private static final boolean DBG = false;
124 private static final boolean VDBG = false;
125 private static final Class[] sMessageClasses = {
126 IpServer.class
127 };
128 private static final SparseArray<String> sMagicDecoderRing =
129 MessageUtils.findMessageNames(sMessageClasses);
130
131 /** IpServer callback. */
132 public static class Callback {
133 /**
134 * Notify that |who| has changed its tethering state.
135 *
136 * @param who the calling instance of IpServer
137 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800138 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800139 */
markchien9d353822019-12-16 20:15:20 +0800140 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800141
142 /**
143 * Notify that |who| has new LinkProperties.
144 *
145 * @param who the calling instance of IpServer
146 * @param newLp the new LinkProperties to report
147 */
markchien9d353822019-12-16 20:15:20 +0800148 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900149
150 /**
151 * Notify that the DHCP leases changed in one of the IpServers.
152 */
153 public void dhcpLeasesChanged() { }
markchien74a4fa92019-09-09 20:50:49 +0800154 }
155
156 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800157 public abstract static class Dependencies {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900158 /** Create an IpNeighborMonitor to be used by this IpServer */
159 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
160 IpNeighborMonitor.NeighborEventConsumer consumer) {
161 return new IpNeighborMonitor(handler, log, consumer);
162 }
163
markchien74a4fa92019-09-09 20:50:49 +0800164 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
165 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
166 return new RouterAdvertisementDaemon(ifParams);
167 }
168
169 /** Get |ifName|'s interface information.*/
170 public InterfaceParams getInterfaceParams(String ifName) {
171 return InterfaceParams.getByName(ifName);
172 }
173
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900174 /** Get |ifName|'s interface index. */
175 public int getIfindex(String ifName) {
176 try {
177 return NetworkInterface.getByName(ifName).getIndex();
178 } catch (IOException | NullPointerException e) {
179 Log.e(TAG, "Can't determine interface index for interface " + ifName);
180 return 0;
181 }
182 }
markchien9d353822019-12-16 20:15:20 +0800183 /** Create a DhcpServer instance to be used by IpServer. */
184 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
185 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800186 }
187
markchien74a4fa92019-09-09 20:50:49 +0800188 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800189 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800190 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800191 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800192 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800193 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
markchien74a4fa92019-09-09 20:50:49 +0800194 // notification from the master SM that it had trouble enabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800195 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
markchien74a4fa92019-09-09 20:50:49 +0800196 // notification from the master SM that it had trouble disabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800197 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
markchien74a4fa92019-09-09 20:50:49 +0800198 // notification from the master SM that it had trouble starting tethering
markchien6cf0e552019-12-06 15:24:53 +0800199 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
markchien74a4fa92019-09-09 20:50:49 +0800200 // notification from the master SM that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800201 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
markchien74a4fa92019-09-09 20:50:49 +0800202 // notification from the master SM that it had trouble setting the DNS forwarders
markchien6cf0e552019-12-06 15:24:53 +0800203 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800204 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800205 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800206 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800207 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900208 // new neighbor cache entry on our interface
209 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
markchien74a4fa92019-09-09 20:50:49 +0800210
211 private final State mInitialState;
212 private final State mLocalHotspotState;
213 private final State mTetheredState;
214 private final State mUnavailableState;
215
216 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800217 private final INetd mNetd;
markchien74a4fa92019-09-09 20:50:49 +0800218 private final Callback mCallback;
219 private final InterfaceController mInterfaceCtrl;
220
221 private final String mIfaceName;
222 private final int mInterfaceType;
223 private final LinkProperties mLinkProperties;
224 private final boolean mUsingLegacyDhcp;
225
226 private final Dependencies mDeps;
227
228 private int mLastError;
229 private int mServingMode;
230 private InterfaceSet mUpstreamIfaceSet; // may change over time
231 private InterfaceParams mInterfaceParams;
232 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
233 // properties are those selected by the IPv6TetheringCoordinator and relayed
234 // to us. By comparison, mLinkProperties contains the addresses and directly
235 // connected routes that have been formed from these properties iff. we have
236 // succeeded in configuring them and are able to announce them within Router
237 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
238 private LinkProperties mLastIPv6LinkProperties;
239 private RouterAdvertisementDaemon mRaDaemon;
240
241 // To be accessed only on the handler thread
242 private int mDhcpServerStartIndex = 0;
243 private IDhcpServer mDhcpServer;
244 private RaParams mLastRaParams;
markchien12c5bb82020-01-07 14:43:17 +0800245 private LinkAddress mIpv4Address;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900246 @NonNull
247 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800248
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900249 private int mLastIPv6UpstreamIfindex = 0;
250
251 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
252 public void accept(NeighborEvent e) {
253 sendMessage(CMD_NEIGHBOR_EVENT, e);
254 }
255 }
256
257 static class Ipv6ForwardingRule {
258 public final int upstreamIfindex;
259 public final int downstreamIfindex;
260 public final Inet6Address address;
261 public final MacAddress srcMac;
262 public final MacAddress dstMac;
263
264 Ipv6ForwardingRule(int upstreamIfindex, int downstreamIfIndex, Inet6Address address,
265 MacAddress srcMac, MacAddress dstMac) {
266 this.upstreamIfindex = upstreamIfindex;
267 this.downstreamIfindex = downstreamIfIndex;
268 this.address = address;
269 this.srcMac = srcMac;
270 this.dstMac = dstMac;
271 }
272
273 public Ipv6ForwardingRule onNewUpstream(int newUpstreamIfindex) {
274 return new Ipv6ForwardingRule(newUpstreamIfindex, downstreamIfindex, address, srcMac,
275 dstMac);
276 }
277 }
278 private final LinkedHashMap<Inet6Address, Ipv6ForwardingRule> mIpv6ForwardingRules =
279 new LinkedHashMap<>();
280
281 private final IpNeighborMonitor mIpNeighborMonitor;
282
markchien74a4fa92019-09-09 20:50:49 +0800283 public IpServer(
284 String ifaceName, Looper looper, int interfaceType, SharedLog log,
junyulai5864a3f2019-12-03 14:34:13 +0800285 INetd netd, Callback callback, boolean usingLegacyDhcp, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800286 super(ifaceName, looper);
287 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800288 mNetd = netd;
markchien74a4fa92019-09-09 20:50:49 +0800289 mCallback = callback;
290 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
291 mIfaceName = ifaceName;
292 mInterfaceType = interfaceType;
293 mLinkProperties = new LinkProperties();
294 mUsingLegacyDhcp = usingLegacyDhcp;
295 mDeps = deps;
296 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800297 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800298 mServingMode = STATE_AVAILABLE;
299
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900300 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
301 new MyNeighborEventConsumer());
302 if (!mIpNeighborMonitor.start()) {
303 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
304 }
305
markchien74a4fa92019-09-09 20:50:49 +0800306 mInitialState = new InitialState();
307 mLocalHotspotState = new LocalHotspotState();
308 mTetheredState = new TetheredState();
309 mUnavailableState = new UnavailableState();
310 addState(mInitialState);
311 addState(mLocalHotspotState);
312 addState(mTetheredState);
313 addState(mUnavailableState);
314
315 setInitialState(mInitialState);
316 }
317
318 /** Interface name which IpServer served.*/
319 public String interfaceName() {
320 return mIfaceName;
321 }
322
323 /**
markchien9b4d7572019-12-25 19:40:32 +0800324 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800325 */
326 public int interfaceType() {
327 return mInterfaceType;
328 }
329
330 /** Last error from this IpServer. */
331 public int lastError() {
332 return mLastError;
333 }
334
335 /** Serving mode is the current state of IpServer state machine. */
336 public int servingMode() {
337 return mServingMode;
338 }
339
340 /** The properties of the network link which IpServer is serving. */
341 public LinkProperties linkProperties() {
342 return new LinkProperties(mLinkProperties);
343 }
344
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900345 /**
346 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
347 * thread.
348 */
349 public List<TetheredClient> getAllLeases() {
350 return Collections.unmodifiableList(mDhcpLeases);
351 }
352
markchien74a4fa92019-09-09 20:50:49 +0800353 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
354 public void stop() {
355 sendMessage(CMD_INTERFACE_DOWN);
356 }
357
358 /**
359 * Tethering is canceled. IpServer state machine will be available and wait for
360 * next tethering request.
361 */
362 public void unwanted() {
363 sendMessage(CMD_TETHER_UNREQUESTED);
364 }
365
366 /** Internals. */
367
368 private boolean startIPv4() {
369 return configureIPv4(true);
370 }
371
372 /**
373 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
374 * handler.
375 *
376 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
377 * with different implementations of the callback, to differentiate handling of success/error in
378 * each call.
379 */
380 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
381 @Override
382 public void onStatusAvailable(int statusCode) {
383 getHandler().post(() -> callback(statusCode));
384 }
385
386 public abstract void callback(int statusCode);
387
388 @Override
389 public int getInterfaceVersion() {
390 return this.VERSION;
391 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900392
393 @Override
394 public String getInterfaceHash() {
395 return this.HASH;
396 }
markchien74a4fa92019-09-09 20:50:49 +0800397 }
398
399 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
400 private final int mStartIndex;
401
402 private DhcpServerCallbacksImpl(int startIndex) {
403 mStartIndex = startIndex;
404 }
405
406 @Override
407 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
408 getHandler().post(() -> {
409 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
410 if (mStartIndex != mDhcpServerStartIndex) {
411 // This start request is obsolete. When the |server| binder token goes out of
412 // scope, the garbage collector will finalize it, which causes the network stack
413 // process garbage collector to collect the server itself.
414 return;
415 }
416
417 if (statusCode != STATUS_SUCCESS) {
418 mLog.e("Error obtaining DHCP server: " + statusCode);
419 handleError();
420 return;
421 }
422
423 mDhcpServer = server;
424 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900425 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800426 @Override
427 public void callback(int startStatusCode) {
428 if (startStatusCode != STATUS_SUCCESS) {
429 mLog.e("Error starting DHCP server: " + startStatusCode);
430 handleError();
431 }
432 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900433 }, new DhcpLeaseCallback());
markchien74a4fa92019-09-09 20:50:49 +0800434 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800435 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800436 }
437 });
438 }
439
440 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800441 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800442 transitionTo(mInitialState);
443 }
444 }
445
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900446 private class DhcpLeaseCallback extends IDhcpLeaseCallbacks.Stub {
447 @Override
448 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
449 final ArrayList<TetheredClient> leases = new ArrayList<>();
450 for (DhcpLeaseParcelable lease : leaseParcelables) {
451 final LinkAddress address = new LinkAddress(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900452 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
453 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
454 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900455
456 final MacAddress macAddress;
457 try {
458 macAddress = MacAddress.fromBytes(lease.hwAddr);
459 } catch (IllegalArgumentException e) {
460 Log.wtf(TAG, "Invalid address received from DhcpServer: "
461 + Arrays.toString(lease.hwAddr));
462 return;
463 }
464
465 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Remi NGUYEN VANdfdf7502020-03-09 15:38:45 +0900466 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900467 leases.add(new TetheredClient(
468 macAddress,
469 Collections.singletonList(addressInfo),
470 mInterfaceType));
471 }
472
473 getHandler().post(() -> {
474 mDhcpLeases = leases;
475 mCallback.dhcpLeasesChanged();
476 });
477 }
478
479 @Override
480 public int getInterfaceVersion() {
481 return this.VERSION;
482 }
483
484 @Override
485 public String getInterfaceHash() throws RemoteException {
486 return this.HASH;
487 }
488 }
489
markchien74a4fa92019-09-09 20:50:49 +0800490 private boolean startDhcp(Inet4Address addr, int prefixLen) {
491 if (mUsingLegacyDhcp) {
492 return true;
493 }
494 final DhcpServingParamsParcel params;
495 params = new DhcpServingParamsParcelExt()
496 .setDefaultRouters(addr)
497 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
498 .setDnsServers(addr)
499 .setServerAddr(new LinkAddress(addr, prefixLen))
500 .setMetered(true);
501 // TODO: also advertise link MTU
502
503 mDhcpServerStartIndex++;
504 mDeps.makeDhcpServer(
505 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
506 return true;
507 }
508
509 private void stopDhcp() {
510 // Make all previous start requests obsolete so servers are not started later
511 mDhcpServerStartIndex++;
512
513 if (mDhcpServer != null) {
514 try {
515 mDhcpServer.stop(new OnHandlerStatusCallback() {
516 @Override
517 public void callback(int statusCode) {
518 if (statusCode != STATUS_SUCCESS) {
519 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800520 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800521 // Not much more we can do here
522 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900523 mDhcpLeases.clear();
524 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800525 }
526 });
527 mDhcpServer = null;
528 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800529 mLog.e("Error stopping DHCP", e);
530 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800531 }
532 }
533 }
534
535 private boolean configureDhcp(boolean enable, Inet4Address addr, int prefixLen) {
536 if (enable) {
537 return startDhcp(addr, prefixLen);
538 } else {
539 stopDhcp();
540 return true;
541 }
542 }
543
544 private void stopIPv4() {
545 configureIPv4(false);
546 // NOTE: All of configureIPv4() will be refactored out of existence
547 // into calls to InterfaceController, shared with startIPv4().
548 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800549 mIpv4Address = null;
markchien74a4fa92019-09-09 20:50:49 +0800550 }
551
markchien74a4fa92019-09-09 20:50:49 +0800552 private boolean configureIPv4(boolean enabled) {
553 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
554
555 // TODO: Replace this hard-coded information with dynamically selected
556 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800557 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800558 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800559 try {
Milim Lee45a971b2019-10-17 05:02:33 +0900560 if (mInterfaceType == TetheringManager.TETHERING_USB
561 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien12c5bb82020-01-07 14:43:17 +0800562 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
563 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800564 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800565 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
566 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800567 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800568 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
569 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900570 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
571 // TODO: randomize address for tethering too, similarly to wifi
572 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
573 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien12c5bb82020-01-07 14:43:17 +0800574 } else {
575 // BT configures the interface elsewhere: only start DHCP.
576 // TODO: make all tethering types behave the same way, and delete the bluetooth
577 // code that calls into NetworkManagementService directly.
578 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
579 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
580 return configureDhcp(enabled, srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
581 }
582 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
583 } catch (IllegalArgumentException e) {
584 mLog.e("Error selecting ipv4 address", e);
585 if (!enabled) stopDhcp();
586 return false;
markchien74a4fa92019-09-09 20:50:49 +0800587 }
588
markchien12c5bb82020-01-07 14:43:17 +0800589 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800590 if (mInterfaceType == TetheringManager.TETHERING_WIFI
591 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800592 // The WiFi stack has ownership of the interface up/down state.
593 // It is unclear whether the Bluetooth or USB stacks will manage their own
594 // state.
595 setIfaceUp = null;
596 } else {
597 setIfaceUp = enabled;
598 }
599 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
600 mLog.e("Error configuring interface");
601 if (!enabled) stopDhcp();
602 return false;
603 }
markchien74a4fa92019-09-09 20:50:49 +0800604
markchien12c5bb82020-01-07 14:43:17 +0800605 if (!configureDhcp(enabled, srvAddr, prefixLen)) {
markchien74a4fa92019-09-09 20:50:49 +0800606 return false;
607 }
608
609 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800610 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
611 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800612 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800613 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800614 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800615 mLinkProperties.addRoute(route);
616 } else {
markchien12c5bb82020-01-07 14:43:17 +0800617 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800618 mLinkProperties.removeRoute(route);
619 }
620 return true;
621 }
622
623 private String getRandomWifiIPv4Address() {
624 try {
625 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
626 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
627 return InetAddress.getByAddress(bytes).getHostAddress();
628 } catch (Exception e) {
629 return WIFI_HOST_IFACE_ADDR;
630 }
631 }
632
633 private boolean startIPv6() {
634 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
635 if (mInterfaceParams == null) {
636 mLog.e("Failed to find InterfaceParams");
637 stopIPv6();
638 return false;
639 }
640
641 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
642 if (!mRaDaemon.start()) {
643 stopIPv6();
644 return false;
645 }
646
647 return true;
648 }
649
650 private void stopIPv6() {
651 mInterfaceParams = null;
652 setRaParams(null);
653
654 if (mRaDaemon != null) {
655 mRaDaemon.stop();
656 mRaDaemon = null;
657 }
658 }
659
660 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
661 // LinkProperties. These have extraneous data filtered out and only the
662 // necessary prefixes included (per its prefix distribution policy).
663 //
664 // TODO: Evaluate using a data structure than is more directly suited to
665 // communicating only the relevant information.
666 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
667 if (mRaDaemon == null) return;
668
669 // Avoid unnecessary work on spurious updates.
670 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
671 return;
672 }
673
674 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900675 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800676
677 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900678 final String upstreamIface = v6only.getInterfaceName();
679
markchien74a4fa92019-09-09 20:50:49 +0800680 params = new RaParams();
Maciej Żenczykowskida0fb1b2020-02-19 01:24:39 -0800681 // We advertise an mtu lower by 16, which is the closest multiple of 8 >= 14,
682 // the ethernet header size. This makes kernel ebpf tethering offload happy.
683 // This hack should be reverted once we have the kernel fixed up.
684 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
685 // see RouterAdvertisementDaemon.java putMtu()
686 params.mtu = v6only.getMtu() - 16;
markchien74a4fa92019-09-09 20:50:49 +0800687 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
688
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900689 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800690
691 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
692 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
693
694 final IpPrefix prefix = new IpPrefix(
695 linkAddr.getAddress(), linkAddr.getPrefixLength());
696 params.prefixes.add(prefix);
697
698 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
699 if (dnsServer != null) {
700 params.dnses.add(dnsServer);
701 }
702 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900703
704 upstreamIfindex = mDeps.getIfindex(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800705 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900706
markchien74a4fa92019-09-09 20:50:49 +0800707 // If v6only is null, we pass in null to setRaParams(), which handles
708 // deprecation of any existing RA data.
709
710 setRaParams(params);
711 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900712
713 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
714 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800715 }
716
717 private void configureLocalIPv6Routes(
718 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
719 // [1] Remove the routes that are deprecated.
720 if (!deprecatedPrefixes.isEmpty()) {
721 final ArrayList<RouteInfo> toBeRemoved =
722 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800723 // Remove routes from local network.
724 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
725 mNetd, toBeRemoved);
726 if (removalFailures > 0) {
727 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
728 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800729 }
730
731 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
732 }
733
734 // [2] Add only the routes that have not previously been added.
735 if (newPrefixes != null && !newPrefixes.isEmpty()) {
736 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
737 if (mLastRaParams != null) {
738 addedPrefixes.removeAll(mLastRaParams.prefixes);
739 }
740
741 if (!addedPrefixes.isEmpty()) {
742 final ArrayList<RouteInfo> toBeAdded =
743 getLocalRoutesFor(mIfaceName, addedPrefixes);
744 try {
markchien12c5bb82020-01-07 14:43:17 +0800745 // It's safe to call networkAddInterface() even if
746 // the interface is already in the local_network.
747 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
748 try {
749 // Add routes from local network. Note that adding routes that
750 // already exist does not cause an error (EEXIST is silently ignored).
751 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
752 } catch (IllegalStateException e) {
753 mLog.e("Failed to add IPv6 routes to local table: " + e);
754 }
755 } catch (ServiceSpecificException | RemoteException e) {
756 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800757 }
758
759 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
760 }
761 }
762 }
763
764 private void configureLocalIPv6Dns(
765 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
766 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
767 if (mNetd == null) {
768 if (newDnses != null) newDnses.clear();
769 mLog.e("No netd service instance available; not setting local IPv6 addresses");
770 return;
771 }
772
773 // [1] Remove deprecated local DNS IP addresses.
774 if (!deprecatedDnses.isEmpty()) {
775 for (Inet6Address dns : deprecatedDnses) {
776 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
777 mLog.e("Failed to remove local dns IP " + dns);
778 }
779
780 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
781 }
782 }
783
784 // [2] Add only the local DNS IP addresses that have not previously been added.
785 if (newDnses != null && !newDnses.isEmpty()) {
786 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
787 if (mLastRaParams != null) {
788 addedDnses.removeAll(mLastRaParams.dnses);
789 }
790
791 for (Inet6Address dns : addedDnses) {
792 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
793 mLog.e("Failed to add local dns IP " + dns);
794 newDnses.remove(dns);
795 }
796
797 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
798 }
799 }
800
801 try {
802 mNetd.tetherApplyDnsInterfaces();
803 } catch (ServiceSpecificException | RemoteException e) {
804 mLog.e("Failed to update local DNS caching server");
805 if (newDnses != null) newDnses.clear();
806 }
807 }
808
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900809 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
810 try {
811 mNetd.tetherRuleAddDownstreamIpv6(mInterfaceParams.index, rule.upstreamIfindex,
812 rule.address.getAddress(), mInterfaceParams.macAddr.toByteArray(),
813 rule.dstMac.toByteArray());
814 mIpv6ForwardingRules.put(rule.address, rule);
815 } catch (RemoteException | ServiceSpecificException e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900816 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900817 }
818 }
819
820 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
821 try {
822 mNetd.tetherRuleRemoveDownstreamIpv6(rule.upstreamIfindex, rule.address.getAddress());
823 if (removeFromMap) {
824 mIpv6ForwardingRules.remove(rule.address);
825 }
826 } catch (RemoteException | ServiceSpecificException e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900827 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900828 }
829 }
830
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900831 private void clearIpv6ForwardingRules() {
832 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
833 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
834 }
835 mIpv6ForwardingRules.clear();
836 }
837
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900838 // Convenience method to replace a rule with the same rule on a new upstream interface.
839 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
840 // Relies on the fact that rules are in a map indexed by IP address.
841 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
842 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
843 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
844 }
845
846 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
847 // changes or if a neighbor event is received.
848 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
849 NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900850 // If we no longer have an upstream, clear forwarding rules and do nothing else.
851 if (upstreamIfindex == 0) {
852 clearIpv6ForwardingRules();
853 return;
854 }
855
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900856 // If the upstream interface has changed, remove all rules and re-add them with the new
857 // upstream interface.
858 if (prevUpstreamIfindex != upstreamIfindex) {
859 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
860 updateIpv6ForwardingRule(rule, upstreamIfindex);
861 }
862 }
863
864 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900865 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900866 if (e == null) return;
867 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
868 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
869 return;
870 }
871
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900872 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900873 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr,
874 e.macAddr);
875 if (e.isValid()) {
876 addIpv6ForwardingRule(rule);
877 } else {
878 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
879 }
880 }
881
882 private void handleNeighborEvent(NeighborEvent e) {
883 if (mInterfaceParams != null
884 && mInterfaceParams.index == e.ifindex
885 && mInterfaceParams.hasMacAddress) {
886 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
887 }
888 }
889
markchien74a4fa92019-09-09 20:50:49 +0800890 private byte getHopLimit(String upstreamIface) {
891 try {
892 int upstreamHopLimit = Integer.parseUnsignedInt(
893 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
894 // Add one hop to account for this forwarding device
895 upstreamHopLimit++;
896 // Cap the hop limit to 255.
897 return (byte) Integer.min(upstreamHopLimit, 255);
898 } catch (Exception e) {
899 mLog.e("Failed to find upstream interface hop limit", e);
900 }
901 return RaParams.DEFAULT_HOPLIMIT;
902 }
903
904 private void setRaParams(RaParams newParams) {
905 if (mRaDaemon != null) {
906 final RaParams deprecatedParams =
907 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
908
909 configureLocalIPv6Routes(deprecatedParams.prefixes,
910 (newParams != null) ? newParams.prefixes : null);
911
912 configureLocalIPv6Dns(deprecatedParams.dnses,
913 (newParams != null) ? newParams.dnses : null);
914
915 mRaDaemon.buildNewRa(deprecatedParams, newParams);
916 }
917
918 mLastRaParams = newParams;
919 }
920
921 private void logMessage(State state, int what) {
922 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
923 }
924
925 private void sendInterfaceState(int newInterfaceState) {
926 mServingMode = newInterfaceState;
927 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
928 sendLinkProperties();
929 }
930
931 private void sendLinkProperties() {
932 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
933 }
934
935 private void resetLinkProperties() {
936 mLinkProperties.clear();
937 mLinkProperties.setInterfaceName(mIfaceName);
938 }
939
940 class InitialState extends State {
941 @Override
942 public void enter() {
943 sendInterfaceState(STATE_AVAILABLE);
944 }
945
946 @Override
947 public boolean processMessage(Message message) {
948 logMessage(this, message.what);
949 switch (message.what) {
950 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800951 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800952 switch (message.arg1) {
953 case STATE_LOCAL_ONLY:
954 transitionTo(mLocalHotspotState);
955 break;
956 case STATE_TETHERED:
957 transitionTo(mTetheredState);
958 break;
959 default:
960 mLog.e("Invalid tethering interface serving state specified.");
961 }
962 break;
963 case CMD_INTERFACE_DOWN:
964 transitionTo(mUnavailableState);
965 break;
966 case CMD_IPV6_TETHER_UPDATE:
967 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
968 break;
969 default:
970 return NOT_HANDLED;
971 }
972 return HANDLED;
973 }
974 }
975
976 class BaseServingState extends State {
977 @Override
978 public void enter() {
979 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +0800980 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800981 return;
982 }
983
984 try {
markchien12c5bb82020-01-07 14:43:17 +0800985 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
986 mIpv4Address.getPrefixLength());
987 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchien6c2b7cc2020-02-15 11:35:00 +0800988 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
markchien74a4fa92019-09-09 20:50:49 +0800989 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +0800990 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800991 return;
992 }
993
994 if (!startIPv6()) {
995 mLog.e("Failed to startIPv6");
996 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
997 return;
998 }
999 }
1000
1001 @Override
1002 public void exit() {
1003 // Note that at this point, we're leaving the tethered state. We can fail any
1004 // of these operations, but it doesn't really change that we have to try them
1005 // all in sequence.
1006 stopIPv6();
1007
1008 try {
markchien12c5bb82020-01-07 14:43:17 +08001009 NetdUtils.untetherInterface(mNetd, mIfaceName);
1010 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001011 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001012 mLog.e("Failed to untether interface: " + e);
1013 }
1014
1015 stopIPv4();
1016
1017 resetLinkProperties();
1018 }
1019
1020 @Override
1021 public boolean processMessage(Message message) {
1022 logMessage(this, message.what);
1023 switch (message.what) {
1024 case CMD_TETHER_UNREQUESTED:
1025 transitionTo(mInitialState);
1026 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1027 break;
1028 case CMD_INTERFACE_DOWN:
1029 transitionTo(mUnavailableState);
1030 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1031 break;
1032 case CMD_IPV6_TETHER_UPDATE:
1033 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1034 sendLinkProperties();
1035 break;
1036 case CMD_IP_FORWARDING_ENABLE_ERROR:
1037 case CMD_IP_FORWARDING_DISABLE_ERROR:
1038 case CMD_START_TETHERING_ERROR:
1039 case CMD_STOP_TETHERING_ERROR:
1040 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien9b4d7572019-12-25 19:40:32 +08001041 mLastError = TetheringManager.TETHER_ERROR_MASTER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001042 transitionTo(mInitialState);
1043 break;
1044 default:
1045 return false;
1046 }
1047 return true;
1048 }
1049 }
1050
1051 // Handling errors in BaseServingState.enter() by transitioning is
1052 // problematic because transitioning during a multi-state jump yields
1053 // a Log.wtf(). Ultimately, there should be only one ServingState,
1054 // and forwarding and NAT rules should be handled by a coordinating
1055 // functional element outside of IpServer.
1056 class LocalHotspotState extends BaseServingState {
1057 @Override
1058 public void enter() {
1059 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001060 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001061 transitionTo(mInitialState);
1062 }
1063
1064 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1065 sendInterfaceState(STATE_LOCAL_ONLY);
1066 }
1067
1068 @Override
1069 public boolean processMessage(Message message) {
1070 if (super.processMessage(message)) return true;
1071
1072 logMessage(this, message.what);
1073 switch (message.what) {
1074 case CMD_TETHER_REQUESTED:
1075 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1076 break;
1077 case CMD_TETHER_CONNECTION_CHANGED:
1078 // Ignored in local hotspot state.
1079 break;
1080 default:
1081 return false;
1082 }
1083 return true;
1084 }
1085 }
1086
1087 // Handling errors in BaseServingState.enter() by transitioning is
1088 // problematic because transitioning during a multi-state jump yields
1089 // a Log.wtf(). Ultimately, there should be only one ServingState,
1090 // and forwarding and NAT rules should be handled by a coordinating
1091 // functional element outside of IpServer.
1092 class TetheredState extends BaseServingState {
1093 @Override
1094 public void enter() {
1095 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001096 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001097 transitionTo(mInitialState);
1098 }
1099
1100 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1101 sendInterfaceState(STATE_TETHERED);
1102 }
1103
1104 @Override
1105 public void exit() {
1106 cleanupUpstream();
1107 super.exit();
1108 }
1109
1110 private void cleanupUpstream() {
1111 if (mUpstreamIfaceSet == null) return;
1112
1113 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1114 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001115 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001116 }
1117
1118 private void cleanupUpstreamInterface(String upstreamIface) {
1119 // Note that we don't care about errors here.
1120 // Sometimes interfaces are gone before we get
1121 // to remove their rules, which generates errors.
1122 // Just do the best we can.
1123 try {
markchien12c5bb82020-01-07 14:43:17 +08001124 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1125 } catch (RemoteException | ServiceSpecificException e) {
1126 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001127 }
1128 try {
markchien12c5bb82020-01-07 14:43:17 +08001129 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1130 } catch (RemoteException | ServiceSpecificException e) {
1131 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001132 }
1133 }
1134
1135 @Override
1136 public boolean processMessage(Message message) {
1137 if (super.processMessage(message)) return true;
1138
1139 logMessage(this, message.what);
1140 switch (message.what) {
1141 case CMD_TETHER_REQUESTED:
1142 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1143 break;
1144 case CMD_TETHER_CONNECTION_CHANGED:
1145 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1146 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1147 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1148 break;
1149 }
1150
1151 if (newUpstreamIfaceSet == null) {
1152 cleanupUpstream();
1153 break;
1154 }
1155
1156 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1157 cleanupUpstreamInterface(removed);
1158 }
1159
1160 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1161 // This makes the call to cleanupUpstream() in the error
1162 // path for any interface neatly cleanup all the interfaces.
1163 mUpstreamIfaceSet = newUpstreamIfaceSet;
1164
1165 for (String ifname : added) {
1166 try {
markchien12c5bb82020-01-07 14:43:17 +08001167 mNetd.tetherAddForward(mIfaceName, ifname);
1168 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1169 } catch (RemoteException | ServiceSpecificException e) {
1170 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001171 cleanupUpstream();
markchien9b4d7572019-12-25 19:40:32 +08001172 mLastError = TetheringManager.TETHER_ERROR_ENABLE_NAT_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001173 transitionTo(mInitialState);
1174 return true;
1175 }
1176 }
1177 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001178 case CMD_NEIGHBOR_EVENT:
1179 handleNeighborEvent((NeighborEvent) message.obj);
1180 break;
markchien74a4fa92019-09-09 20:50:49 +08001181 default:
1182 return false;
1183 }
1184 return true;
1185 }
1186
1187 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1188 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1189 if (mUpstreamIfaceSet != null && newIfaces != null) {
1190 return mUpstreamIfaceSet.equals(newIfaces);
1191 }
1192 return false;
1193 }
1194
1195 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1196 if (mUpstreamIfaceSet == null) return new HashSet<>();
1197
1198 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1199 removed.removeAll(newIfaces.ifnames);
1200 return removed;
1201 }
1202
1203 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1204 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1205 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1206 return added;
1207 }
1208 }
1209
1210 /**
1211 * This state is terminal for the per interface state machine. At this
1212 * point, the master state machine should have removed this interface
1213 * specific state machine from its list of possible recipients of
1214 * tethering requests. The state machine itself will hang around until
1215 * the garbage collector finds it.
1216 */
1217 class UnavailableState extends State {
1218 @Override
1219 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001220 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001221 sendInterfaceState(STATE_UNAVAILABLE);
1222 }
1223 }
1224
1225 // Accumulate routes representing "prefixes to be assigned to the local
1226 // interface", for subsequent modification of local_network routing.
1227 private static ArrayList<RouteInfo> getLocalRoutesFor(
1228 String ifname, HashSet<IpPrefix> prefixes) {
1229 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1230 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001231 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001232 }
1233 return localRoutes;
1234 }
1235
1236 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1237 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1238 final byte[] dnsBytes = localPrefix.getRawAddress();
1239 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1240 try {
1241 return Inet6Address.getByAddress(null, dnsBytes, 0);
1242 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001243 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001244 return null;
1245 }
1246 }
1247
1248 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1249 final byte random = (byte) (new Random()).nextInt();
1250 for (int value : excluded) {
1251 if (random == value) return dflt;
1252 }
1253 return random;
1254 }
1255}