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