blob: 433b903ebe52188f427d73c9491f117fa235785e [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;
Automerger Merge Worker0010ca02020-03-16 04:06:46 +000027import static android.system.OsConstants.RT_SCOPE_UNIVERSE;
markchien74a4fa92019-09-09 20:50:49 +080028
markchien74a4fa92019-09-09 20:50:49 +080029import android.net.INetd;
30import android.net.INetworkStackStatusCallback;
markchien74a4fa92019-09-09 20:50:49 +080031import android.net.IpPrefix;
32import android.net.LinkAddress;
33import android.net.LinkProperties;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090034import android.net.MacAddress;
markchien74a4fa92019-09-09 20:50:49 +080035import android.net.RouteInfo;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090036import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080037import android.net.TetheringManager;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +000038import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090039import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080040import android.net.dhcp.DhcpServerCallbacks;
41import android.net.dhcp.DhcpServingParamsParcel;
42import android.net.dhcp.DhcpServingParamsParcelExt;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090043import android.net.dhcp.IDhcpLeaseCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080044import android.net.dhcp.IDhcpServer;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090045import android.net.ip.IpNeighborMonitor.NeighborEvent;
markchien74a4fa92019-09-09 20:50:49 +080046import android.net.ip.RouterAdvertisementDaemon.RaParams;
markchien12c5bb82020-01-07 14:43:17 +080047import android.net.shared.NetdUtils;
48import android.net.shared.RouteUtils;
markchien74a4fa92019-09-09 20:50:49 +080049import android.net.util.InterfaceParams;
50import android.net.util.InterfaceSet;
markchien74a4fa92019-09-09 20:50:49 +080051import android.net.util.SharedLog;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090052import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080053import android.os.Looper;
54import android.os.Message;
55import android.os.RemoteException;
56import android.os.ServiceSpecificException;
57import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080058import android.util.SparseArray;
59
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090060import androidx.annotation.NonNull;
61
markchien74a4fa92019-09-09 20:50:49 +080062import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080063import com.android.internal.util.State;
64import com.android.internal.util.StateMachine;
65
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090066import java.io.IOException;
markchien74a4fa92019-09-09 20:50:49 +080067import java.net.Inet4Address;
68import java.net.Inet6Address;
69import java.net.InetAddress;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090070import java.net.NetworkInterface;
markchien74a4fa92019-09-09 20:50:49 +080071import java.net.UnknownHostException;
72import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090073import java.util.Arrays;
74import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080075import java.util.HashSet;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090076import java.util.LinkedHashMap;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090077import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080078import java.util.Objects;
79import java.util.Random;
80import java.util.Set;
81
82/**
83 * Provides the interface to IP-layer serving functionality for a given network
84 * interface, e.g. for tethering or "local-only hotspot" mode.
85 *
86 * @hide
87 */
88public class IpServer extends StateMachine {
89 public static final int STATE_UNAVAILABLE = 0;
90 public static final int STATE_AVAILABLE = 1;
91 public static final int STATE_TETHERED = 2;
92 public static final int STATE_LOCAL_ONLY = 3;
93
94 /** Get string name of |state|.*/
95 public static String getStateString(int state) {
96 switch (state) {
97 case STATE_UNAVAILABLE: return "UNAVAILABLE";
98 case STATE_AVAILABLE: return "AVAILABLE";
99 case STATE_TETHERED: return "TETHERED";
100 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
101 }
102 return "UNKNOWN: " + state;
103 }
104
105 private static final byte DOUG_ADAMS = (byte) 42;
106
107 private static final String USB_NEAR_IFACE_ADDR = "192.168.42.129";
108 private static final int USB_PREFIX_LENGTH = 24;
109 private static final String WIFI_HOST_IFACE_ADDR = "192.168.43.1";
110 private static final int WIFI_HOST_IFACE_PREFIX_LENGTH = 24;
111 private static final String WIFI_P2P_IFACE_ADDR = "192.168.49.1";
112 private static final int WIFI_P2P_IFACE_PREFIX_LENGTH = 24;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900113 private static final String ETHERNET_IFACE_ADDR = "192.168.50.1";
114 private static final int ETHERNET_IFACE_PREFIX_LENGTH = 24;
markchien74a4fa92019-09-09 20:50:49 +0800115
116 // TODO: have PanService use some visible version of this constant
117 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1";
118 private static final int BLUETOOTH_DHCP_PREFIX_LENGTH = 24;
119
120 // TODO: have this configurable
121 private static final int DHCP_LEASE_TIME_SECS = 3600;
122
123 private static final String TAG = "IpServer";
124 private static final boolean DBG = false;
125 private static final boolean VDBG = false;
126 private static final Class[] sMessageClasses = {
127 IpServer.class
128 };
129 private static final SparseArray<String> sMagicDecoderRing =
130 MessageUtils.findMessageNames(sMessageClasses);
131
132 /** IpServer callback. */
133 public static class Callback {
134 /**
135 * Notify that |who| has changed its tethering state.
136 *
137 * @param who the calling instance of IpServer
138 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800139 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800140 */
markchien9d353822019-12-16 20:15:20 +0800141 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800142
143 /**
144 * Notify that |who| has new LinkProperties.
145 *
146 * @param who the calling instance of IpServer
147 * @param newLp the new LinkProperties to report
148 */
markchien9d353822019-12-16 20:15:20 +0800149 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900150
151 /**
152 * Notify that the DHCP leases changed in one of the IpServers.
153 */
154 public void dhcpLeasesChanged() { }
markchien74a4fa92019-09-09 20:50:49 +0800155 }
156
157 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800158 public abstract static class Dependencies {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900159 /** Create an IpNeighborMonitor to be used by this IpServer */
160 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
161 IpNeighborMonitor.NeighborEventConsumer consumer) {
162 return new IpNeighborMonitor(handler, log, consumer);
163 }
164
markchien74a4fa92019-09-09 20:50:49 +0800165 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
166 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
167 return new RouterAdvertisementDaemon(ifParams);
168 }
169
170 /** Get |ifName|'s interface information.*/
171 public InterfaceParams getInterfaceParams(String ifName) {
172 return InterfaceParams.getByName(ifName);
173 }
174
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900175 /** Get |ifName|'s interface index. */
176 public int getIfindex(String ifName) {
177 try {
178 return NetworkInterface.getByName(ifName).getIndex();
179 } catch (IOException | NullPointerException e) {
180 Log.e(TAG, "Can't determine interface index for interface " + ifName);
181 return 0;
182 }
183 }
markchien9d353822019-12-16 20:15:20 +0800184 /** Create a DhcpServer instance to be used by IpServer. */
185 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
186 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800187 }
188
markchien74a4fa92019-09-09 20:50:49 +0800189 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800190 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800191 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800192 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800193 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800194 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
markchien74a4fa92019-09-09 20:50:49 +0800195 // notification from the master SM that it had trouble enabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800196 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
markchien74a4fa92019-09-09 20:50:49 +0800197 // notification from the master SM that it had trouble disabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800198 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
markchien74a4fa92019-09-09 20:50:49 +0800199 // notification from the master SM that it had trouble starting tethering
markchien6cf0e552019-12-06 15:24:53 +0800200 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
markchien74a4fa92019-09-09 20:50:49 +0800201 // notification from the master SM that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800202 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
markchien74a4fa92019-09-09 20:50:49 +0800203 // notification from the master SM that it had trouble setting the DNS forwarders
markchien6cf0e552019-12-06 15:24:53 +0800204 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800205 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800206 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800207 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800208 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900209 // new neighbor cache entry on our interface
210 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
markchien74a4fa92019-09-09 20:50:49 +0800211
212 private final State mInitialState;
213 private final State mLocalHotspotState;
214 private final State mTetheredState;
215 private final State mUnavailableState;
216
217 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800218 private final INetd mNetd;
markchien74a4fa92019-09-09 20:50:49 +0800219 private final Callback mCallback;
220 private final InterfaceController mInterfaceCtrl;
221
222 private final String mIfaceName;
223 private final int mInterfaceType;
224 private final LinkProperties mLinkProperties;
225 private final boolean mUsingLegacyDhcp;
226
227 private final Dependencies mDeps;
228
229 private int mLastError;
230 private int mServingMode;
231 private InterfaceSet mUpstreamIfaceSet; // may change over time
232 private InterfaceParams mInterfaceParams;
233 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
234 // properties are those selected by the IPv6TetheringCoordinator and relayed
235 // to us. By comparison, mLinkProperties contains the addresses and directly
236 // connected routes that have been formed from these properties iff. we have
237 // succeeded in configuring them and are able to announce them within Router
238 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
239 private LinkProperties mLastIPv6LinkProperties;
240 private RouterAdvertisementDaemon mRaDaemon;
241
242 // To be accessed only on the handler thread
243 private int mDhcpServerStartIndex = 0;
244 private IDhcpServer mDhcpServer;
245 private RaParams mLastRaParams;
markchien12c5bb82020-01-07 14:43:17 +0800246 private LinkAddress mIpv4Address;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000247
248 private LinkAddress mStaticIpv4ServerAddr;
249 private LinkAddress mStaticIpv4ClientAddr;
250
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900251 @NonNull
252 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800253
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900254 private int mLastIPv6UpstreamIfindex = 0;
255
256 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
257 public void accept(NeighborEvent e) {
258 sendMessage(CMD_NEIGHBOR_EVENT, e);
259 }
260 }
261
262 static class Ipv6ForwardingRule {
263 public final int upstreamIfindex;
264 public final int downstreamIfindex;
265 public final Inet6Address address;
266 public final MacAddress srcMac;
267 public final MacAddress dstMac;
268
269 Ipv6ForwardingRule(int upstreamIfindex, int downstreamIfIndex, Inet6Address address,
270 MacAddress srcMac, MacAddress dstMac) {
271 this.upstreamIfindex = upstreamIfindex;
272 this.downstreamIfindex = downstreamIfIndex;
273 this.address = address;
274 this.srcMac = srcMac;
275 this.dstMac = dstMac;
276 }
277
278 public Ipv6ForwardingRule onNewUpstream(int newUpstreamIfindex) {
279 return new Ipv6ForwardingRule(newUpstreamIfindex, downstreamIfindex, address, srcMac,
280 dstMac);
281 }
282 }
283 private final LinkedHashMap<Inet6Address, Ipv6ForwardingRule> mIpv6ForwardingRules =
284 new LinkedHashMap<>();
285
286 private final IpNeighborMonitor mIpNeighborMonitor;
287
markchien74a4fa92019-09-09 20:50:49 +0800288 public IpServer(
289 String ifaceName, Looper looper, int interfaceType, SharedLog log,
junyulai5864a3f2019-12-03 14:34:13 +0800290 INetd netd, Callback callback, boolean usingLegacyDhcp, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800291 super(ifaceName, looper);
292 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800293 mNetd = netd;
markchien74a4fa92019-09-09 20:50:49 +0800294 mCallback = callback;
295 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
296 mIfaceName = ifaceName;
297 mInterfaceType = interfaceType;
298 mLinkProperties = new LinkProperties();
299 mUsingLegacyDhcp = usingLegacyDhcp;
300 mDeps = deps;
301 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800302 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800303 mServingMode = STATE_AVAILABLE;
304
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900305 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
306 new MyNeighborEventConsumer());
307 if (!mIpNeighborMonitor.start()) {
308 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
309 }
310
markchien74a4fa92019-09-09 20:50:49 +0800311 mInitialState = new InitialState();
312 mLocalHotspotState = new LocalHotspotState();
313 mTetheredState = new TetheredState();
314 mUnavailableState = new UnavailableState();
315 addState(mInitialState);
316 addState(mLocalHotspotState);
317 addState(mTetheredState);
318 addState(mUnavailableState);
319
320 setInitialState(mInitialState);
321 }
322
323 /** Interface name which IpServer served.*/
324 public String interfaceName() {
325 return mIfaceName;
326 }
327
328 /**
markchien9b4d7572019-12-25 19:40:32 +0800329 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800330 */
331 public int interfaceType() {
332 return mInterfaceType;
333 }
334
335 /** Last error from this IpServer. */
336 public int lastError() {
337 return mLastError;
338 }
339
340 /** Serving mode is the current state of IpServer state machine. */
341 public int servingMode() {
342 return mServingMode;
343 }
344
345 /** The properties of the network link which IpServer is serving. */
346 public LinkProperties linkProperties() {
347 return new LinkProperties(mLinkProperties);
348 }
349
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900350 /**
351 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
352 * thread.
353 */
354 public List<TetheredClient> getAllLeases() {
355 return Collections.unmodifiableList(mDhcpLeases);
356 }
357
markchien74a4fa92019-09-09 20:50:49 +0800358 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
359 public void stop() {
360 sendMessage(CMD_INTERFACE_DOWN);
361 }
362
363 /**
364 * Tethering is canceled. IpServer state machine will be available and wait for
365 * next tethering request.
366 */
367 public void unwanted() {
368 sendMessage(CMD_TETHER_UNREQUESTED);
369 }
370
371 /** Internals. */
372
373 private boolean startIPv4() {
374 return configureIPv4(true);
375 }
376
377 /**
378 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
379 * handler.
380 *
381 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
382 * with different implementations of the callback, to differentiate handling of success/error in
383 * each call.
384 */
385 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
386 @Override
387 public void onStatusAvailable(int statusCode) {
388 getHandler().post(() -> callback(statusCode));
389 }
390
391 public abstract void callback(int statusCode);
392
393 @Override
394 public int getInterfaceVersion() {
395 return this.VERSION;
396 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900397
398 @Override
399 public String getInterfaceHash() {
400 return this.HASH;
401 }
markchien74a4fa92019-09-09 20:50:49 +0800402 }
403
404 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
405 private final int mStartIndex;
406
407 private DhcpServerCallbacksImpl(int startIndex) {
408 mStartIndex = startIndex;
409 }
410
411 @Override
412 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
413 getHandler().post(() -> {
414 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
415 if (mStartIndex != mDhcpServerStartIndex) {
416 // This start request is obsolete. When the |server| binder token goes out of
417 // scope, the garbage collector will finalize it, which causes the network stack
418 // process garbage collector to collect the server itself.
419 return;
420 }
421
422 if (statusCode != STATUS_SUCCESS) {
423 mLog.e("Error obtaining DHCP server: " + statusCode);
424 handleError();
425 return;
426 }
427
428 mDhcpServer = server;
429 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900430 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800431 @Override
432 public void callback(int startStatusCode) {
433 if (startStatusCode != STATUS_SUCCESS) {
434 mLog.e("Error starting DHCP server: " + startStatusCode);
435 handleError();
436 }
437 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900438 }, new DhcpLeaseCallback());
markchien74a4fa92019-09-09 20:50:49 +0800439 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800440 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800441 }
442 });
443 }
444
445 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800446 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800447 transitionTo(mInitialState);
448 }
449 }
450
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900451 private class DhcpLeaseCallback extends IDhcpLeaseCallbacks.Stub {
452 @Override
453 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
454 final ArrayList<TetheredClient> leases = new ArrayList<>();
455 for (DhcpLeaseParcelable lease : leaseParcelables) {
456 final LinkAddress address = new LinkAddress(
Automerger Merge Worker0010ca02020-03-16 04:06:46 +0000457 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
458 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
459 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900460
461 final MacAddress macAddress;
462 try {
463 macAddress = MacAddress.fromBytes(lease.hwAddr);
464 } catch (IllegalArgumentException e) {
465 Log.wtf(TAG, "Invalid address received from DhcpServer: "
466 + Arrays.toString(lease.hwAddr));
467 return;
468 }
469
470 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Automerger Merge Worker0010ca02020-03-16 04:06:46 +0000471 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900472 leases.add(new TetheredClient(
473 macAddress,
474 Collections.singletonList(addressInfo),
475 mInterfaceType));
476 }
477
478 getHandler().post(() -> {
479 mDhcpLeases = leases;
480 mCallback.dhcpLeasesChanged();
481 });
482 }
483
484 @Override
485 public int getInterfaceVersion() {
486 return this.VERSION;
487 }
488
489 @Override
490 public String getInterfaceHash() throws RemoteException {
491 return this.HASH;
492 }
493 }
494
markchien74a4fa92019-09-09 20:50:49 +0800495 private boolean startDhcp(Inet4Address addr, int prefixLen) {
496 if (mUsingLegacyDhcp) {
497 return true;
498 }
499 final DhcpServingParamsParcel params;
500 params = new DhcpServingParamsParcelExt()
501 .setDefaultRouters(addr)
502 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
503 .setDnsServers(addr)
504 .setServerAddr(new LinkAddress(addr, prefixLen))
505 .setMetered(true);
506 // TODO: also advertise link MTU
507
508 mDhcpServerStartIndex++;
509 mDeps.makeDhcpServer(
510 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
511 return true;
512 }
513
514 private void stopDhcp() {
515 // Make all previous start requests obsolete so servers are not started later
516 mDhcpServerStartIndex++;
517
518 if (mDhcpServer != null) {
519 try {
520 mDhcpServer.stop(new OnHandlerStatusCallback() {
521 @Override
522 public void callback(int statusCode) {
523 if (statusCode != STATUS_SUCCESS) {
524 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800525 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800526 // Not much more we can do here
527 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900528 mDhcpLeases.clear();
529 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800530 }
531 });
532 mDhcpServer = null;
533 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800534 mLog.e("Error stopping DHCP", e);
535 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800536 }
537 }
538 }
539
540 private boolean configureDhcp(boolean enable, Inet4Address addr, int prefixLen) {
541 if (enable) {
542 return startDhcp(addr, prefixLen);
543 } else {
544 stopDhcp();
545 return true;
546 }
547 }
548
549 private void stopIPv4() {
550 configureIPv4(false);
551 // NOTE: All of configureIPv4() will be refactored out of existence
552 // into calls to InterfaceController, shared with startIPv4().
553 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800554 mIpv4Address = null;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000555 mStaticIpv4ServerAddr = null;
556 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800557 }
558
markchien74a4fa92019-09-09 20:50:49 +0800559 private boolean configureIPv4(boolean enabled) {
560 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
561
562 // TODO: Replace this hard-coded information with dynamically selected
563 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800564 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800565 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800566 try {
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000567 if (mStaticIpv4ServerAddr != null) {
568 srvAddr = (Inet4Address) mStaticIpv4ServerAddr.getAddress();
569 prefixLen = mStaticIpv4ServerAddr.getPrefixLength();
570 } else if (mInterfaceType == TetheringManager.TETHERING_USB
Milim Lee45a971b2019-10-17 05:02:33 +0900571 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien12c5bb82020-01-07 14:43:17 +0800572 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
573 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800574 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800575 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
576 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800577 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800578 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
579 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900580 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
581 // TODO: randomize address for tethering too, similarly to wifi
582 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
583 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien12c5bb82020-01-07 14:43:17 +0800584 } else {
585 // BT configures the interface elsewhere: only start DHCP.
586 // TODO: make all tethering types behave the same way, and delete the bluetooth
587 // code that calls into NetworkManagementService directly.
588 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
589 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
590 return configureDhcp(enabled, srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
591 }
592 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
593 } catch (IllegalArgumentException e) {
594 mLog.e("Error selecting ipv4 address", e);
595 if (!enabled) stopDhcp();
596 return false;
markchien74a4fa92019-09-09 20:50:49 +0800597 }
598
markchien12c5bb82020-01-07 14:43:17 +0800599 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800600 if (mInterfaceType == TetheringManager.TETHERING_WIFI
601 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800602 // The WiFi stack has ownership of the interface up/down state.
603 // It is unclear whether the Bluetooth or USB stacks will manage their own
604 // state.
605 setIfaceUp = null;
606 } else {
607 setIfaceUp = enabled;
608 }
609 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
610 mLog.e("Error configuring interface");
611 if (!enabled) stopDhcp();
612 return false;
613 }
markchien74a4fa92019-09-09 20:50:49 +0800614
markchien74a4fa92019-09-09 20:50:49 +0800615 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800616 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
617 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800618 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800619 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800620 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800621 mLinkProperties.addRoute(route);
622 } else {
markchien12c5bb82020-01-07 14:43:17 +0800623 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800624 mLinkProperties.removeRoute(route);
625 }
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000626
627 return configureDhcp(enabled, srvAddr, prefixLen);
markchien74a4fa92019-09-09 20:50:49 +0800628 }
629
630 private String getRandomWifiIPv4Address() {
631 try {
632 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
633 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
634 return InetAddress.getByAddress(bytes).getHostAddress();
635 } catch (Exception e) {
636 return WIFI_HOST_IFACE_ADDR;
637 }
638 }
639
640 private boolean startIPv6() {
641 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
642 if (mInterfaceParams == null) {
643 mLog.e("Failed to find InterfaceParams");
644 stopIPv6();
645 return false;
646 }
647
648 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
649 if (!mRaDaemon.start()) {
650 stopIPv6();
651 return false;
652 }
653
654 return true;
655 }
656
657 private void stopIPv6() {
658 mInterfaceParams = null;
659 setRaParams(null);
660
661 if (mRaDaemon != null) {
662 mRaDaemon.stop();
663 mRaDaemon = null;
664 }
665 }
666
667 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
668 // LinkProperties. These have extraneous data filtered out and only the
669 // necessary prefixes included (per its prefix distribution policy).
670 //
671 // TODO: Evaluate using a data structure than is more directly suited to
672 // communicating only the relevant information.
673 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
674 if (mRaDaemon == null) return;
675
676 // Avoid unnecessary work on spurious updates.
677 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
678 return;
679 }
680
681 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900682 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800683
684 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900685 final String upstreamIface = v6only.getInterfaceName();
686
markchien74a4fa92019-09-09 20:50:49 +0800687 params = new RaParams();
Maciej Żenczykowskida0fb1b2020-02-19 01:24:39 -0800688 // We advertise an mtu lower by 16, which is the closest multiple of 8 >= 14,
689 // the ethernet header size. This makes kernel ebpf tethering offload happy.
690 // This hack should be reverted once we have the kernel fixed up.
691 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
692 // see RouterAdvertisementDaemon.java putMtu()
693 params.mtu = v6only.getMtu() - 16;
markchien74a4fa92019-09-09 20:50:49 +0800694 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
695
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900696 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800697
698 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
699 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
700
701 final IpPrefix prefix = new IpPrefix(
702 linkAddr.getAddress(), linkAddr.getPrefixLength());
703 params.prefixes.add(prefix);
704
705 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
706 if (dnsServer != null) {
707 params.dnses.add(dnsServer);
708 }
709 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900710
711 upstreamIfindex = mDeps.getIfindex(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800712 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900713
markchien74a4fa92019-09-09 20:50:49 +0800714 // If v6only is null, we pass in null to setRaParams(), which handles
715 // deprecation of any existing RA data.
716
717 setRaParams(params);
718 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900719
720 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
721 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800722 }
723
724 private void configureLocalIPv6Routes(
725 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
726 // [1] Remove the routes that are deprecated.
727 if (!deprecatedPrefixes.isEmpty()) {
728 final ArrayList<RouteInfo> toBeRemoved =
729 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800730 // Remove routes from local network.
731 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
732 mNetd, toBeRemoved);
733 if (removalFailures > 0) {
734 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
735 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800736 }
737
738 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
739 }
740
741 // [2] Add only the routes that have not previously been added.
742 if (newPrefixes != null && !newPrefixes.isEmpty()) {
743 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
744 if (mLastRaParams != null) {
745 addedPrefixes.removeAll(mLastRaParams.prefixes);
746 }
747
748 if (!addedPrefixes.isEmpty()) {
749 final ArrayList<RouteInfo> toBeAdded =
750 getLocalRoutesFor(mIfaceName, addedPrefixes);
751 try {
markchien12c5bb82020-01-07 14:43:17 +0800752 // It's safe to call networkAddInterface() even if
753 // the interface is already in the local_network.
754 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
755 try {
756 // Add routes from local network. Note that adding routes that
757 // already exist does not cause an error (EEXIST is silently ignored).
758 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
759 } catch (IllegalStateException e) {
760 mLog.e("Failed to add IPv6 routes to local table: " + e);
761 }
762 } catch (ServiceSpecificException | RemoteException e) {
763 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800764 }
765
766 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
767 }
768 }
769 }
770
771 private void configureLocalIPv6Dns(
772 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
773 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
774 if (mNetd == null) {
775 if (newDnses != null) newDnses.clear();
776 mLog.e("No netd service instance available; not setting local IPv6 addresses");
777 return;
778 }
779
780 // [1] Remove deprecated local DNS IP addresses.
781 if (!deprecatedDnses.isEmpty()) {
782 for (Inet6Address dns : deprecatedDnses) {
783 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
784 mLog.e("Failed to remove local dns IP " + dns);
785 }
786
787 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
788 }
789 }
790
791 // [2] Add only the local DNS IP addresses that have not previously been added.
792 if (newDnses != null && !newDnses.isEmpty()) {
793 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
794 if (mLastRaParams != null) {
795 addedDnses.removeAll(mLastRaParams.dnses);
796 }
797
798 for (Inet6Address dns : addedDnses) {
799 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
800 mLog.e("Failed to add local dns IP " + dns);
801 newDnses.remove(dns);
802 }
803
804 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
805 }
806 }
807
808 try {
809 mNetd.tetherApplyDnsInterfaces();
810 } catch (ServiceSpecificException | RemoteException e) {
811 mLog.e("Failed to update local DNS caching server");
812 if (newDnses != null) newDnses.clear();
813 }
814 }
815
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900816 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
817 try {
818 mNetd.tetherRuleAddDownstreamIpv6(mInterfaceParams.index, rule.upstreamIfindex,
819 rule.address.getAddress(), mInterfaceParams.macAddr.toByteArray(),
820 rule.dstMac.toByteArray());
821 mIpv6ForwardingRules.put(rule.address, rule);
822 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000823 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900824 }
825 }
826
827 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
828 try {
829 mNetd.tetherRuleRemoveDownstreamIpv6(rule.upstreamIfindex, rule.address.getAddress());
830 if (removeFromMap) {
831 mIpv6ForwardingRules.remove(rule.address);
832 }
833 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000834 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900835 }
836 }
837
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000838 private void clearIpv6ForwardingRules() {
839 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
840 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
841 }
842 mIpv6ForwardingRules.clear();
843 }
844
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900845 // Convenience method to replace a rule with the same rule on a new upstream interface.
846 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
847 // Relies on the fact that rules are in a map indexed by IP address.
848 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
849 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
850 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
851 }
852
853 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
854 // changes or if a neighbor event is received.
855 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
856 NeighborEvent e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000857 // If we no longer have an upstream, clear forwarding rules and do nothing else.
858 if (upstreamIfindex == 0) {
859 clearIpv6ForwardingRules();
860 return;
861 }
862
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900863 // If the upstream interface has changed, remove all rules and re-add them with the new
864 // upstream interface.
865 if (prevUpstreamIfindex != upstreamIfindex) {
866 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
867 updateIpv6ForwardingRule(rule, upstreamIfindex);
868 }
869 }
870
871 // If we're here to process a NeighborEvent, do so now.
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000872 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900873 if (e == null) return;
874 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
875 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
876 return;
877 }
878
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000879 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900880 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr,
881 e.macAddr);
882 if (e.isValid()) {
883 addIpv6ForwardingRule(rule);
884 } else {
885 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
886 }
887 }
888
889 private void handleNeighborEvent(NeighborEvent e) {
890 if (mInterfaceParams != null
891 && mInterfaceParams.index == e.ifindex
892 && mInterfaceParams.hasMacAddress) {
893 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
894 }
895 }
896
markchien74a4fa92019-09-09 20:50:49 +0800897 private byte getHopLimit(String upstreamIface) {
898 try {
899 int upstreamHopLimit = Integer.parseUnsignedInt(
900 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
901 // Add one hop to account for this forwarding device
902 upstreamHopLimit++;
903 // Cap the hop limit to 255.
904 return (byte) Integer.min(upstreamHopLimit, 255);
905 } catch (Exception e) {
906 mLog.e("Failed to find upstream interface hop limit", e);
907 }
908 return RaParams.DEFAULT_HOPLIMIT;
909 }
910
911 private void setRaParams(RaParams newParams) {
912 if (mRaDaemon != null) {
913 final RaParams deprecatedParams =
914 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
915
916 configureLocalIPv6Routes(deprecatedParams.prefixes,
917 (newParams != null) ? newParams.prefixes : null);
918
919 configureLocalIPv6Dns(deprecatedParams.dnses,
920 (newParams != null) ? newParams.dnses : null);
921
922 mRaDaemon.buildNewRa(deprecatedParams, newParams);
923 }
924
925 mLastRaParams = newParams;
926 }
927
928 private void logMessage(State state, int what) {
929 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
930 }
931
932 private void sendInterfaceState(int newInterfaceState) {
933 mServingMode = newInterfaceState;
934 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
935 sendLinkProperties();
936 }
937
938 private void sendLinkProperties() {
939 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
940 }
941
942 private void resetLinkProperties() {
943 mLinkProperties.clear();
944 mLinkProperties.setInterfaceName(mIfaceName);
945 }
946
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000947 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
948 if (request == null) return;
949
950 mStaticIpv4ServerAddr = request.localIPv4Address;
951 mStaticIpv4ClientAddr = request.staticClientAddress;
952 }
953
markchien74a4fa92019-09-09 20:50:49 +0800954 class InitialState extends State {
955 @Override
956 public void enter() {
957 sendInterfaceState(STATE_AVAILABLE);
958 }
959
960 @Override
961 public boolean processMessage(Message message) {
962 logMessage(this, message.what);
963 switch (message.what) {
964 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800965 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800966 switch (message.arg1) {
967 case STATE_LOCAL_ONLY:
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000968 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +0800969 transitionTo(mLocalHotspotState);
970 break;
971 case STATE_TETHERED:
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000972 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +0800973 transitionTo(mTetheredState);
974 break;
975 default:
976 mLog.e("Invalid tethering interface serving state specified.");
977 }
978 break;
979 case CMD_INTERFACE_DOWN:
980 transitionTo(mUnavailableState);
981 break;
982 case CMD_IPV6_TETHER_UPDATE:
983 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
984 break;
985 default:
986 return NOT_HANDLED;
987 }
988 return HANDLED;
989 }
990 }
991
992 class BaseServingState extends State {
993 @Override
994 public void enter() {
995 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +0800996 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800997 return;
998 }
999
1000 try {
markchien12c5bb82020-01-07 14:43:17 +08001001 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
1002 mIpv4Address.getPrefixLength());
1003 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchien6c2b7cc2020-02-15 11:35:00 +08001004 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
markchien74a4fa92019-09-09 20:50:49 +08001005 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +08001006 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001007 return;
1008 }
1009
1010 if (!startIPv6()) {
1011 mLog.e("Failed to startIPv6");
1012 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1013 return;
1014 }
1015 }
1016
1017 @Override
1018 public void exit() {
1019 // Note that at this point, we're leaving the tethered state. We can fail any
1020 // of these operations, but it doesn't really change that we have to try them
1021 // all in sequence.
1022 stopIPv6();
1023
1024 try {
markchien12c5bb82020-01-07 14:43:17 +08001025 NetdUtils.untetherInterface(mNetd, mIfaceName);
1026 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001027 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001028 mLog.e("Failed to untether interface: " + e);
1029 }
1030
1031 stopIPv4();
1032
1033 resetLinkProperties();
1034 }
1035
1036 @Override
1037 public boolean processMessage(Message message) {
1038 logMessage(this, message.what);
1039 switch (message.what) {
1040 case CMD_TETHER_UNREQUESTED:
1041 transitionTo(mInitialState);
1042 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1043 break;
1044 case CMD_INTERFACE_DOWN:
1045 transitionTo(mUnavailableState);
1046 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1047 break;
1048 case CMD_IPV6_TETHER_UPDATE:
1049 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1050 sendLinkProperties();
1051 break;
1052 case CMD_IP_FORWARDING_ENABLE_ERROR:
1053 case CMD_IP_FORWARDING_DISABLE_ERROR:
1054 case CMD_START_TETHERING_ERROR:
1055 case CMD_STOP_TETHERING_ERROR:
1056 case CMD_SET_DNS_FORWARDERS_ERROR:
markchien9b4d7572019-12-25 19:40:32 +08001057 mLastError = TetheringManager.TETHER_ERROR_MASTER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001058 transitionTo(mInitialState);
1059 break;
1060 default:
1061 return false;
1062 }
1063 return true;
1064 }
1065 }
1066
1067 // Handling errors in BaseServingState.enter() by transitioning is
1068 // problematic because transitioning during a multi-state jump yields
1069 // a Log.wtf(). Ultimately, there should be only one ServingState,
1070 // and forwarding and NAT rules should be handled by a coordinating
1071 // functional element outside of IpServer.
1072 class LocalHotspotState extends BaseServingState {
1073 @Override
1074 public void enter() {
1075 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001076 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001077 transitionTo(mInitialState);
1078 }
1079
1080 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1081 sendInterfaceState(STATE_LOCAL_ONLY);
1082 }
1083
1084 @Override
1085 public boolean processMessage(Message message) {
1086 if (super.processMessage(message)) return true;
1087
1088 logMessage(this, message.what);
1089 switch (message.what) {
1090 case CMD_TETHER_REQUESTED:
1091 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1092 break;
1093 case CMD_TETHER_CONNECTION_CHANGED:
1094 // Ignored in local hotspot state.
1095 break;
1096 default:
1097 return false;
1098 }
1099 return true;
1100 }
1101 }
1102
1103 // Handling errors in BaseServingState.enter() by transitioning is
1104 // problematic because transitioning during a multi-state jump yields
1105 // a Log.wtf(). Ultimately, there should be only one ServingState,
1106 // and forwarding and NAT rules should be handled by a coordinating
1107 // functional element outside of IpServer.
1108 class TetheredState extends BaseServingState {
1109 @Override
1110 public void enter() {
1111 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001112 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001113 transitionTo(mInitialState);
1114 }
1115
1116 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1117 sendInterfaceState(STATE_TETHERED);
1118 }
1119
1120 @Override
1121 public void exit() {
1122 cleanupUpstream();
1123 super.exit();
1124 }
1125
1126 private void cleanupUpstream() {
1127 if (mUpstreamIfaceSet == null) return;
1128
1129 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1130 mUpstreamIfaceSet = null;
Automerger Merge Workerf1194882020-02-25 04:04:44 +00001131 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001132 }
1133
1134 private void cleanupUpstreamInterface(String upstreamIface) {
1135 // Note that we don't care about errors here.
1136 // Sometimes interfaces are gone before we get
1137 // to remove their rules, which generates errors.
1138 // Just do the best we can.
1139 try {
markchien12c5bb82020-01-07 14:43:17 +08001140 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1141 } catch (RemoteException | ServiceSpecificException e) {
1142 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001143 }
1144 try {
markchien12c5bb82020-01-07 14:43:17 +08001145 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1146 } catch (RemoteException | ServiceSpecificException e) {
1147 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001148 }
1149 }
1150
1151 @Override
1152 public boolean processMessage(Message message) {
1153 if (super.processMessage(message)) return true;
1154
1155 logMessage(this, message.what);
1156 switch (message.what) {
1157 case CMD_TETHER_REQUESTED:
1158 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1159 break;
1160 case CMD_TETHER_CONNECTION_CHANGED:
1161 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1162 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1163 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1164 break;
1165 }
1166
1167 if (newUpstreamIfaceSet == null) {
1168 cleanupUpstream();
1169 break;
1170 }
1171
1172 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1173 cleanupUpstreamInterface(removed);
1174 }
1175
1176 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1177 // This makes the call to cleanupUpstream() in the error
1178 // path for any interface neatly cleanup all the interfaces.
1179 mUpstreamIfaceSet = newUpstreamIfaceSet;
1180
1181 for (String ifname : added) {
1182 try {
markchien12c5bb82020-01-07 14:43:17 +08001183 mNetd.tetherAddForward(mIfaceName, ifname);
1184 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1185 } catch (RemoteException | ServiceSpecificException e) {
1186 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001187 cleanupUpstream();
markchien9b4d7572019-12-25 19:40:32 +08001188 mLastError = TetheringManager.TETHER_ERROR_ENABLE_NAT_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001189 transitionTo(mInitialState);
1190 return true;
1191 }
1192 }
1193 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001194 case CMD_NEIGHBOR_EVENT:
1195 handleNeighborEvent((NeighborEvent) message.obj);
1196 break;
markchien74a4fa92019-09-09 20:50:49 +08001197 default:
1198 return false;
1199 }
1200 return true;
1201 }
1202
1203 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1204 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1205 if (mUpstreamIfaceSet != null && newIfaces != null) {
1206 return mUpstreamIfaceSet.equals(newIfaces);
1207 }
1208 return false;
1209 }
1210
1211 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1212 if (mUpstreamIfaceSet == null) return new HashSet<>();
1213
1214 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1215 removed.removeAll(newIfaces.ifnames);
1216 return removed;
1217 }
1218
1219 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1220 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1221 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1222 return added;
1223 }
1224 }
1225
1226 /**
1227 * This state is terminal for the per interface state machine. At this
1228 * point, the master state machine should have removed this interface
1229 * specific state machine from its list of possible recipients of
1230 * tethering requests. The state machine itself will hang around until
1231 * the garbage collector finds it.
1232 */
1233 class UnavailableState extends State {
1234 @Override
1235 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001236 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001237 sendInterfaceState(STATE_UNAVAILABLE);
1238 }
1239 }
1240
1241 // Accumulate routes representing "prefixes to be assigned to the local
1242 // interface", for subsequent modification of local_network routing.
1243 private static ArrayList<RouteInfo> getLocalRoutesFor(
1244 String ifname, HashSet<IpPrefix> prefixes) {
1245 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1246 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001247 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001248 }
1249 return localRoutes;
1250 }
1251
1252 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1253 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1254 final byte[] dnsBytes = localPrefix.getRawAddress();
1255 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1256 try {
1257 return Inet6Address.getByAddress(null, dnsBytes, 0);
1258 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001259 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001260 return null;
1261 }
1262 }
1263
1264 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1265 final byte random = (byte) (new Random()).nextInt();
1266 for (int value : excluded) {
1267 if (random == value) return dflt;
1268 }
1269 return random;
1270 }
1271}