blob: 5f5de9ea6bd3612dc129abfe5d6c46657ada0100 [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;
markchien74a4fa92019-09-09 20:50:49 +080027
markchien74a4fa92019-09-09 20:50:49 +080028import android.net.INetd;
29import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080030import android.net.IpPrefix;
31import android.net.LinkAddress;
32import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090033import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080034import android.net.RouteInfo;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090035import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080036import android.net.TetheringManager;
markchienf053e4b2020-03-16 21:49:48 +080037import android.net.TetheringRequestParcel;
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;
markchienf053e4b2020-03-16 21:49:48 +0800246
247 private LinkAddress mStaticIpv4ServerAddr;
248 private LinkAddress mStaticIpv4ClientAddr;
249
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900250 @NonNull
251 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800252
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900253 private int mLastIPv6UpstreamIfindex = 0;
254
255 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
256 public void accept(NeighborEvent e) {
257 sendMessage(CMD_NEIGHBOR_EVENT, e);
258 }
259 }
260
261 static class Ipv6ForwardingRule {
262 public final int upstreamIfindex;
263 public final int downstreamIfindex;
264 public final Inet6Address address;
265 public final MacAddress srcMac;
266 public final MacAddress dstMac;
267
268 Ipv6ForwardingRule(int upstreamIfindex, int downstreamIfIndex, Inet6Address address,
269 MacAddress srcMac, MacAddress dstMac) {
270 this.upstreamIfindex = upstreamIfindex;
271 this.downstreamIfindex = downstreamIfIndex;
272 this.address = address;
273 this.srcMac = srcMac;
274 this.dstMac = dstMac;
275 }
276
277 public Ipv6ForwardingRule onNewUpstream(int newUpstreamIfindex) {
278 return new Ipv6ForwardingRule(newUpstreamIfindex, downstreamIfindex, address, srcMac,
279 dstMac);
280 }
281 }
282 private final LinkedHashMap<Inet6Address, Ipv6ForwardingRule> mIpv6ForwardingRules =
283 new LinkedHashMap<>();
284
285 private final IpNeighborMonitor mIpNeighborMonitor;
286
markchien74a4fa92019-09-09 20:50:49 +0800287 public IpServer(
288 String ifaceName, Looper looper, int interfaceType, SharedLog log,
junyulai5864a3f2019-12-03 14:34:13 +0800289 INetd netd, Callback callback, boolean usingLegacyDhcp, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800290 super(ifaceName, looper);
291 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800292 mNetd = netd;
markchien74a4fa92019-09-09 20:50:49 +0800293 mCallback = callback;
294 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
295 mIfaceName = ifaceName;
296 mInterfaceType = interfaceType;
297 mLinkProperties = new LinkProperties();
298 mUsingLegacyDhcp = usingLegacyDhcp;
299 mDeps = deps;
300 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800301 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800302 mServingMode = STATE_AVAILABLE;
303
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900304 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
305 new MyNeighborEventConsumer());
306 if (!mIpNeighborMonitor.start()) {
307 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
308 }
309
markchien74a4fa92019-09-09 20:50:49 +0800310 mInitialState = new InitialState();
311 mLocalHotspotState = new LocalHotspotState();
312 mTetheredState = new TetheredState();
313 mUnavailableState = new UnavailableState();
314 addState(mInitialState);
315 addState(mLocalHotspotState);
316 addState(mTetheredState);
317 addState(mUnavailableState);
318
319 setInitialState(mInitialState);
320 }
321
322 /** Interface name which IpServer served.*/
323 public String interfaceName() {
324 return mIfaceName;
325 }
326
327 /**
markchien9b4d7572019-12-25 19:40:32 +0800328 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800329 */
330 public int interfaceType() {
331 return mInterfaceType;
332 }
333
334 /** Last error from this IpServer. */
335 public int lastError() {
336 return mLastError;
337 }
338
339 /** Serving mode is the current state of IpServer state machine. */
340 public int servingMode() {
341 return mServingMode;
342 }
343
344 /** The properties of the network link which IpServer is serving. */
345 public LinkProperties linkProperties() {
346 return new LinkProperties(mLinkProperties);
347 }
348
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900349 /**
350 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
351 * thread.
352 */
353 public List<TetheredClient> getAllLeases() {
354 return Collections.unmodifiableList(mDhcpLeases);
355 }
356
markchien74a4fa92019-09-09 20:50:49 +0800357 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
358 public void stop() {
359 sendMessage(CMD_INTERFACE_DOWN);
360 }
361
362 /**
363 * Tethering is canceled. IpServer state machine will be available and wait for
364 * next tethering request.
365 */
366 public void unwanted() {
367 sendMessage(CMD_TETHER_UNREQUESTED);
368 }
369
370 /** Internals. */
371
372 private boolean startIPv4() {
373 return configureIPv4(true);
374 }
375
376 /**
377 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
378 * handler.
379 *
380 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
381 * with different implementations of the callback, to differentiate handling of success/error in
382 * each call.
383 */
384 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
385 @Override
386 public void onStatusAvailable(int statusCode) {
387 getHandler().post(() -> callback(statusCode));
388 }
389
390 public abstract void callback(int statusCode);
391
392 @Override
393 public int getInterfaceVersion() {
394 return this.VERSION;
395 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900396
397 @Override
398 public String getInterfaceHash() {
399 return this.HASH;
400 }
markchien74a4fa92019-09-09 20:50:49 +0800401 }
402
403 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
404 private final int mStartIndex;
405
406 private DhcpServerCallbacksImpl(int startIndex) {
407 mStartIndex = startIndex;
408 }
409
410 @Override
411 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
412 getHandler().post(() -> {
413 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
414 if (mStartIndex != mDhcpServerStartIndex) {
415 // This start request is obsolete. When the |server| binder token goes out of
416 // scope, the garbage collector will finalize it, which causes the network stack
417 // process garbage collector to collect the server itself.
418 return;
419 }
420
421 if (statusCode != STATUS_SUCCESS) {
422 mLog.e("Error obtaining DHCP server: " + statusCode);
423 handleError();
424 return;
425 }
426
427 mDhcpServer = server;
428 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900429 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800430 @Override
431 public void callback(int startStatusCode) {
432 if (startStatusCode != STATUS_SUCCESS) {
433 mLog.e("Error starting DHCP server: " + startStatusCode);
434 handleError();
435 }
436 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900437 }, new DhcpLeaseCallback());
markchien74a4fa92019-09-09 20:50:49 +0800438 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800439 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800440 }
441 });
442 }
443
444 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800445 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800446 transitionTo(mInitialState);
447 }
448 }
449
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900450 private class DhcpLeaseCallback extends IDhcpLeaseCallbacks.Stub {
451 @Override
452 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
453 final ArrayList<TetheredClient> leases = new ArrayList<>();
454 for (DhcpLeaseParcelable lease : leaseParcelables) {
455 final LinkAddress address = new LinkAddress(
456 intToInet4AddressHTH(lease.netAddr), lease.prefixLength);
457
458 final MacAddress macAddress;
459 try {
460 macAddress = MacAddress.fromBytes(lease.hwAddr);
461 } catch (IllegalArgumentException e) {
462 Log.wtf(TAG, "Invalid address received from DhcpServer: "
463 + Arrays.toString(lease.hwAddr));
464 return;
465 }
466
467 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
468 address, lease.hostname, lease.expTime);
469 leases.add(new TetheredClient(
470 macAddress,
471 Collections.singletonList(addressInfo),
472 mInterfaceType));
473 }
474
475 getHandler().post(() -> {
476 mDhcpLeases = leases;
477 mCallback.dhcpLeasesChanged();
478 });
479 }
480
481 @Override
482 public int getInterfaceVersion() {
483 return this.VERSION;
484 }
485
486 @Override
487 public String getInterfaceHash() throws RemoteException {
488 return this.HASH;
489 }
490 }
491
markchien74a4fa92019-09-09 20:50:49 +0800492 private boolean startDhcp(Inet4Address addr, int prefixLen) {
493 if (mUsingLegacyDhcp) {
494 return true;
495 }
496 final DhcpServingParamsParcel params;
497 params = new DhcpServingParamsParcelExt()
498 .setDefaultRouters(addr)
499 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
500 .setDnsServers(addr)
501 .setServerAddr(new LinkAddress(addr, prefixLen))
502 .setMetered(true);
503 // TODO: also advertise link MTU
504
505 mDhcpServerStartIndex++;
506 mDeps.makeDhcpServer(
507 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
508 return true;
509 }
510
511 private void stopDhcp() {
512 // Make all previous start requests obsolete so servers are not started later
513 mDhcpServerStartIndex++;
514
515 if (mDhcpServer != null) {
516 try {
517 mDhcpServer.stop(new OnHandlerStatusCallback() {
518 @Override
519 public void callback(int statusCode) {
520 if (statusCode != STATUS_SUCCESS) {
521 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800522 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800523 // Not much more we can do here
524 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900525 mDhcpLeases.clear();
526 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800527 }
528 });
529 mDhcpServer = null;
530 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800531 mLog.e("Error stopping DHCP", e);
532 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800533 }
534 }
535 }
536
537 private boolean configureDhcp(boolean enable, Inet4Address addr, int prefixLen) {
538 if (enable) {
539 return startDhcp(addr, prefixLen);
540 } else {
541 stopDhcp();
542 return true;
543 }
544 }
545
546 private void stopIPv4() {
547 configureIPv4(false);
548 // NOTE: All of configureIPv4() will be refactored out of existence
549 // into calls to InterfaceController, shared with startIPv4().
550 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800551 mIpv4Address = null;
markchienf053e4b2020-03-16 21:49:48 +0800552 mStaticIpv4ServerAddr = null;
553 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800554 }
555
markchien74a4fa92019-09-09 20:50:49 +0800556 private boolean configureIPv4(boolean enabled) {
557 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
558
559 // TODO: Replace this hard-coded information with dynamically selected
560 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800561 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800562 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800563 try {
markchienf053e4b2020-03-16 21:49:48 +0800564 if (mStaticIpv4ServerAddr != null) {
565 srvAddr = (Inet4Address) mStaticIpv4ServerAddr.getAddress();
566 prefixLen = mStaticIpv4ServerAddr.getPrefixLength();
567 } else if (mInterfaceType == TetheringManager.TETHERING_USB
Milim Lee45a971b2019-10-17 05:02:33 +0900568 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien12c5bb82020-01-07 14:43:17 +0800569 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
570 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800571 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800572 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
573 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800574 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800575 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
576 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900577 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
578 // TODO: randomize address for tethering too, similarly to wifi
579 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
580 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien12c5bb82020-01-07 14:43:17 +0800581 } else {
582 // BT configures the interface elsewhere: only start DHCP.
583 // TODO: make all tethering types behave the same way, and delete the bluetooth
584 // code that calls into NetworkManagementService directly.
585 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
586 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
587 return configureDhcp(enabled, srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
588 }
589 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
590 } catch (IllegalArgumentException e) {
591 mLog.e("Error selecting ipv4 address", e);
592 if (!enabled) stopDhcp();
593 return false;
markchien74a4fa92019-09-09 20:50:49 +0800594 }
595
markchien12c5bb82020-01-07 14:43:17 +0800596 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800597 if (mInterfaceType == TetheringManager.TETHERING_WIFI
598 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800599 // The WiFi stack has ownership of the interface up/down state.
600 // It is unclear whether the Bluetooth or USB stacks will manage their own
601 // state.
602 setIfaceUp = null;
603 } else {
604 setIfaceUp = enabled;
605 }
606 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
607 mLog.e("Error configuring interface");
608 if (!enabled) stopDhcp();
609 return false;
610 }
markchien74a4fa92019-09-09 20:50:49 +0800611
markchien74a4fa92019-09-09 20:50:49 +0800612 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800613 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
614 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800615 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800616 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800617 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800618 mLinkProperties.addRoute(route);
619 } else {
markchien12c5bb82020-01-07 14:43:17 +0800620 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800621 mLinkProperties.removeRoute(route);
622 }
markchienf053e4b2020-03-16 21:49:48 +0800623
624 return configureDhcp(enabled, srvAddr, prefixLen);
markchien74a4fa92019-09-09 20:50:49 +0800625 }
626
627 private String getRandomWifiIPv4Address() {
628 try {
629 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
630 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
631 return InetAddress.getByAddress(bytes).getHostAddress();
632 } catch (Exception e) {
633 return WIFI_HOST_IFACE_ADDR;
634 }
635 }
636
637 private boolean startIPv6() {
638 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
639 if (mInterfaceParams == null) {
640 mLog.e("Failed to find InterfaceParams");
641 stopIPv6();
642 return false;
643 }
644
645 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
646 if (!mRaDaemon.start()) {
647 stopIPv6();
648 return false;
649 }
650
651 return true;
652 }
653
654 private void stopIPv6() {
655 mInterfaceParams = null;
656 setRaParams(null);
657
658 if (mRaDaemon != null) {
659 mRaDaemon.stop();
660 mRaDaemon = null;
661 }
662 }
663
664 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
665 // LinkProperties. These have extraneous data filtered out and only the
666 // necessary prefixes included (per its prefix distribution policy).
667 //
668 // TODO: Evaluate using a data structure than is more directly suited to
669 // communicating only the relevant information.
670 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
671 if (mRaDaemon == null) return;
672
673 // Avoid unnecessary work on spurious updates.
674 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
675 return;
676 }
677
678 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900679 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800680
681 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900682 final String upstreamIface = v6only.getInterfaceName();
683
markchien74a4fa92019-09-09 20:50:49 +0800684 params = new RaParams();
Maciej Żenczykowskida0fb1b2020-02-19 01:24:39 -0800685 // We advertise an mtu lower by 16, which is the closest multiple of 8 >= 14,
686 // the ethernet header size. This makes kernel ebpf tethering offload happy.
687 // This hack should be reverted once we have the kernel fixed up.
688 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
689 // see RouterAdvertisementDaemon.java putMtu()
690 params.mtu = v6only.getMtu() - 16;
markchien74a4fa92019-09-09 20:50:49 +0800691 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
692
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900693 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800694
695 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
696 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
697
698 final IpPrefix prefix = new IpPrefix(
699 linkAddr.getAddress(), linkAddr.getPrefixLength());
700 params.prefixes.add(prefix);
701
702 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
703 if (dnsServer != null) {
704 params.dnses.add(dnsServer);
705 }
706 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900707
708 upstreamIfindex = mDeps.getIfindex(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800709 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900710
markchien74a4fa92019-09-09 20:50:49 +0800711 // If v6only is null, we pass in null to setRaParams(), which handles
712 // deprecation of any existing RA data.
713
714 setRaParams(params);
715 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900716
717 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
718 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800719 }
720
721 private void configureLocalIPv6Routes(
722 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
723 // [1] Remove the routes that are deprecated.
724 if (!deprecatedPrefixes.isEmpty()) {
725 final ArrayList<RouteInfo> toBeRemoved =
726 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800727 // Remove routes from local network.
728 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
729 mNetd, toBeRemoved);
730 if (removalFailures > 0) {
731 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
732 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800733 }
734
735 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
736 }
737
738 // [2] Add only the routes that have not previously been added.
739 if (newPrefixes != null && !newPrefixes.isEmpty()) {
740 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
741 if (mLastRaParams != null) {
742 addedPrefixes.removeAll(mLastRaParams.prefixes);
743 }
744
745 if (!addedPrefixes.isEmpty()) {
746 final ArrayList<RouteInfo> toBeAdded =
747 getLocalRoutesFor(mIfaceName, addedPrefixes);
748 try {
markchien12c5bb82020-01-07 14:43:17 +0800749 // It's safe to call networkAddInterface() even if
750 // the interface is already in the local_network.
751 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
752 try {
753 // Add routes from local network. Note that adding routes that
754 // already exist does not cause an error (EEXIST is silently ignored).
755 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
756 } catch (IllegalStateException e) {
757 mLog.e("Failed to add IPv6 routes to local table: " + e);
758 }
759 } catch (ServiceSpecificException | RemoteException e) {
760 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800761 }
762
763 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
764 }
765 }
766 }
767
768 private void configureLocalIPv6Dns(
769 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
770 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
771 if (mNetd == null) {
772 if (newDnses != null) newDnses.clear();
773 mLog.e("No netd service instance available; not setting local IPv6 addresses");
774 return;
775 }
776
777 // [1] Remove deprecated local DNS IP addresses.
778 if (!deprecatedDnses.isEmpty()) {
779 for (Inet6Address dns : deprecatedDnses) {
780 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
781 mLog.e("Failed to remove local dns IP " + dns);
782 }
783
784 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
785 }
786 }
787
788 // [2] Add only the local DNS IP addresses that have not previously been added.
789 if (newDnses != null && !newDnses.isEmpty()) {
790 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
791 if (mLastRaParams != null) {
792 addedDnses.removeAll(mLastRaParams.dnses);
793 }
794
795 for (Inet6Address dns : addedDnses) {
796 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
797 mLog.e("Failed to add local dns IP " + dns);
798 newDnses.remove(dns);
799 }
800
801 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
802 }
803 }
804
805 try {
806 mNetd.tetherApplyDnsInterfaces();
807 } catch (ServiceSpecificException | RemoteException e) {
808 mLog.e("Failed to update local DNS caching server");
809 if (newDnses != null) newDnses.clear();
810 }
811 }
812
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900813 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
814 try {
815 mNetd.tetherRuleAddDownstreamIpv6(mInterfaceParams.index, rule.upstreamIfindex,
816 rule.address.getAddress(), mInterfaceParams.macAddr.toByteArray(),
817 rule.dstMac.toByteArray());
818 mIpv6ForwardingRules.put(rule.address, rule);
819 } catch (RemoteException | ServiceSpecificException e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900820 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900821 }
822 }
823
824 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
825 try {
826 mNetd.tetherRuleRemoveDownstreamIpv6(rule.upstreamIfindex, rule.address.getAddress());
827 if (removeFromMap) {
828 mIpv6ForwardingRules.remove(rule.address);
829 }
830 } catch (RemoteException | ServiceSpecificException e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900831 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900832 }
833 }
834
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900835 private void clearIpv6ForwardingRules() {
836 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
837 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
838 }
839 mIpv6ForwardingRules.clear();
840 }
841
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900842 // Convenience method to replace a rule with the same rule on a new upstream interface.
843 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
844 // Relies on the fact that rules are in a map indexed by IP address.
845 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
846 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
847 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
848 }
849
850 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
851 // changes or if a neighbor event is received.
852 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
853 NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900854 // If we no longer have an upstream, clear forwarding rules and do nothing else.
855 if (upstreamIfindex == 0) {
856 clearIpv6ForwardingRules();
857 return;
858 }
859
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900860 // If the upstream interface has changed, remove all rules and re-add them with the new
861 // upstream interface.
862 if (prevUpstreamIfindex != upstreamIfindex) {
863 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
864 updateIpv6ForwardingRule(rule, upstreamIfindex);
865 }
866 }
867
868 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900869 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900870 if (e == null) return;
871 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
872 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
873 return;
874 }
875
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900876 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900877 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr,
878 e.macAddr);
879 if (e.isValid()) {
880 addIpv6ForwardingRule(rule);
881 } else {
882 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
883 }
884 }
885
886 private void handleNeighborEvent(NeighborEvent e) {
887 if (mInterfaceParams != null
888 && mInterfaceParams.index == e.ifindex
889 && mInterfaceParams.hasMacAddress) {
890 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
891 }
892 }
893
markchien74a4fa92019-09-09 20:50:49 +0800894 private byte getHopLimit(String upstreamIface) {
895 try {
896 int upstreamHopLimit = Integer.parseUnsignedInt(
897 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
898 // Add one hop to account for this forwarding device
899 upstreamHopLimit++;
900 // Cap the hop limit to 255.
901 return (byte) Integer.min(upstreamHopLimit, 255);
902 } catch (Exception e) {
903 mLog.e("Failed to find upstream interface hop limit", e);
904 }
905 return RaParams.DEFAULT_HOPLIMIT;
906 }
907
908 private void setRaParams(RaParams newParams) {
909 if (mRaDaemon != null) {
910 final RaParams deprecatedParams =
911 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
912
913 configureLocalIPv6Routes(deprecatedParams.prefixes,
914 (newParams != null) ? newParams.prefixes : null);
915
916 configureLocalIPv6Dns(deprecatedParams.dnses,
917 (newParams != null) ? newParams.dnses : null);
918
919 mRaDaemon.buildNewRa(deprecatedParams, newParams);
920 }
921
922 mLastRaParams = newParams;
923 }
924
925 private void logMessage(State state, int what) {
926 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
927 }
928
929 private void sendInterfaceState(int newInterfaceState) {
930 mServingMode = newInterfaceState;
931 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
932 sendLinkProperties();
933 }
934
935 private void sendLinkProperties() {
936 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
937 }
938
939 private void resetLinkProperties() {
940 mLinkProperties.clear();
941 mLinkProperties.setInterfaceName(mIfaceName);
942 }
943
markchienf053e4b2020-03-16 21:49:48 +0800944 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
945 if (request == null) return;
946
947 mStaticIpv4ServerAddr = request.localIPv4Address;
948 mStaticIpv4ClientAddr = request.staticClientAddress;
949 }
950
markchien74a4fa92019-09-09 20:50:49 +0800951 class InitialState extends State {
952 @Override
953 public void enter() {
954 sendInterfaceState(STATE_AVAILABLE);
955 }
956
957 @Override
958 public boolean processMessage(Message message) {
959 logMessage(this, message.what);
960 switch (message.what) {
961 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800962 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800963 switch (message.arg1) {
964 case STATE_LOCAL_ONLY:
markchienf053e4b2020-03-16 21:49:48 +0800965 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +0800966 transitionTo(mLocalHotspotState);
967 break;
968 case STATE_TETHERED:
markchienf053e4b2020-03-16 21:49:48 +0800969 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +0800970 transitionTo(mTetheredState);
971 break;
972 default:
973 mLog.e("Invalid tethering interface serving state specified.");
974 }
975 break;
976 case CMD_INTERFACE_DOWN:
977 transitionTo(mUnavailableState);
978 break;
979 case CMD_IPV6_TETHER_UPDATE:
980 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
981 break;
982 default:
983 return NOT_HANDLED;
984 }
985 return HANDLED;
986 }
987 }
988
989 class BaseServingState extends State {
990 @Override
991 public void enter() {
992 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +0800993 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800994 return;
995 }
996
997 try {
markchien12c5bb82020-01-07 14:43:17 +0800998 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
999 mIpv4Address.getPrefixLength());
1000 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchien6c2b7cc2020-02-15 11:35:00 +08001001 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
markchien74a4fa92019-09-09 20:50:49 +08001002 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +08001003 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001004 return;
1005 }
1006
1007 if (!startIPv6()) {
1008 mLog.e("Failed to startIPv6");
1009 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1010 return;
1011 }
1012 }
1013
1014 @Override
1015 public void exit() {
1016 // Note that at this point, we're leaving the tethered state. We can fail any
1017 // of these operations, but it doesn't really change that we have to try them
1018 // all in sequence.
1019 stopIPv6();
1020
1021 try {
markchien12c5bb82020-01-07 14:43:17 +08001022 NetdUtils.untetherInterface(mNetd, mIfaceName);
1023 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001024 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001025 mLog.e("Failed to untether interface: " + e);
1026 }
1027
1028 stopIPv4();
1029
1030 resetLinkProperties();
1031 }
1032
1033 @Override
1034 public boolean processMessage(Message message) {
1035 logMessage(this, message.what);
1036 switch (message.what) {
1037 case CMD_TETHER_UNREQUESTED:
1038 transitionTo(mInitialState);
1039 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1040 break;
1041 case CMD_INTERFACE_DOWN:
1042 transitionTo(mUnavailableState);
1043 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1044 break;
1045 case CMD_IPV6_TETHER_UPDATE:
1046 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1047 sendLinkProperties();
1048 break;
1049 case CMD_IP_FORWARDING_ENABLE_ERROR:
1050 case CMD_IP_FORWARDING_DISABLE_ERROR:
1051 case CMD_START_TETHERING_ERROR:
1052 case CMD_STOP_TETHERING_ERROR:
1053 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien9b4d7572019-12-25 19:40:32 +08001054 mLastError = TetheringManager.TETHER_ERROR_MASTER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001055 transitionTo(mInitialState);
1056 break;
1057 default:
1058 return false;
1059 }
1060 return true;
1061 }
1062 }
1063
1064 // Handling errors in BaseServingState.enter() by transitioning is
1065 // problematic because transitioning during a multi-state jump yields
1066 // a Log.wtf(). Ultimately, there should be only one ServingState,
1067 // and forwarding and NAT rules should be handled by a coordinating
1068 // functional element outside of IpServer.
1069 class LocalHotspotState extends BaseServingState {
1070 @Override
1071 public void enter() {
1072 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001073 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001074 transitionTo(mInitialState);
1075 }
1076
1077 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1078 sendInterfaceState(STATE_LOCAL_ONLY);
1079 }
1080
1081 @Override
1082 public boolean processMessage(Message message) {
1083 if (super.processMessage(message)) return true;
1084
1085 logMessage(this, message.what);
1086 switch (message.what) {
1087 case CMD_TETHER_REQUESTED:
1088 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1089 break;
1090 case CMD_TETHER_CONNECTION_CHANGED:
1091 // Ignored in local hotspot state.
1092 break;
1093 default:
1094 return false;
1095 }
1096 return true;
1097 }
1098 }
1099
1100 // Handling errors in BaseServingState.enter() by transitioning is
1101 // problematic because transitioning during a multi-state jump yields
1102 // a Log.wtf(). Ultimately, there should be only one ServingState,
1103 // and forwarding and NAT rules should be handled by a coordinating
1104 // functional element outside of IpServer.
1105 class TetheredState extends BaseServingState {
1106 @Override
1107 public void enter() {
1108 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001109 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001110 transitionTo(mInitialState);
1111 }
1112
1113 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1114 sendInterfaceState(STATE_TETHERED);
1115 }
1116
1117 @Override
1118 public void exit() {
1119 cleanupUpstream();
1120 super.exit();
1121 }
1122
1123 private void cleanupUpstream() {
1124 if (mUpstreamIfaceSet == null) return;
1125
1126 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1127 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001128 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001129 }
1130
1131 private void cleanupUpstreamInterface(String upstreamIface) {
1132 // Note that we don't care about errors here.
1133 // Sometimes interfaces are gone before we get
1134 // to remove their rules, which generates errors.
1135 // Just do the best we can.
1136 try {
markchien12c5bb82020-01-07 14:43:17 +08001137 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1138 } catch (RemoteException | ServiceSpecificException e) {
1139 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001140 }
1141 try {
markchien12c5bb82020-01-07 14:43:17 +08001142 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1143 } catch (RemoteException | ServiceSpecificException e) {
1144 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001145 }
1146 }
1147
1148 @Override
1149 public boolean processMessage(Message message) {
1150 if (super.processMessage(message)) return true;
1151
1152 logMessage(this, message.what);
1153 switch (message.what) {
1154 case CMD_TETHER_REQUESTED:
1155 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1156 break;
1157 case CMD_TETHER_CONNECTION_CHANGED:
1158 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1159 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1160 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1161 break;
1162 }
1163
1164 if (newUpstreamIfaceSet == null) {
1165 cleanupUpstream();
1166 break;
1167 }
1168
1169 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1170 cleanupUpstreamInterface(removed);
1171 }
1172
1173 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1174 // This makes the call to cleanupUpstream() in the error
1175 // path for any interface neatly cleanup all the interfaces.
1176 mUpstreamIfaceSet = newUpstreamIfaceSet;
1177
1178 for (String ifname : added) {
1179 try {
markchien12c5bb82020-01-07 14:43:17 +08001180 mNetd.tetherAddForward(mIfaceName, ifname);
1181 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1182 } catch (RemoteException | ServiceSpecificException e) {
1183 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001184 cleanupUpstream();
markchien9b4d7572019-12-25 19:40:32 +08001185 mLastError = TetheringManager.TETHER_ERROR_ENABLE_NAT_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001186 transitionTo(mInitialState);
1187 return true;
1188 }
1189 }
1190 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001191 case CMD_NEIGHBOR_EVENT:
1192 handleNeighborEvent((NeighborEvent) message.obj);
1193 break;
markchien74a4fa92019-09-09 20:50:49 +08001194 default:
1195 return false;
1196 }
1197 return true;
1198 }
1199
1200 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1201 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1202 if (mUpstreamIfaceSet != null && newIfaces != null) {
1203 return mUpstreamIfaceSet.equals(newIfaces);
1204 }
1205 return false;
1206 }
1207
1208 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1209 if (mUpstreamIfaceSet == null) return new HashSet<>();
1210
1211 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1212 removed.removeAll(newIfaces.ifnames);
1213 return removed;
1214 }
1215
1216 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1217 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1218 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1219 return added;
1220 }
1221 }
1222
1223 /**
1224 * This state is terminal for the per interface state machine. At this
1225 * point, the master state machine should have removed this interface
1226 * specific state machine from its list of possible recipients of
1227 * tethering requests. The state machine itself will hang around until
1228 * the garbage collector finds it.
1229 */
1230 class UnavailableState extends State {
1231 @Override
1232 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001233 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001234 sendInterfaceState(STATE_UNAVAILABLE);
1235 }
1236 }
1237
1238 // Accumulate routes representing "prefixes to be assigned to the local
1239 // interface", for subsequent modification of local_network routing.
1240 private static ArrayList<RouteInfo> getLocalRoutesFor(
1241 String ifname, HashSet<IpPrefix> prefixes) {
1242 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1243 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001244 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001245 }
1246 return localRoutes;
1247 }
1248
1249 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1250 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1251 final byte[] dnsBytes = localPrefix.getRawAddress();
1252 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1253 try {
1254 return Inet6Address.getByAddress(null, dnsBytes, 0);
1255 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001256 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001257 return null;
1258 }
1259 }
1260
1261 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1262 final byte random = (byte) (new Random()).nextInt();
1263 for (int value : excluded) {
1264 if (random == value) return dflt;
1265 }
1266 return random;
1267 }
1268}