blob: 38f8609e217ff3ad6a934f018aba60648d4b41d4 [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) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000813 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900814 }
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) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000824 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900825 }
826 }
827
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000828 private void clearIpv6ForwardingRules() {
829 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
830 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
831 }
832 mIpv6ForwardingRules.clear();
833 }
834
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900835 // Convenience method to replace a rule with the same rule on a new upstream interface.
836 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
837 // Relies on the fact that rules are in a map indexed by IP address.
838 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
839 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
840 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
841 }
842
843 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
844 // changes or if a neighbor event is received.
845 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
846 NeighborEvent e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000847 // If we no longer have an upstream, clear forwarding rules and do nothing else.
848 if (upstreamIfindex == 0) {
849 clearIpv6ForwardingRules();
850 return;
851 }
852
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900853 // If the upstream interface has changed, remove all rules and re-add them with the new
854 // upstream interface.
855 if (prevUpstreamIfindex != upstreamIfindex) {
856 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
857 updateIpv6ForwardingRule(rule, upstreamIfindex);
858 }
859 }
860
861 // If we're here to process a NeighborEvent, do so now.
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000862 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900863 if (e == null) return;
864 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
865 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
866 return;
867 }
868
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000869 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900870 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr,
871 e.macAddr);
872 if (e.isValid()) {
873 addIpv6ForwardingRule(rule);
874 } else {
875 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
876 }
877 }
878
879 private void handleNeighborEvent(NeighborEvent e) {
880 if (mInterfaceParams != null
881 && mInterfaceParams.index == e.ifindex
882 && mInterfaceParams.hasMacAddress) {
883 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
884 }
885 }
886
markchien74a4fa92019-09-09 20:50:49 +0800887 private byte getHopLimit(String upstreamIface) {
888 try {
889 int upstreamHopLimit = Integer.parseUnsignedInt(
890 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
891 // Add one hop to account for this forwarding device
892 upstreamHopLimit++;
893 // Cap the hop limit to 255.
894 return (byte) Integer.min(upstreamHopLimit, 255);
895 } catch (Exception e) {
896 mLog.e("Failed to find upstream interface hop limit", e);
897 }
898 return RaParams.DEFAULT_HOPLIMIT;
899 }
900
901 private void setRaParams(RaParams newParams) {
902 if (mRaDaemon != null) {
903 final RaParams deprecatedParams =
904 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
905
906 configureLocalIPv6Routes(deprecatedParams.prefixes,
907 (newParams != null) ? newParams.prefixes : null);
908
909 configureLocalIPv6Dns(deprecatedParams.dnses,
910 (newParams != null) ? newParams.dnses : null);
911
912 mRaDaemon.buildNewRa(deprecatedParams, newParams);
913 }
914
915 mLastRaParams = newParams;
916 }
917
918 private void logMessage(State state, int what) {
919 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
920 }
921
922 private void sendInterfaceState(int newInterfaceState) {
923 mServingMode = newInterfaceState;
924 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
925 sendLinkProperties();
926 }
927
928 private void sendLinkProperties() {
929 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
930 }
931
932 private void resetLinkProperties() {
933 mLinkProperties.clear();
934 mLinkProperties.setInterfaceName(mIfaceName);
935 }
936
937 class InitialState extends State {
938 @Override
939 public void enter() {
940 sendInterfaceState(STATE_AVAILABLE);
941 }
942
943 @Override
944 public boolean processMessage(Message message) {
945 logMessage(this, message.what);
946 switch (message.what) {
947 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800948 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800949 switch (message.arg1) {
950 case STATE_LOCAL_ONLY:
951 transitionTo(mLocalHotspotState);
952 break;
953 case STATE_TETHERED:
954 transitionTo(mTetheredState);
955 break;
956 default:
957 mLog.e("Invalid tethering interface serving state specified.");
958 }
959 break;
960 case CMD_INTERFACE_DOWN:
961 transitionTo(mUnavailableState);
962 break;
963 case CMD_IPV6_TETHER_UPDATE:
964 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
965 break;
966 default:
967 return NOT_HANDLED;
968 }
969 return HANDLED;
970 }
971 }
972
973 class BaseServingState extends State {
974 @Override
975 public void enter() {
976 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +0800977 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800978 return;
979 }
980
981 try {
markchien12c5bb82020-01-07 14:43:17 +0800982 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
983 mIpv4Address.getPrefixLength());
984 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchien6c2b7cc2020-02-15 11:35:00 +0800985 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
markchien74a4fa92019-09-09 20:50:49 +0800986 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +0800987 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800988 return;
989 }
990
991 if (!startIPv6()) {
992 mLog.e("Failed to startIPv6");
993 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
994 return;
995 }
996 }
997
998 @Override
999 public void exit() {
1000 // Note that at this point, we're leaving the tethered state. We can fail any
1001 // of these operations, but it doesn't really change that we have to try them
1002 // all in sequence.
1003 stopIPv6();
1004
1005 try {
markchien12c5bb82020-01-07 14:43:17 +08001006 NetdUtils.untetherInterface(mNetd, mIfaceName);
1007 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001008 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001009 mLog.e("Failed to untether interface: " + e);
1010 }
1011
1012 stopIPv4();
1013
1014 resetLinkProperties();
1015 }
1016
1017 @Override
1018 public boolean processMessage(Message message) {
1019 logMessage(this, message.what);
1020 switch (message.what) {
1021 case CMD_TETHER_UNREQUESTED:
1022 transitionTo(mInitialState);
1023 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1024 break;
1025 case CMD_INTERFACE_DOWN:
1026 transitionTo(mUnavailableState);
1027 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1028 break;
1029 case CMD_IPV6_TETHER_UPDATE:
1030 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1031 sendLinkProperties();
1032 break;
1033 case CMD_IP_FORWARDING_ENABLE_ERROR:
1034 case CMD_IP_FORWARDING_DISABLE_ERROR:
1035 case CMD_START_TETHERING_ERROR:
1036 case CMD_STOP_TETHERING_ERROR:
1037 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien9b4d7572019-12-25 19:40:32 +08001038 mLastError = TetheringManager.TETHER_ERROR_MASTER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001039 transitionTo(mInitialState);
1040 break;
1041 default:
1042 return false;
1043 }
1044 return true;
1045 }
1046 }
1047
1048 // Handling errors in BaseServingState.enter() by transitioning is
1049 // problematic because transitioning during a multi-state jump yields
1050 // a Log.wtf(). Ultimately, there should be only one ServingState,
1051 // and forwarding and NAT rules should be handled by a coordinating
1052 // functional element outside of IpServer.
1053 class LocalHotspotState extends BaseServingState {
1054 @Override
1055 public void enter() {
1056 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001057 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001058 transitionTo(mInitialState);
1059 }
1060
1061 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1062 sendInterfaceState(STATE_LOCAL_ONLY);
1063 }
1064
1065 @Override
1066 public boolean processMessage(Message message) {
1067 if (super.processMessage(message)) return true;
1068
1069 logMessage(this, message.what);
1070 switch (message.what) {
1071 case CMD_TETHER_REQUESTED:
1072 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1073 break;
1074 case CMD_TETHER_CONNECTION_CHANGED:
1075 // Ignored in local hotspot state.
1076 break;
1077 default:
1078 return false;
1079 }
1080 return true;
1081 }
1082 }
1083
1084 // Handling errors in BaseServingState.enter() by transitioning is
1085 // problematic because transitioning during a multi-state jump yields
1086 // a Log.wtf(). Ultimately, there should be only one ServingState,
1087 // and forwarding and NAT rules should be handled by a coordinating
1088 // functional element outside of IpServer.
1089 class TetheredState extends BaseServingState {
1090 @Override
1091 public void enter() {
1092 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001093 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001094 transitionTo(mInitialState);
1095 }
1096
1097 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1098 sendInterfaceState(STATE_TETHERED);
1099 }
1100
1101 @Override
1102 public void exit() {
1103 cleanupUpstream();
1104 super.exit();
1105 }
1106
1107 private void cleanupUpstream() {
1108 if (mUpstreamIfaceSet == null) return;
1109
1110 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1111 mUpstreamIfaceSet = null;
Automerger Merge Workerf1194882020-02-25 04:04:44 +00001112 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001113 }
1114
1115 private void cleanupUpstreamInterface(String upstreamIface) {
1116 // Note that we don't care about errors here.
1117 // Sometimes interfaces are gone before we get
1118 // to remove their rules, which generates errors.
1119 // Just do the best we can.
1120 try {
markchien12c5bb82020-01-07 14:43:17 +08001121 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1122 } catch (RemoteException | ServiceSpecificException e) {
1123 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001124 }
1125 try {
markchien12c5bb82020-01-07 14:43:17 +08001126 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1127 } catch (RemoteException | ServiceSpecificException e) {
1128 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001129 }
1130 }
1131
1132 @Override
1133 public boolean processMessage(Message message) {
1134 if (super.processMessage(message)) return true;
1135
1136 logMessage(this, message.what);
1137 switch (message.what) {
1138 case CMD_TETHER_REQUESTED:
1139 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1140 break;
1141 case CMD_TETHER_CONNECTION_CHANGED:
1142 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1143 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1144 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1145 break;
1146 }
1147
1148 if (newUpstreamIfaceSet == null) {
1149 cleanupUpstream();
1150 break;
1151 }
1152
1153 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1154 cleanupUpstreamInterface(removed);
1155 }
1156
1157 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1158 // This makes the call to cleanupUpstream() in the error
1159 // path for any interface neatly cleanup all the interfaces.
1160 mUpstreamIfaceSet = newUpstreamIfaceSet;
1161
1162 for (String ifname : added) {
1163 try {
markchien12c5bb82020-01-07 14:43:17 +08001164 mNetd.tetherAddForward(mIfaceName, ifname);
1165 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1166 } catch (RemoteException | ServiceSpecificException e) {
1167 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001168 cleanupUpstream();
markchien9b4d7572019-12-25 19:40:32 +08001169 mLastError = TetheringManager.TETHER_ERROR_ENABLE_NAT_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001170 transitionTo(mInitialState);
1171 return true;
1172 }
1173 }
1174 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001175 case CMD_NEIGHBOR_EVENT:
1176 handleNeighborEvent((NeighborEvent) message.obj);
1177 break;
markchien74a4fa92019-09-09 20:50:49 +08001178 default:
1179 return false;
1180 }
1181 return true;
1182 }
1183
1184 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1185 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1186 if (mUpstreamIfaceSet != null && newIfaces != null) {
1187 return mUpstreamIfaceSet.equals(newIfaces);
1188 }
1189 return false;
1190 }
1191
1192 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1193 if (mUpstreamIfaceSet == null) return new HashSet<>();
1194
1195 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1196 removed.removeAll(newIfaces.ifnames);
1197 return removed;
1198 }
1199
1200 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1201 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1202 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1203 return added;
1204 }
1205 }
1206
1207 /**
1208 * This state is terminal for the per interface state machine. At this
1209 * point, the master state machine should have removed this interface
1210 * specific state machine from its list of possible recipients of
1211 * tethering requests. The state machine itself will hang around until
1212 * the garbage collector finds it.
1213 */
1214 class UnavailableState extends State {
1215 @Override
1216 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001217 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001218 sendInterfaceState(STATE_UNAVAILABLE);
1219 }
1220 }
1221
1222 // Accumulate routes representing "prefixes to be assigned to the local
1223 // interface", for subsequent modification of local_network routing.
1224 private static ArrayList<RouteInfo> getLocalRoutesFor(
1225 String ifname, HashSet<IpPrefix> prefixes) {
1226 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1227 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001228 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001229 }
1230 return localRoutes;
1231 }
1232
1233 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1234 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1235 final byte[] dnsBytes = localPrefix.getRawAddress();
1236 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1237 try {
1238 return Inet6Address.getByAddress(null, dnsBytes, 0);
1239 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001240 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001241 return null;
1242 }
1243 }
1244
1245 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1246 final byte random = (byte) (new Random()).nextInt();
1247 for (int value : excluded) {
1248 if (random == value) return dflt;
1249 }
1250 return random;
1251 }
1252}