blob: 3acc7665773192f87112551f61e003158f822410 [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;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090037import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080038import android.net.dhcp.DhcpServerCallbacks;
39import android.net.dhcp.DhcpServingParamsParcel;
40import android.net.dhcp.DhcpServingParamsParcelExt;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090041import android.net.dhcp.IDhcpLeaseCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080042import android.net.dhcp.IDhcpServer;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090043import android.net.ip.IpNeighborMonitor.NeighborEvent;
markchien74a4fa92019-09-09 20:50:49 +080044import android.net.ip.RouterAdvertisementDaemon.RaParams;
markchien12c5bb82020-01-07 14:43:17 +080045import android.net.shared.NetdUtils;
46import android.net.shared.RouteUtils;
markchien74a4fa92019-09-09 20:50:49 +080047import android.net.util.InterfaceParams;
48import android.net.util.InterfaceSet;
markchien74a4fa92019-09-09 20:50:49 +080049import android.net.util.SharedLog;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090050import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080051import android.os.Looper;
52import android.os.Message;
53import android.os.RemoteException;
54import android.os.ServiceSpecificException;
55import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080056import android.util.SparseArray;
57
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090058import androidx.annotation.NonNull;
59
markchien74a4fa92019-09-09 20:50:49 +080060import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080061import com.android.internal.util.State;
62import com.android.internal.util.StateMachine;
63
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090064import java.io.IOException;
markchien74a4fa92019-09-09 20:50:49 +080065import java.net.Inet4Address;
66import java.net.Inet6Address;
67import java.net.InetAddress;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090068import java.net.NetworkInterface;
markchien74a4fa92019-09-09 20:50:49 +080069import java.net.UnknownHostException;
70import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090071import java.util.Arrays;
72import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080073import java.util.HashSet;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090074import java.util.LinkedHashMap;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090075import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080076import java.util.Objects;
77import java.util.Random;
78import java.util.Set;
79
80/**
81 * Provides the interface to IP-layer serving functionality for a given network
82 * interface, e.g. for tethering or "local-only hotspot" mode.
83 *
84 * @hide
85 */
86public class IpServer extends StateMachine {
87 public static final int STATE_UNAVAILABLE = 0;
88 public static final int STATE_AVAILABLE = 1;
89 public static final int STATE_TETHERED = 2;
90 public static final int STATE_LOCAL_ONLY = 3;
91
92 /** Get string name of |state|.*/
93 public static String getStateString(int state) {
94 switch (state) {
95 case STATE_UNAVAILABLE: return "UNAVAILABLE";
96 case STATE_AVAILABLE: return "AVAILABLE";
97 case STATE_TETHERED: return "TETHERED";
98 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
99 }
100 return "UNKNOWN: " + state;
101 }
102
103 private static final byte DOUG_ADAMS = (byte) 42;
104
105 private static final String USB_NEAR_IFACE_ADDR = "192.168.42.129";
106 private static final int USB_PREFIX_LENGTH = 24;
107 private static final String WIFI_HOST_IFACE_ADDR = "192.168.43.1";
108 private static final int WIFI_HOST_IFACE_PREFIX_LENGTH = 24;
109 private static final String WIFI_P2P_IFACE_ADDR = "192.168.49.1";
110 private static final int WIFI_P2P_IFACE_PREFIX_LENGTH = 24;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900111 private static final String ETHERNET_IFACE_ADDR = "192.168.50.1";
112 private static final int ETHERNET_IFACE_PREFIX_LENGTH = 24;
markchien74a4fa92019-09-09 20:50:49 +0800113
114 // TODO: have PanService use some visible version of this constant
115 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1";
116 private static final int BLUETOOTH_DHCP_PREFIX_LENGTH = 24;
117
118 // TODO: have this configurable
119 private static final int DHCP_LEASE_TIME_SECS = 3600;
120
121 private static final String TAG = "IpServer";
122 private static final boolean DBG = false;
123 private static final boolean VDBG = false;
124 private static final Class[] sMessageClasses = {
125 IpServer.class
126 };
127 private static final SparseArray<String> sMagicDecoderRing =
128 MessageUtils.findMessageNames(sMessageClasses);
129
130 /** IpServer callback. */
131 public static class Callback {
132 /**
133 * Notify that |who| has changed its tethering state.
134 *
135 * @param who the calling instance of IpServer
136 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800137 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800138 */
markchien9d353822019-12-16 20:15:20 +0800139 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800140
141 /**
142 * Notify that |who| has new LinkProperties.
143 *
144 * @param who the calling instance of IpServer
145 * @param newLp the new LinkProperties to report
146 */
markchien9d353822019-12-16 20:15:20 +0800147 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900148
149 /**
150 * Notify that the DHCP leases changed in one of the IpServers.
151 */
152 public void dhcpLeasesChanged() { }
markchien74a4fa92019-09-09 20:50:49 +0800153 }
154
155 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800156 public abstract static class Dependencies {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900157 /** Create an IpNeighborMonitor to be used by this IpServer */
158 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
159 IpNeighborMonitor.NeighborEventConsumer consumer) {
160 return new IpNeighborMonitor(handler, log, consumer);
161 }
162
markchien74a4fa92019-09-09 20:50:49 +0800163 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
164 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
165 return new RouterAdvertisementDaemon(ifParams);
166 }
167
168 /** Get |ifName|'s interface information.*/
169 public InterfaceParams getInterfaceParams(String ifName) {
170 return InterfaceParams.getByName(ifName);
171 }
172
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900173 /** Get |ifName|'s interface index. */
174 public int getIfindex(String ifName) {
175 try {
176 return NetworkInterface.getByName(ifName).getIndex();
177 } catch (IOException | NullPointerException e) {
178 Log.e(TAG, "Can't determine interface index for interface " + ifName);
179 return 0;
180 }
181 }
markchien9d353822019-12-16 20:15:20 +0800182 /** Create a DhcpServer instance to be used by IpServer. */
183 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
184 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800185 }
186
markchien74a4fa92019-09-09 20:50:49 +0800187 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800188 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800189 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800190 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800191 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800192 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
markchien74a4fa92019-09-09 20:50:49 +0800193 // notification from the master SM that it had trouble enabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800194 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
markchien74a4fa92019-09-09 20:50:49 +0800195 // notification from the master SM that it had trouble disabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800196 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
markchien74a4fa92019-09-09 20:50:49 +0800197 // notification from the master SM that it had trouble starting tethering
markchien6cf0e552019-12-06 15:24:53 +0800198 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
markchien74a4fa92019-09-09 20:50:49 +0800199 // notification from the master SM that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800200 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
markchien74a4fa92019-09-09 20:50:49 +0800201 // notification from the master SM that it had trouble setting the DNS forwarders
markchien6cf0e552019-12-06 15:24:53 +0800202 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800203 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800204 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800205 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800206 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900207 // new neighbor cache entry on our interface
208 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
markchien74a4fa92019-09-09 20:50:49 +0800209
210 private final State mInitialState;
211 private final State mLocalHotspotState;
212 private final State mTetheredState;
213 private final State mUnavailableState;
214
215 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800216 private final INetd mNetd;
markchien74a4fa92019-09-09 20:50:49 +0800217 private final Callback mCallback;
218 private final InterfaceController mInterfaceCtrl;
219
220 private final String mIfaceName;
221 private final int mInterfaceType;
222 private final LinkProperties mLinkProperties;
223 private final boolean mUsingLegacyDhcp;
224
225 private final Dependencies mDeps;
226
227 private int mLastError;
228 private int mServingMode;
229 private InterfaceSet mUpstreamIfaceSet; // may change over time
230 private InterfaceParams mInterfaceParams;
231 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
232 // properties are those selected by the IPv6TetheringCoordinator and relayed
233 // to us. By comparison, mLinkProperties contains the addresses and directly
234 // connected routes that have been formed from these properties iff. we have
235 // succeeded in configuring them and are able to announce them within Router
236 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
237 private LinkProperties mLastIPv6LinkProperties;
238 private RouterAdvertisementDaemon mRaDaemon;
239
240 // To be accessed only on the handler thread
241 private int mDhcpServerStartIndex = 0;
242 private IDhcpServer mDhcpServer;
243 private RaParams mLastRaParams;
markchien12c5bb82020-01-07 14:43:17 +0800244 private LinkAddress mIpv4Address;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900245 @NonNull
246 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800247
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900248 private int mLastIPv6UpstreamIfindex = 0;
249
250 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
251 public void accept(NeighborEvent e) {
252 sendMessage(CMD_NEIGHBOR_EVENT, e);
253 }
254 }
255
256 static class Ipv6ForwardingRule {
257 public final int upstreamIfindex;
258 public final int downstreamIfindex;
259 public final Inet6Address address;
260 public final MacAddress srcMac;
261 public final MacAddress dstMac;
262
263 Ipv6ForwardingRule(int upstreamIfindex, int downstreamIfIndex, Inet6Address address,
264 MacAddress srcMac, MacAddress dstMac) {
265 this.upstreamIfindex = upstreamIfindex;
266 this.downstreamIfindex = downstreamIfIndex;
267 this.address = address;
268 this.srcMac = srcMac;
269 this.dstMac = dstMac;
270 }
271
272 public Ipv6ForwardingRule onNewUpstream(int newUpstreamIfindex) {
273 return new Ipv6ForwardingRule(newUpstreamIfindex, downstreamIfindex, address, srcMac,
274 dstMac);
275 }
276 }
277 private final LinkedHashMap<Inet6Address, Ipv6ForwardingRule> mIpv6ForwardingRules =
278 new LinkedHashMap<>();
279
280 private final IpNeighborMonitor mIpNeighborMonitor;
281
markchien74a4fa92019-09-09 20:50:49 +0800282 public IpServer(
283 String ifaceName, Looper looper, int interfaceType, SharedLog log,
junyulai5864a3f2019-12-03 14:34:13 +0800284 INetd netd, Callback callback, boolean usingLegacyDhcp, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800285 super(ifaceName, looper);
286 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800287 mNetd = netd;
markchien74a4fa92019-09-09 20:50:49 +0800288 mCallback = callback;
289 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
290 mIfaceName = ifaceName;
291 mInterfaceType = interfaceType;
292 mLinkProperties = new LinkProperties();
293 mUsingLegacyDhcp = usingLegacyDhcp;
294 mDeps = deps;
295 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800296 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800297 mServingMode = STATE_AVAILABLE;
298
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900299 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
300 new MyNeighborEventConsumer());
301 if (!mIpNeighborMonitor.start()) {
302 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
303 }
304
markchien74a4fa92019-09-09 20:50:49 +0800305 mInitialState = new InitialState();
306 mLocalHotspotState = new LocalHotspotState();
307 mTetheredState = new TetheredState();
308 mUnavailableState = new UnavailableState();
309 addState(mInitialState);
310 addState(mLocalHotspotState);
311 addState(mTetheredState);
312 addState(mUnavailableState);
313
314 setInitialState(mInitialState);
315 }
316
317 /** Interface name which IpServer served.*/
318 public String interfaceName() {
319 return mIfaceName;
320 }
321
322 /**
markchien9b4d7572019-12-25 19:40:32 +0800323 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800324 */
325 public int interfaceType() {
326 return mInterfaceType;
327 }
328
329 /** Last error from this IpServer. */
330 public int lastError() {
331 return mLastError;
332 }
333
334 /** Serving mode is the current state of IpServer state machine. */
335 public int servingMode() {
336 return mServingMode;
337 }
338
339 /** The properties of the network link which IpServer is serving. */
340 public LinkProperties linkProperties() {
341 return new LinkProperties(mLinkProperties);
342 }
343
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900344 /**
345 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
346 * thread.
347 */
348 public List<TetheredClient> getAllLeases() {
349 return Collections.unmodifiableList(mDhcpLeases);
350 }
351
markchien74a4fa92019-09-09 20:50:49 +0800352 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
353 public void stop() {
354 sendMessage(CMD_INTERFACE_DOWN);
355 }
356
357 /**
358 * Tethering is canceled. IpServer state machine will be available and wait for
359 * next tethering request.
360 */
361 public void unwanted() {
362 sendMessage(CMD_TETHER_UNREQUESTED);
363 }
364
365 /** Internals. */
366
367 private boolean startIPv4() {
368 return configureIPv4(true);
369 }
370
371 /**
372 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
373 * handler.
374 *
375 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
376 * with different implementations of the callback, to differentiate handling of success/error in
377 * each call.
378 */
379 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
380 @Override
381 public void onStatusAvailable(int statusCode) {
382 getHandler().post(() -> callback(statusCode));
383 }
384
385 public abstract void callback(int statusCode);
386
387 @Override
388 public int getInterfaceVersion() {
389 return this.VERSION;
390 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900391
392 @Override
393 public String getInterfaceHash() {
394 return this.HASH;
395 }
markchien74a4fa92019-09-09 20:50:49 +0800396 }
397
398 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
399 private final int mStartIndex;
400
401 private DhcpServerCallbacksImpl(int startIndex) {
402 mStartIndex = startIndex;
403 }
404
405 @Override
406 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
407 getHandler().post(() -> {
408 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
409 if (mStartIndex != mDhcpServerStartIndex) {
410 // This start request is obsolete. When the |server| binder token goes out of
411 // scope, the garbage collector will finalize it, which causes the network stack
412 // process garbage collector to collect the server itself.
413 return;
414 }
415
416 if (statusCode != STATUS_SUCCESS) {
417 mLog.e("Error obtaining DHCP server: " + statusCode);
418 handleError();
419 return;
420 }
421
422 mDhcpServer = server;
423 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900424 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800425 @Override
426 public void callback(int startStatusCode) {
427 if (startStatusCode != STATUS_SUCCESS) {
428 mLog.e("Error starting DHCP server: " + startStatusCode);
429 handleError();
430 }
431 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900432 }, new DhcpLeaseCallback());
markchien74a4fa92019-09-09 20:50:49 +0800433 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800434 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800435 }
436 });
437 }
438
439 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800440 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800441 transitionTo(mInitialState);
442 }
443 }
444
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900445 private class DhcpLeaseCallback extends IDhcpLeaseCallbacks.Stub {
446 @Override
447 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
448 final ArrayList<TetheredClient> leases = new ArrayList<>();
449 for (DhcpLeaseParcelable lease : leaseParcelables) {
450 final LinkAddress address = new LinkAddress(
451 intToInet4AddressHTH(lease.netAddr), lease.prefixLength);
452
453 final MacAddress macAddress;
454 try {
455 macAddress = MacAddress.fromBytes(lease.hwAddr);
456 } catch (IllegalArgumentException e) {
457 Log.wtf(TAG, "Invalid address received from DhcpServer: "
458 + Arrays.toString(lease.hwAddr));
459 return;
460 }
461
462 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
463 address, lease.hostname, lease.expTime);
464 leases.add(new TetheredClient(
465 macAddress,
466 Collections.singletonList(addressInfo),
467 mInterfaceType));
468 }
469
470 getHandler().post(() -> {
471 mDhcpLeases = leases;
472 mCallback.dhcpLeasesChanged();
473 });
474 }
475
476 @Override
477 public int getInterfaceVersion() {
478 return this.VERSION;
479 }
480
481 @Override
482 public String getInterfaceHash() throws RemoteException {
483 return this.HASH;
484 }
485 }
486
markchien74a4fa92019-09-09 20:50:49 +0800487 private boolean startDhcp(Inet4Address addr, int prefixLen) {
488 if (mUsingLegacyDhcp) {
489 return true;
490 }
491 final DhcpServingParamsParcel params;
492 params = new DhcpServingParamsParcelExt()
493 .setDefaultRouters(addr)
494 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
495 .setDnsServers(addr)
496 .setServerAddr(new LinkAddress(addr, prefixLen))
497 .setMetered(true);
498 // TODO: also advertise link MTU
499
500 mDhcpServerStartIndex++;
501 mDeps.makeDhcpServer(
502 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
503 return true;
504 }
505
506 private void stopDhcp() {
507 // Make all previous start requests obsolete so servers are not started later
508 mDhcpServerStartIndex++;
509
510 if (mDhcpServer != null) {
511 try {
512 mDhcpServer.stop(new OnHandlerStatusCallback() {
513 @Override
514 public void callback(int statusCode) {
515 if (statusCode != STATUS_SUCCESS) {
516 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800517 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800518 // Not much more we can do here
519 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900520 mDhcpLeases.clear();
521 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800522 }
523 });
524 mDhcpServer = null;
525 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800526 mLog.e("Error stopping DHCP", e);
527 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800528 }
529 }
530 }
531
532 private boolean configureDhcp(boolean enable, Inet4Address addr, int prefixLen) {
533 if (enable) {
534 return startDhcp(addr, prefixLen);
535 } else {
536 stopDhcp();
537 return true;
538 }
539 }
540
541 private void stopIPv4() {
542 configureIPv4(false);
543 // NOTE: All of configureIPv4() will be refactored out of existence
544 // into calls to InterfaceController, shared with startIPv4().
545 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800546 mIpv4Address = null;
markchien74a4fa92019-09-09 20:50:49 +0800547 }
548
markchien74a4fa92019-09-09 20:50:49 +0800549 private boolean configureIPv4(boolean enabled) {
550 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
551
552 // TODO: Replace this hard-coded information with dynamically selected
553 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800554 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800555 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800556 try {
Milim Lee45a971b2019-10-17 05:02:33 +0900557 if (mInterfaceType == TetheringManager.TETHERING_USB
558 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien12c5bb82020-01-07 14:43:17 +0800559 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
560 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800561 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800562 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
563 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800564 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800565 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
566 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900567 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
568 // TODO: randomize address for tethering too, similarly to wifi
569 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
570 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien12c5bb82020-01-07 14:43:17 +0800571 } else {
572 // BT configures the interface elsewhere: only start DHCP.
573 // TODO: make all tethering types behave the same way, and delete the bluetooth
574 // code that calls into NetworkManagementService directly.
575 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
576 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
577 return configureDhcp(enabled, srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
578 }
579 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
580 } catch (IllegalArgumentException e) {
581 mLog.e("Error selecting ipv4 address", e);
582 if (!enabled) stopDhcp();
583 return false;
markchien74a4fa92019-09-09 20:50:49 +0800584 }
585
markchien12c5bb82020-01-07 14:43:17 +0800586 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800587 if (mInterfaceType == TetheringManager.TETHERING_WIFI
588 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800589 // The WiFi stack has ownership of the interface up/down state.
590 // It is unclear whether the Bluetooth or USB stacks will manage their own
591 // state.
592 setIfaceUp = null;
593 } else {
594 setIfaceUp = enabled;
595 }
596 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
597 mLog.e("Error configuring interface");
598 if (!enabled) stopDhcp();
599 return false;
600 }
markchien74a4fa92019-09-09 20:50:49 +0800601
markchien12c5bb82020-01-07 14:43:17 +0800602 if (!configureDhcp(enabled, srvAddr, prefixLen)) {
markchien74a4fa92019-09-09 20:50:49 +0800603 return false;
604 }
605
606 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800607 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
608 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800609 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800610 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800611 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800612 mLinkProperties.addRoute(route);
613 } else {
markchien12c5bb82020-01-07 14:43:17 +0800614 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800615 mLinkProperties.removeRoute(route);
616 }
617 return true;
618 }
619
620 private String getRandomWifiIPv4Address() {
621 try {
622 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
623 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
624 return InetAddress.getByAddress(bytes).getHostAddress();
625 } catch (Exception e) {
626 return WIFI_HOST_IFACE_ADDR;
627 }
628 }
629
630 private boolean startIPv6() {
631 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
632 if (mInterfaceParams == null) {
633 mLog.e("Failed to find InterfaceParams");
634 stopIPv6();
635 return false;
636 }
637
638 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
639 if (!mRaDaemon.start()) {
640 stopIPv6();
641 return false;
642 }
643
644 return true;
645 }
646
647 private void stopIPv6() {
648 mInterfaceParams = null;
649 setRaParams(null);
650
651 if (mRaDaemon != null) {
652 mRaDaemon.stop();
653 mRaDaemon = null;
654 }
655 }
656
657 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
658 // LinkProperties. These have extraneous data filtered out and only the
659 // necessary prefixes included (per its prefix distribution policy).
660 //
661 // TODO: Evaluate using a data structure than is more directly suited to
662 // communicating only the relevant information.
663 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
664 if (mRaDaemon == null) return;
665
666 // Avoid unnecessary work on spurious updates.
667 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
668 return;
669 }
670
671 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900672 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800673
674 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900675 final String upstreamIface = v6only.getInterfaceName();
676
markchien74a4fa92019-09-09 20:50:49 +0800677 params = new RaParams();
Maciej Żenczykowskida0fb1b2020-02-19 01:24:39 -0800678 // We advertise an mtu lower by 16, which is the closest multiple of 8 >= 14,
679 // the ethernet header size. This makes kernel ebpf tethering offload happy.
680 // This hack should be reverted once we have the kernel fixed up.
681 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
682 // see RouterAdvertisementDaemon.java putMtu()
683 params.mtu = v6only.getMtu() - 16;
markchien74a4fa92019-09-09 20:50:49 +0800684 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
685
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900686 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800687
688 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
689 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
690
691 final IpPrefix prefix = new IpPrefix(
692 linkAddr.getAddress(), linkAddr.getPrefixLength());
693 params.prefixes.add(prefix);
694
695 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
696 if (dnsServer != null) {
697 params.dnses.add(dnsServer);
698 }
699 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900700
701 upstreamIfindex = mDeps.getIfindex(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800702 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900703
markchien74a4fa92019-09-09 20:50:49 +0800704 // If v6only is null, we pass in null to setRaParams(), which handles
705 // deprecation of any existing RA data.
706
707 setRaParams(params);
708 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900709
710 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
711 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800712 }
713
714 private void configureLocalIPv6Routes(
715 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
716 // [1] Remove the routes that are deprecated.
717 if (!deprecatedPrefixes.isEmpty()) {
718 final ArrayList<RouteInfo> toBeRemoved =
719 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800720 // Remove routes from local network.
721 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
722 mNetd, toBeRemoved);
723 if (removalFailures > 0) {
724 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
725 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800726 }
727
728 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
729 }
730
731 // [2] Add only the routes that have not previously been added.
732 if (newPrefixes != null && !newPrefixes.isEmpty()) {
733 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
734 if (mLastRaParams != null) {
735 addedPrefixes.removeAll(mLastRaParams.prefixes);
736 }
737
738 if (!addedPrefixes.isEmpty()) {
739 final ArrayList<RouteInfo> toBeAdded =
740 getLocalRoutesFor(mIfaceName, addedPrefixes);
741 try {
markchien12c5bb82020-01-07 14:43:17 +0800742 // It's safe to call networkAddInterface() even if
743 // the interface is already in the local_network.
744 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
745 try {
746 // Add routes from local network. Note that adding routes that
747 // already exist does not cause an error (EEXIST is silently ignored).
748 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
749 } catch (IllegalStateException e) {
750 mLog.e("Failed to add IPv6 routes to local table: " + e);
751 }
752 } catch (ServiceSpecificException | RemoteException e) {
753 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800754 }
755
756 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
757 }
758 }
759 }
760
761 private void configureLocalIPv6Dns(
762 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
763 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
764 if (mNetd == null) {
765 if (newDnses != null) newDnses.clear();
766 mLog.e("No netd service instance available; not setting local IPv6 addresses");
767 return;
768 }
769
770 // [1] Remove deprecated local DNS IP addresses.
771 if (!deprecatedDnses.isEmpty()) {
772 for (Inet6Address dns : deprecatedDnses) {
773 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
774 mLog.e("Failed to remove local dns IP " + dns);
775 }
776
777 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
778 }
779 }
780
781 // [2] Add only the local DNS IP addresses that have not previously been added.
782 if (newDnses != null && !newDnses.isEmpty()) {
783 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
784 if (mLastRaParams != null) {
785 addedDnses.removeAll(mLastRaParams.dnses);
786 }
787
788 for (Inet6Address dns : addedDnses) {
789 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
790 mLog.e("Failed to add local dns IP " + dns);
791 newDnses.remove(dns);
792 }
793
794 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
795 }
796 }
797
798 try {
799 mNetd.tetherApplyDnsInterfaces();
800 } catch (ServiceSpecificException | RemoteException e) {
801 mLog.e("Failed to update local DNS caching server");
802 if (newDnses != null) newDnses.clear();
803 }
804 }
805
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900806 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
807 try {
808 mNetd.tetherRuleAddDownstreamIpv6(mInterfaceParams.index, rule.upstreamIfindex,
809 rule.address.getAddress(), mInterfaceParams.macAddr.toByteArray(),
810 rule.dstMac.toByteArray());
811 mIpv6ForwardingRules.put(rule.address, rule);
812 } catch (RemoteException | ServiceSpecificException e) {
813 Log.e(TAG, "Could not add IPv6 downstream rule: " + e);
814 }
815 }
816
817 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
818 try {
819 mNetd.tetherRuleRemoveDownstreamIpv6(rule.upstreamIfindex, rule.address.getAddress());
820 if (removeFromMap) {
821 mIpv6ForwardingRules.remove(rule.address);
822 }
823 } catch (RemoteException | ServiceSpecificException e) {
824 Log.e(TAG, "Could not remove IPv6 downstream rule: " + e);
825 }
826 }
827
828 // Convenience method to replace a rule with the same rule on a new upstream interface.
829 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
830 // Relies on the fact that rules are in a map indexed by IP address.
831 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
832 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
833 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
834 }
835
836 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
837 // changes or if a neighbor event is received.
838 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
839 NeighborEvent e) {
840 // If the upstream interface has changed, remove all rules and re-add them with the new
841 // upstream interface.
842 if (prevUpstreamIfindex != upstreamIfindex) {
843 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
844 updateIpv6ForwardingRule(rule, upstreamIfindex);
845 }
846 }
847
848 // If we're here to process a NeighborEvent, do so now.
849 if (e == null) return;
850 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
851 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
852 return;
853 }
854
855 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(mLastIPv6UpstreamIfindex,
856 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr,
857 e.macAddr);
858 if (e.isValid()) {
859 addIpv6ForwardingRule(rule);
860 } else {
861 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
862 }
863 }
864
865 private void handleNeighborEvent(NeighborEvent e) {
866 if (mInterfaceParams != null
867 && mInterfaceParams.index == e.ifindex
868 && mInterfaceParams.hasMacAddress) {
869 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
870 }
871 }
872
markchien74a4fa92019-09-09 20:50:49 +0800873 private byte getHopLimit(String upstreamIface) {
874 try {
875 int upstreamHopLimit = Integer.parseUnsignedInt(
876 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
877 // Add one hop to account for this forwarding device
878 upstreamHopLimit++;
879 // Cap the hop limit to 255.
880 return (byte) Integer.min(upstreamHopLimit, 255);
881 } catch (Exception e) {
882 mLog.e("Failed to find upstream interface hop limit", e);
883 }
884 return RaParams.DEFAULT_HOPLIMIT;
885 }
886
887 private void setRaParams(RaParams newParams) {
888 if (mRaDaemon != null) {
889 final RaParams deprecatedParams =
890 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
891
892 configureLocalIPv6Routes(deprecatedParams.prefixes,
893 (newParams != null) ? newParams.prefixes : null);
894
895 configureLocalIPv6Dns(deprecatedParams.dnses,
896 (newParams != null) ? newParams.dnses : null);
897
898 mRaDaemon.buildNewRa(deprecatedParams, newParams);
899 }
900
901 mLastRaParams = newParams;
902 }
903
904 private void logMessage(State state, int what) {
905 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
906 }
907
908 private void sendInterfaceState(int newInterfaceState) {
909 mServingMode = newInterfaceState;
910 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
911 sendLinkProperties();
912 }
913
914 private void sendLinkProperties() {
915 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
916 }
917
918 private void resetLinkProperties() {
919 mLinkProperties.clear();
920 mLinkProperties.setInterfaceName(mIfaceName);
921 }
922
923 class InitialState extends State {
924 @Override
925 public void enter() {
926 sendInterfaceState(STATE_AVAILABLE);
927 }
928
929 @Override
930 public boolean processMessage(Message message) {
931 logMessage(this, message.what);
932 switch (message.what) {
933 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800934 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800935 switch (message.arg1) {
936 case STATE_LOCAL_ONLY:
937 transitionTo(mLocalHotspotState);
938 break;
939 case STATE_TETHERED:
940 transitionTo(mTetheredState);
941 break;
942 default:
943 mLog.e("Invalid tethering interface serving state specified.");
944 }
945 break;
946 case CMD_INTERFACE_DOWN:
947 transitionTo(mUnavailableState);
948 break;
949 case CMD_IPV6_TETHER_UPDATE:
950 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
951 break;
952 default:
953 return NOT_HANDLED;
954 }
955 return HANDLED;
956 }
957 }
958
959 class BaseServingState extends State {
960 @Override
961 public void enter() {
962 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +0800963 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800964 return;
965 }
966
967 try {
markchien12c5bb82020-01-07 14:43:17 +0800968 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
969 mIpv4Address.getPrefixLength());
970 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchien6c2b7cc2020-02-15 11:35:00 +0800971 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
markchien74a4fa92019-09-09 20:50:49 +0800972 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +0800973 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800974 return;
975 }
976
977 if (!startIPv6()) {
978 mLog.e("Failed to startIPv6");
979 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
980 return;
981 }
982 }
983
984 @Override
985 public void exit() {
986 // Note that at this point, we're leaving the tethered state. We can fail any
987 // of these operations, but it doesn't really change that we have to try them
988 // all in sequence.
989 stopIPv6();
990
991 try {
markchien12c5bb82020-01-07 14:43:17 +0800992 NetdUtils.untetherInterface(mNetd, mIfaceName);
993 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +0800994 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800995 mLog.e("Failed to untether interface: " + e);
996 }
997
998 stopIPv4();
999
1000 resetLinkProperties();
1001 }
1002
1003 @Override
1004 public boolean processMessage(Message message) {
1005 logMessage(this, message.what);
1006 switch (message.what) {
1007 case CMD_TETHER_UNREQUESTED:
1008 transitionTo(mInitialState);
1009 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1010 break;
1011 case CMD_INTERFACE_DOWN:
1012 transitionTo(mUnavailableState);
1013 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1014 break;
1015 case CMD_IPV6_TETHER_UPDATE:
1016 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1017 sendLinkProperties();
1018 break;
1019 case CMD_IP_FORWARDING_ENABLE_ERROR:
1020 case CMD_IP_FORWARDING_DISABLE_ERROR:
1021 case CMD_START_TETHERING_ERROR:
1022 case CMD_STOP_TETHERING_ERROR:
1023 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien9b4d7572019-12-25 19:40:32 +08001024 mLastError = TetheringManager.TETHER_ERROR_MASTER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001025 transitionTo(mInitialState);
1026 break;
1027 default:
1028 return false;
1029 }
1030 return true;
1031 }
1032 }
1033
1034 // Handling errors in BaseServingState.enter() by transitioning is
1035 // problematic because transitioning during a multi-state jump yields
1036 // a Log.wtf(). Ultimately, there should be only one ServingState,
1037 // and forwarding and NAT rules should be handled by a coordinating
1038 // functional element outside of IpServer.
1039 class LocalHotspotState extends BaseServingState {
1040 @Override
1041 public void enter() {
1042 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001043 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001044 transitionTo(mInitialState);
1045 }
1046
1047 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1048 sendInterfaceState(STATE_LOCAL_ONLY);
1049 }
1050
1051 @Override
1052 public boolean processMessage(Message message) {
1053 if (super.processMessage(message)) return true;
1054
1055 logMessage(this, message.what);
1056 switch (message.what) {
1057 case CMD_TETHER_REQUESTED:
1058 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1059 break;
1060 case CMD_TETHER_CONNECTION_CHANGED:
1061 // Ignored in local hotspot state.
1062 break;
1063 default:
1064 return false;
1065 }
1066 return true;
1067 }
1068 }
1069
1070 // Handling errors in BaseServingState.enter() by transitioning is
1071 // problematic because transitioning during a multi-state jump yields
1072 // a Log.wtf(). Ultimately, there should be only one ServingState,
1073 // and forwarding and NAT rules should be handled by a coordinating
1074 // functional element outside of IpServer.
1075 class TetheredState extends BaseServingState {
1076 @Override
1077 public void enter() {
1078 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001079 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001080 transitionTo(mInitialState);
1081 }
1082
1083 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1084 sendInterfaceState(STATE_TETHERED);
1085 }
1086
1087 @Override
1088 public void exit() {
1089 cleanupUpstream();
1090 super.exit();
1091 }
1092
1093 private void cleanupUpstream() {
1094 if (mUpstreamIfaceSet == null) return;
1095
1096 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1097 mUpstreamIfaceSet = null;
1098 }
1099
1100 private void cleanupUpstreamInterface(String upstreamIface) {
1101 // Note that we don't care about errors here.
1102 // Sometimes interfaces are gone before we get
1103 // to remove their rules, which generates errors.
1104 // Just do the best we can.
1105 try {
markchien12c5bb82020-01-07 14:43:17 +08001106 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1107 } catch (RemoteException | ServiceSpecificException e) {
1108 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001109 }
1110 try {
markchien12c5bb82020-01-07 14:43:17 +08001111 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1112 } catch (RemoteException | ServiceSpecificException e) {
1113 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001114 }
1115 }
1116
1117 @Override
1118 public boolean processMessage(Message message) {
1119 if (super.processMessage(message)) return true;
1120
1121 logMessage(this, message.what);
1122 switch (message.what) {
1123 case CMD_TETHER_REQUESTED:
1124 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1125 break;
1126 case CMD_TETHER_CONNECTION_CHANGED:
1127 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1128 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1129 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1130 break;
1131 }
1132
1133 if (newUpstreamIfaceSet == null) {
1134 cleanupUpstream();
1135 break;
1136 }
1137
1138 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1139 cleanupUpstreamInterface(removed);
1140 }
1141
1142 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1143 // This makes the call to cleanupUpstream() in the error
1144 // path for any interface neatly cleanup all the interfaces.
1145 mUpstreamIfaceSet = newUpstreamIfaceSet;
1146
1147 for (String ifname : added) {
1148 try {
markchien12c5bb82020-01-07 14:43:17 +08001149 mNetd.tetherAddForward(mIfaceName, ifname);
1150 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1151 } catch (RemoteException | ServiceSpecificException e) {
1152 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001153 cleanupUpstream();
markchien9b4d7572019-12-25 19:40:32 +08001154 mLastError = TetheringManager.TETHER_ERROR_ENABLE_NAT_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001155 transitionTo(mInitialState);
1156 return true;
1157 }
1158 }
1159 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001160 case CMD_NEIGHBOR_EVENT:
1161 handleNeighborEvent((NeighborEvent) message.obj);
1162 break;
markchien74a4fa92019-09-09 20:50:49 +08001163 default:
1164 return false;
1165 }
1166 return true;
1167 }
1168
1169 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1170 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1171 if (mUpstreamIfaceSet != null && newIfaces != null) {
1172 return mUpstreamIfaceSet.equals(newIfaces);
1173 }
1174 return false;
1175 }
1176
1177 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1178 if (mUpstreamIfaceSet == null) return new HashSet<>();
1179
1180 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1181 removed.removeAll(newIfaces.ifnames);
1182 return removed;
1183 }
1184
1185 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1186 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1187 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1188 return added;
1189 }
1190 }
1191
1192 /**
1193 * This state is terminal for the per interface state machine. At this
1194 * point, the master state machine should have removed this interface
1195 * specific state machine from its list of possible recipients of
1196 * tethering requests. The state machine itself will hang around until
1197 * the garbage collector finds it.
1198 */
1199 class UnavailableState extends State {
1200 @Override
1201 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001202 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001203 sendInterfaceState(STATE_UNAVAILABLE);
1204 }
1205 }
1206
1207 // Accumulate routes representing "prefixes to be assigned to the local
1208 // interface", for subsequent modification of local_network routing.
1209 private static ArrayList<RouteInfo> getLocalRoutesFor(
1210 String ifname, HashSet<IpPrefix> prefixes) {
1211 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1212 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001213 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001214 }
1215 return localRoutes;
1216 }
1217
1218 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1219 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1220 final byte[] dnsBytes = localPrefix.getRawAddress();
1221 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1222 try {
1223 return Inet6Address.getByAddress(null, dnsBytes, 0);
1224 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001225 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001226 return null;
1227 }
1228 }
1229
1230 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1231 final byte random = (byte) (new Random()).nextInt();
1232 for (int value : excluded) {
1233 if (random == value) return dflt;
1234 }
1235 return random;
1236 }
1237}