blob: 89670292922f6d00a591355ec2b50140994ccc1f [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();
678 params.mtu = v6only.getMtu();
679 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
680
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900681 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800682
683 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
684 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
685
686 final IpPrefix prefix = new IpPrefix(
687 linkAddr.getAddress(), linkAddr.getPrefixLength());
688 params.prefixes.add(prefix);
689
690 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
691 if (dnsServer != null) {
692 params.dnses.add(dnsServer);
693 }
694 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900695
696 upstreamIfindex = mDeps.getIfindex(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800697 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900698
markchien74a4fa92019-09-09 20:50:49 +0800699 // If v6only is null, we pass in null to setRaParams(), which handles
700 // deprecation of any existing RA data.
701
702 setRaParams(params);
703 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900704
705 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
706 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800707 }
708
709 private void configureLocalIPv6Routes(
710 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
711 // [1] Remove the routes that are deprecated.
712 if (!deprecatedPrefixes.isEmpty()) {
713 final ArrayList<RouteInfo> toBeRemoved =
714 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800715 // Remove routes from local network.
716 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
717 mNetd, toBeRemoved);
718 if (removalFailures > 0) {
719 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
720 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800721 }
722
723 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
724 }
725
726 // [2] Add only the routes that have not previously been added.
727 if (newPrefixes != null && !newPrefixes.isEmpty()) {
728 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
729 if (mLastRaParams != null) {
730 addedPrefixes.removeAll(mLastRaParams.prefixes);
731 }
732
733 if (!addedPrefixes.isEmpty()) {
734 final ArrayList<RouteInfo> toBeAdded =
735 getLocalRoutesFor(mIfaceName, addedPrefixes);
736 try {
markchien12c5bb82020-01-07 14:43:17 +0800737 // It's safe to call networkAddInterface() even if
738 // the interface is already in the local_network.
739 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
740 try {
741 // Add routes from local network. Note that adding routes that
742 // already exist does not cause an error (EEXIST is silently ignored).
743 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
744 } catch (IllegalStateException e) {
745 mLog.e("Failed to add IPv6 routes to local table: " + e);
746 }
747 } catch (ServiceSpecificException | RemoteException e) {
748 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800749 }
750
751 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
752 }
753 }
754 }
755
756 private void configureLocalIPv6Dns(
757 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
758 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
759 if (mNetd == null) {
760 if (newDnses != null) newDnses.clear();
761 mLog.e("No netd service instance available; not setting local IPv6 addresses");
762 return;
763 }
764
765 // [1] Remove deprecated local DNS IP addresses.
766 if (!deprecatedDnses.isEmpty()) {
767 for (Inet6Address dns : deprecatedDnses) {
768 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
769 mLog.e("Failed to remove local dns IP " + dns);
770 }
771
772 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
773 }
774 }
775
776 // [2] Add only the local DNS IP addresses that have not previously been added.
777 if (newDnses != null && !newDnses.isEmpty()) {
778 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
779 if (mLastRaParams != null) {
780 addedDnses.removeAll(mLastRaParams.dnses);
781 }
782
783 for (Inet6Address dns : addedDnses) {
784 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
785 mLog.e("Failed to add local dns IP " + dns);
786 newDnses.remove(dns);
787 }
788
789 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
790 }
791 }
792
793 try {
794 mNetd.tetherApplyDnsInterfaces();
795 } catch (ServiceSpecificException | RemoteException e) {
796 mLog.e("Failed to update local DNS caching server");
797 if (newDnses != null) newDnses.clear();
798 }
799 }
800
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900801 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
802 try {
803 mNetd.tetherRuleAddDownstreamIpv6(mInterfaceParams.index, rule.upstreamIfindex,
804 rule.address.getAddress(), mInterfaceParams.macAddr.toByteArray(),
805 rule.dstMac.toByteArray());
806 mIpv6ForwardingRules.put(rule.address, rule);
807 } catch (RemoteException | ServiceSpecificException e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900808 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900809 }
810 }
811
812 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
813 try {
814 mNetd.tetherRuleRemoveDownstreamIpv6(rule.upstreamIfindex, rule.address.getAddress());
815 if (removeFromMap) {
816 mIpv6ForwardingRules.remove(rule.address);
817 }
818 } catch (RemoteException | ServiceSpecificException e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900819 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900820 }
821 }
822
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900823 private void clearIpv6ForwardingRules() {
824 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
825 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
826 }
827 mIpv6ForwardingRules.clear();
828 }
829
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900830 // Convenience method to replace a rule with the same rule on a new upstream interface.
831 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
832 // Relies on the fact that rules are in a map indexed by IP address.
833 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
834 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
835 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
836 }
837
838 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
839 // changes or if a neighbor event is received.
840 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
841 NeighborEvent e) {
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900842 // If we no longer have an upstream, clear forwarding rules and do nothing else.
843 if (upstreamIfindex == 0) {
844 clearIpv6ForwardingRules();
845 return;
846 }
847
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900848 // If the upstream interface has changed, remove all rules and re-add them with the new
849 // upstream interface.
850 if (prevUpstreamIfindex != upstreamIfindex) {
851 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
852 updateIpv6ForwardingRule(rule, upstreamIfindex);
853 }
854 }
855
856 // If we're here to process a NeighborEvent, do so now.
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900857 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900858 if (e == null) return;
859 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
860 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
861 return;
862 }
863
Lorenzo Colittic61fc082020-02-21 20:21:14 +0900864 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900865 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr,
866 e.macAddr);
867 if (e.isValid()) {
868 addIpv6ForwardingRule(rule);
869 } else {
870 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
871 }
872 }
873
874 private void handleNeighborEvent(NeighborEvent e) {
875 if (mInterfaceParams != null
876 && mInterfaceParams.index == e.ifindex
877 && mInterfaceParams.hasMacAddress) {
878 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
879 }
880 }
881
markchien74a4fa92019-09-09 20:50:49 +0800882 private byte getHopLimit(String upstreamIface) {
883 try {
884 int upstreamHopLimit = Integer.parseUnsignedInt(
885 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
886 // Add one hop to account for this forwarding device
887 upstreamHopLimit++;
888 // Cap the hop limit to 255.
889 return (byte) Integer.min(upstreamHopLimit, 255);
890 } catch (Exception e) {
891 mLog.e("Failed to find upstream interface hop limit", e);
892 }
893 return RaParams.DEFAULT_HOPLIMIT;
894 }
895
896 private void setRaParams(RaParams newParams) {
897 if (mRaDaemon != null) {
898 final RaParams deprecatedParams =
899 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
900
901 configureLocalIPv6Routes(deprecatedParams.prefixes,
902 (newParams != null) ? newParams.prefixes : null);
903
904 configureLocalIPv6Dns(deprecatedParams.dnses,
905 (newParams != null) ? newParams.dnses : null);
906
907 mRaDaemon.buildNewRa(deprecatedParams, newParams);
908 }
909
910 mLastRaParams = newParams;
911 }
912
913 private void logMessage(State state, int what) {
914 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
915 }
916
917 private void sendInterfaceState(int newInterfaceState) {
918 mServingMode = newInterfaceState;
919 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
920 sendLinkProperties();
921 }
922
923 private void sendLinkProperties() {
924 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
925 }
926
927 private void resetLinkProperties() {
928 mLinkProperties.clear();
929 mLinkProperties.setInterfaceName(mIfaceName);
930 }
931
932 class InitialState extends State {
933 @Override
934 public void enter() {
935 sendInterfaceState(STATE_AVAILABLE);
936 }
937
938 @Override
939 public boolean processMessage(Message message) {
940 logMessage(this, message.what);
941 switch (message.what) {
942 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800943 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800944 switch (message.arg1) {
945 case STATE_LOCAL_ONLY:
946 transitionTo(mLocalHotspotState);
947 break;
948 case STATE_TETHERED:
949 transitionTo(mTetheredState);
950 break;
951 default:
952 mLog.e("Invalid tethering interface serving state specified.");
953 }
954 break;
955 case CMD_INTERFACE_DOWN:
956 transitionTo(mUnavailableState);
957 break;
958 case CMD_IPV6_TETHER_UPDATE:
959 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
960 break;
961 default:
962 return NOT_HANDLED;
963 }
964 return HANDLED;
965 }
966 }
967
968 class BaseServingState extends State {
969 @Override
970 public void enter() {
971 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +0800972 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800973 return;
974 }
975
976 try {
markchien12c5bb82020-01-07 14:43:17 +0800977 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
978 mIpv4Address.getPrefixLength());
979 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchien6c2b7cc2020-02-15 11:35:00 +0800980 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
markchien74a4fa92019-09-09 20:50:49 +0800981 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +0800982 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800983 return;
984 }
985
986 if (!startIPv6()) {
987 mLog.e("Failed to startIPv6");
988 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
989 return;
990 }
991 }
992
993 @Override
994 public void exit() {
995 // Note that at this point, we're leaving the tethered state. We can fail any
996 // of these operations, but it doesn't really change that we have to try them
997 // all in sequence.
998 stopIPv6();
999
1000 try {
markchien12c5bb82020-01-07 14:43:17 +08001001 NetdUtils.untetherInterface(mNetd, mIfaceName);
1002 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001003 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001004 mLog.e("Failed to untether interface: " + e);
1005 }
1006
1007 stopIPv4();
1008
1009 resetLinkProperties();
1010 }
1011
1012 @Override
1013 public boolean processMessage(Message message) {
1014 logMessage(this, message.what);
1015 switch (message.what) {
1016 case CMD_TETHER_UNREQUESTED:
1017 transitionTo(mInitialState);
1018 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1019 break;
1020 case CMD_INTERFACE_DOWN:
1021 transitionTo(mUnavailableState);
1022 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1023 break;
1024 case CMD_IPV6_TETHER_UPDATE:
1025 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1026 sendLinkProperties();
1027 break;
1028 case CMD_IP_FORWARDING_ENABLE_ERROR:
1029 case CMD_IP_FORWARDING_DISABLE_ERROR:
1030 case CMD_START_TETHERING_ERROR:
1031 case CMD_STOP_TETHERING_ERROR:
1032 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien9b4d7572019-12-25 19:40:32 +08001033 mLastError = TetheringManager.TETHER_ERROR_MASTER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001034 transitionTo(mInitialState);
1035 break;
1036 default:
1037 return false;
1038 }
1039 return true;
1040 }
1041 }
1042
1043 // Handling errors in BaseServingState.enter() by transitioning is
1044 // problematic because transitioning during a multi-state jump yields
1045 // a Log.wtf(). Ultimately, there should be only one ServingState,
1046 // and forwarding and NAT rules should be handled by a coordinating
1047 // functional element outside of IpServer.
1048 class LocalHotspotState extends BaseServingState {
1049 @Override
1050 public void enter() {
1051 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001052 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001053 transitionTo(mInitialState);
1054 }
1055
1056 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1057 sendInterfaceState(STATE_LOCAL_ONLY);
1058 }
1059
1060 @Override
1061 public boolean processMessage(Message message) {
1062 if (super.processMessage(message)) return true;
1063
1064 logMessage(this, message.what);
1065 switch (message.what) {
1066 case CMD_TETHER_REQUESTED:
1067 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1068 break;
1069 case CMD_TETHER_CONNECTION_CHANGED:
1070 // Ignored in local hotspot state.
1071 break;
1072 default:
1073 return false;
1074 }
1075 return true;
1076 }
1077 }
1078
1079 // Handling errors in BaseServingState.enter() by transitioning is
1080 // problematic because transitioning during a multi-state jump yields
1081 // a Log.wtf(). Ultimately, there should be only one ServingState,
1082 // and forwarding and NAT rules should be handled by a coordinating
1083 // functional element outside of IpServer.
1084 class TetheredState extends BaseServingState {
1085 @Override
1086 public void enter() {
1087 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001088 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001089 transitionTo(mInitialState);
1090 }
1091
1092 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1093 sendInterfaceState(STATE_TETHERED);
1094 }
1095
1096 @Override
1097 public void exit() {
1098 cleanupUpstream();
1099 super.exit();
1100 }
1101
1102 private void cleanupUpstream() {
1103 if (mUpstreamIfaceSet == null) return;
1104
1105 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1106 mUpstreamIfaceSet = null;
Lorenzo Colittic61fc082020-02-21 20:21:14 +09001107 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001108 }
1109
1110 private void cleanupUpstreamInterface(String upstreamIface) {
1111 // Note that we don't care about errors here.
1112 // Sometimes interfaces are gone before we get
1113 // to remove their rules, which generates errors.
1114 // Just do the best we can.
1115 try {
markchien12c5bb82020-01-07 14:43:17 +08001116 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1117 } catch (RemoteException | ServiceSpecificException e) {
1118 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001119 }
1120 try {
markchien12c5bb82020-01-07 14:43:17 +08001121 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1122 } catch (RemoteException | ServiceSpecificException e) {
1123 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001124 }
1125 }
1126
1127 @Override
1128 public boolean processMessage(Message message) {
1129 if (super.processMessage(message)) return true;
1130
1131 logMessage(this, message.what);
1132 switch (message.what) {
1133 case CMD_TETHER_REQUESTED:
1134 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1135 break;
1136 case CMD_TETHER_CONNECTION_CHANGED:
1137 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1138 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1139 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1140 break;
1141 }
1142
1143 if (newUpstreamIfaceSet == null) {
1144 cleanupUpstream();
1145 break;
1146 }
1147
1148 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1149 cleanupUpstreamInterface(removed);
1150 }
1151
1152 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1153 // This makes the call to cleanupUpstream() in the error
1154 // path for any interface neatly cleanup all the interfaces.
1155 mUpstreamIfaceSet = newUpstreamIfaceSet;
1156
1157 for (String ifname : added) {
1158 try {
markchien12c5bb82020-01-07 14:43:17 +08001159 mNetd.tetherAddForward(mIfaceName, ifname);
1160 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1161 } catch (RemoteException | ServiceSpecificException e) {
1162 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001163 cleanupUpstream();
markchien9b4d7572019-12-25 19:40:32 +08001164 mLastError = TetheringManager.TETHER_ERROR_ENABLE_NAT_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001165 transitionTo(mInitialState);
1166 return true;
1167 }
1168 }
1169 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001170 case CMD_NEIGHBOR_EVENT:
1171 handleNeighborEvent((NeighborEvent) message.obj);
1172 break;
markchien74a4fa92019-09-09 20:50:49 +08001173 default:
1174 return false;
1175 }
1176 return true;
1177 }
1178
1179 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1180 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1181 if (mUpstreamIfaceSet != null && newIfaces != null) {
1182 return mUpstreamIfaceSet.equals(newIfaces);
1183 }
1184 return false;
1185 }
1186
1187 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1188 if (mUpstreamIfaceSet == null) return new HashSet<>();
1189
1190 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1191 removed.removeAll(newIfaces.ifnames);
1192 return removed;
1193 }
1194
1195 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1196 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1197 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1198 return added;
1199 }
1200 }
1201
1202 /**
1203 * This state is terminal for the per interface state machine. At this
1204 * point, the master state machine should have removed this interface
1205 * specific state machine from its list of possible recipients of
1206 * tethering requests. The state machine itself will hang around until
1207 * the garbage collector finds it.
1208 */
1209 class UnavailableState extends State {
1210 @Override
1211 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001212 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001213 sendInterfaceState(STATE_UNAVAILABLE);
1214 }
1215 }
1216
1217 // Accumulate routes representing "prefixes to be assigned to the local
1218 // interface", for subsequent modification of local_network routing.
1219 private static ArrayList<RouteInfo> getLocalRoutesFor(
1220 String ifname, HashSet<IpPrefix> prefixes) {
1221 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1222 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001223 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001224 }
1225 return localRoutes;
1226 }
1227
1228 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1229 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1230 final byte[] dnsBytes = localPrefix.getRawAddress();
1231 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1232 try {
1233 return Inet6Address.getByAddress(null, dnsBytes, 0);
1234 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001235 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001236 return null;
1237 }
1238 }
1239
1240 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1241 final byte random = (byte) (new Random()).nextInt();
1242 for (int value : excluded) {
1243 if (random == value) return dflt;
1244 }
1245 return random;
1246 }
1247}