blob: 780da775158ed0e54d8ce8e821d237e1a6494aec [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;
Xiao Ma06c8ba02020-04-06 11:24:48 +000043import android.net.dhcp.IDhcpEventCallbacks;
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
Xiao Ma06c8ba02020-04-06 11:24:48 +0000451 private class DhcpLeaseCallback extends IDhcpEventCallbacks.Stub {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900452 @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
Xiao Ma06c8ba02020-04-06 11:24:48 +0000485 public void onNewPrefixRequest(IpPrefix currentPrefix) {
486 //TODO: add specific implementation.
487 }
488
489 @Override
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900490 public int getInterfaceVersion() {
491 return this.VERSION;
492 }
493
494 @Override
495 public String getInterfaceHash() throws RemoteException {
496 return this.HASH;
497 }
498 }
499
markchien74a4fa92019-09-09 20:50:49 +0800500 private boolean startDhcp(Inet4Address addr, int prefixLen) {
501 if (mUsingLegacyDhcp) {
502 return true;
503 }
504 final DhcpServingParamsParcel params;
505 params = new DhcpServingParamsParcelExt()
506 .setDefaultRouters(addr)
507 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
508 .setDnsServers(addr)
509 .setServerAddr(new LinkAddress(addr, prefixLen))
510 .setMetered(true);
511 // TODO: also advertise link MTU
512
513 mDhcpServerStartIndex++;
514 mDeps.makeDhcpServer(
515 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
516 return true;
517 }
518
519 private void stopDhcp() {
520 // Make all previous start requests obsolete so servers are not started later
521 mDhcpServerStartIndex++;
522
523 if (mDhcpServer != null) {
524 try {
525 mDhcpServer.stop(new OnHandlerStatusCallback() {
526 @Override
527 public void callback(int statusCode) {
528 if (statusCode != STATUS_SUCCESS) {
529 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800530 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800531 // Not much more we can do here
532 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900533 mDhcpLeases.clear();
534 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800535 }
536 });
537 mDhcpServer = null;
538 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800539 mLog.e("Error stopping DHCP", e);
540 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800541 }
542 }
543 }
544
545 private boolean configureDhcp(boolean enable, Inet4Address addr, int prefixLen) {
546 if (enable) {
547 return startDhcp(addr, prefixLen);
548 } else {
549 stopDhcp();
550 return true;
551 }
552 }
553
554 private void stopIPv4() {
555 configureIPv4(false);
556 // NOTE: All of configureIPv4() will be refactored out of existence
557 // into calls to InterfaceController, shared with startIPv4().
558 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800559 mIpv4Address = null;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000560 mStaticIpv4ServerAddr = null;
561 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800562 }
563
markchien74a4fa92019-09-09 20:50:49 +0800564 private boolean configureIPv4(boolean enabled) {
565 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
566
567 // TODO: Replace this hard-coded information with dynamically selected
568 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800569 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800570 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800571 try {
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000572 if (mStaticIpv4ServerAddr != null) {
573 srvAddr = (Inet4Address) mStaticIpv4ServerAddr.getAddress();
574 prefixLen = mStaticIpv4ServerAddr.getPrefixLength();
575 } else if (mInterfaceType == TetheringManager.TETHERING_USB
Milim Lee45a971b2019-10-17 05:02:33 +0900576 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien12c5bb82020-01-07 14:43:17 +0800577 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
578 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800579 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800580 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
581 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800582 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800583 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
584 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900585 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
586 // TODO: randomize address for tethering too, similarly to wifi
587 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
588 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien12c5bb82020-01-07 14:43:17 +0800589 } else {
590 // BT configures the interface elsewhere: only start DHCP.
591 // TODO: make all tethering types behave the same way, and delete the bluetooth
592 // code that calls into NetworkManagementService directly.
593 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
594 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
595 return configureDhcp(enabled, srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
596 }
597 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
598 } catch (IllegalArgumentException e) {
599 mLog.e("Error selecting ipv4 address", e);
600 if (!enabled) stopDhcp();
601 return false;
markchien74a4fa92019-09-09 20:50:49 +0800602 }
603
markchien12c5bb82020-01-07 14:43:17 +0800604 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800605 if (mInterfaceType == TetheringManager.TETHERING_WIFI
606 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800607 // The WiFi stack has ownership of the interface up/down state.
608 // It is unclear whether the Bluetooth or USB stacks will manage their own
609 // state.
610 setIfaceUp = null;
611 } else {
612 setIfaceUp = enabled;
613 }
614 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
615 mLog.e("Error configuring interface");
616 if (!enabled) stopDhcp();
617 return false;
618 }
markchien74a4fa92019-09-09 20:50:49 +0800619
markchien74a4fa92019-09-09 20:50:49 +0800620 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800621 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
622 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800623 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800624 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800625 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800626 mLinkProperties.addRoute(route);
627 } else {
markchien12c5bb82020-01-07 14:43:17 +0800628 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800629 mLinkProperties.removeRoute(route);
630 }
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000631
632 return configureDhcp(enabled, srvAddr, prefixLen);
markchien74a4fa92019-09-09 20:50:49 +0800633 }
634
635 private String getRandomWifiIPv4Address() {
636 try {
637 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
638 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
639 return InetAddress.getByAddress(bytes).getHostAddress();
640 } catch (Exception e) {
641 return WIFI_HOST_IFACE_ADDR;
642 }
643 }
644
645 private boolean startIPv6() {
646 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
647 if (mInterfaceParams == null) {
648 mLog.e("Failed to find InterfaceParams");
649 stopIPv6();
650 return false;
651 }
652
653 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
654 if (!mRaDaemon.start()) {
655 stopIPv6();
656 return false;
657 }
658
659 return true;
660 }
661
662 private void stopIPv6() {
663 mInterfaceParams = null;
664 setRaParams(null);
665
666 if (mRaDaemon != null) {
667 mRaDaemon.stop();
668 mRaDaemon = null;
669 }
670 }
671
672 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
673 // LinkProperties. These have extraneous data filtered out and only the
674 // necessary prefixes included (per its prefix distribution policy).
675 //
676 // TODO: Evaluate using a data structure than is more directly suited to
677 // communicating only the relevant information.
678 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
679 if (mRaDaemon == null) return;
680
681 // Avoid unnecessary work on spurious updates.
682 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
683 return;
684 }
685
686 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900687 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800688
689 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900690 final String upstreamIface = v6only.getInterfaceName();
691
markchien74a4fa92019-09-09 20:50:49 +0800692 params = new RaParams();
Maciej Żenczykowskida0fb1b2020-02-19 01:24:39 -0800693 // We advertise an mtu lower by 16, which is the closest multiple of 8 >= 14,
694 // the ethernet header size. This makes kernel ebpf tethering offload happy.
695 // This hack should be reverted once we have the kernel fixed up.
696 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
697 // see RouterAdvertisementDaemon.java putMtu()
698 params.mtu = v6only.getMtu() - 16;
markchien74a4fa92019-09-09 20:50:49 +0800699 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
700
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900701 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800702
703 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
704 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
705
706 final IpPrefix prefix = new IpPrefix(
707 linkAddr.getAddress(), linkAddr.getPrefixLength());
708 params.prefixes.add(prefix);
709
710 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
711 if (dnsServer != null) {
712 params.dnses.add(dnsServer);
713 }
714 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900715
716 upstreamIfindex = mDeps.getIfindex(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800717 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900718
markchien74a4fa92019-09-09 20:50:49 +0800719 // If v6only is null, we pass in null to setRaParams(), which handles
720 // deprecation of any existing RA data.
721
722 setRaParams(params);
723 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900724
725 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
726 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800727 }
728
729 private void configureLocalIPv6Routes(
730 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
731 // [1] Remove the routes that are deprecated.
732 if (!deprecatedPrefixes.isEmpty()) {
733 final ArrayList<RouteInfo> toBeRemoved =
734 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800735 // Remove routes from local network.
736 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
737 mNetd, toBeRemoved);
738 if (removalFailures > 0) {
739 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
740 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800741 }
742
743 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
744 }
745
746 // [2] Add only the routes that have not previously been added.
747 if (newPrefixes != null && !newPrefixes.isEmpty()) {
748 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
749 if (mLastRaParams != null) {
750 addedPrefixes.removeAll(mLastRaParams.prefixes);
751 }
752
753 if (!addedPrefixes.isEmpty()) {
754 final ArrayList<RouteInfo> toBeAdded =
755 getLocalRoutesFor(mIfaceName, addedPrefixes);
756 try {
markchien12c5bb82020-01-07 14:43:17 +0800757 // It's safe to call networkAddInterface() even if
758 // the interface is already in the local_network.
759 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
760 try {
761 // Add routes from local network. Note that adding routes that
762 // already exist does not cause an error (EEXIST is silently ignored).
763 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
764 } catch (IllegalStateException e) {
765 mLog.e("Failed to add IPv6 routes to local table: " + e);
766 }
767 } catch (ServiceSpecificException | RemoteException e) {
768 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800769 }
770
771 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
772 }
773 }
774 }
775
776 private void configureLocalIPv6Dns(
777 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
778 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
779 if (mNetd == null) {
780 if (newDnses != null) newDnses.clear();
781 mLog.e("No netd service instance available; not setting local IPv6 addresses");
782 return;
783 }
784
785 // [1] Remove deprecated local DNS IP addresses.
786 if (!deprecatedDnses.isEmpty()) {
787 for (Inet6Address dns : deprecatedDnses) {
788 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
789 mLog.e("Failed to remove local dns IP " + dns);
790 }
791
792 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
793 }
794 }
795
796 // [2] Add only the local DNS IP addresses that have not previously been added.
797 if (newDnses != null && !newDnses.isEmpty()) {
798 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
799 if (mLastRaParams != null) {
800 addedDnses.removeAll(mLastRaParams.dnses);
801 }
802
803 for (Inet6Address dns : addedDnses) {
804 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
805 mLog.e("Failed to add local dns IP " + dns);
806 newDnses.remove(dns);
807 }
808
809 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
810 }
811 }
812
813 try {
814 mNetd.tetherApplyDnsInterfaces();
815 } catch (ServiceSpecificException | RemoteException e) {
816 mLog.e("Failed to update local DNS caching server");
817 if (newDnses != null) newDnses.clear();
818 }
819 }
820
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900821 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
822 try {
823 mNetd.tetherRuleAddDownstreamIpv6(mInterfaceParams.index, rule.upstreamIfindex,
824 rule.address.getAddress(), mInterfaceParams.macAddr.toByteArray(),
825 rule.dstMac.toByteArray());
826 mIpv6ForwardingRules.put(rule.address, rule);
827 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000828 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900829 }
830 }
831
832 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
833 try {
834 mNetd.tetherRuleRemoveDownstreamIpv6(rule.upstreamIfindex, rule.address.getAddress());
835 if (removeFromMap) {
836 mIpv6ForwardingRules.remove(rule.address);
837 }
838 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000839 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900840 }
841 }
842
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000843 private void clearIpv6ForwardingRules() {
844 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
845 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
846 }
847 mIpv6ForwardingRules.clear();
848 }
849
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900850 // Convenience method to replace a rule with the same rule on a new upstream interface.
851 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
852 // Relies on the fact that rules are in a map indexed by IP address.
853 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
854 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
855 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
856 }
857
858 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
859 // changes or if a neighbor event is received.
860 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
861 NeighborEvent e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000862 // If we no longer have an upstream, clear forwarding rules and do nothing else.
863 if (upstreamIfindex == 0) {
864 clearIpv6ForwardingRules();
865 return;
866 }
867
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900868 // If the upstream interface has changed, remove all rules and re-add them with the new
869 // upstream interface.
870 if (prevUpstreamIfindex != upstreamIfindex) {
871 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
872 updateIpv6ForwardingRule(rule, upstreamIfindex);
873 }
874 }
875
876 // If we're here to process a NeighborEvent, do so now.
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000877 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900878 if (e == null) return;
879 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
880 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
881 return;
882 }
883
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000884 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900885 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr,
886 e.macAddr);
887 if (e.isValid()) {
888 addIpv6ForwardingRule(rule);
889 } else {
890 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
891 }
892 }
893
894 private void handleNeighborEvent(NeighborEvent e) {
895 if (mInterfaceParams != null
896 && mInterfaceParams.index == e.ifindex
897 && mInterfaceParams.hasMacAddress) {
898 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
899 }
900 }
901
markchien74a4fa92019-09-09 20:50:49 +0800902 private byte getHopLimit(String upstreamIface) {
903 try {
904 int upstreamHopLimit = Integer.parseUnsignedInt(
905 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
906 // Add one hop to account for this forwarding device
907 upstreamHopLimit++;
908 // Cap the hop limit to 255.
909 return (byte) Integer.min(upstreamHopLimit, 255);
910 } catch (Exception e) {
911 mLog.e("Failed to find upstream interface hop limit", e);
912 }
913 return RaParams.DEFAULT_HOPLIMIT;
914 }
915
916 private void setRaParams(RaParams newParams) {
917 if (mRaDaemon != null) {
918 final RaParams deprecatedParams =
919 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
920
921 configureLocalIPv6Routes(deprecatedParams.prefixes,
922 (newParams != null) ? newParams.prefixes : null);
923
924 configureLocalIPv6Dns(deprecatedParams.dnses,
925 (newParams != null) ? newParams.dnses : null);
926
927 mRaDaemon.buildNewRa(deprecatedParams, newParams);
928 }
929
930 mLastRaParams = newParams;
931 }
932
933 private void logMessage(State state, int what) {
934 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
935 }
936
937 private void sendInterfaceState(int newInterfaceState) {
938 mServingMode = newInterfaceState;
939 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
940 sendLinkProperties();
941 }
942
943 private void sendLinkProperties() {
944 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
945 }
946
947 private void resetLinkProperties() {
948 mLinkProperties.clear();
949 mLinkProperties.setInterfaceName(mIfaceName);
950 }
951
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000952 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
953 if (request == null) return;
954
955 mStaticIpv4ServerAddr = request.localIPv4Address;
956 mStaticIpv4ClientAddr = request.staticClientAddress;
957 }
958
markchien74a4fa92019-09-09 20:50:49 +0800959 class InitialState extends State {
960 @Override
961 public void enter() {
962 sendInterfaceState(STATE_AVAILABLE);
963 }
964
965 @Override
966 public boolean processMessage(Message message) {
967 logMessage(this, message.what);
968 switch (message.what) {
969 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800970 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800971 switch (message.arg1) {
972 case STATE_LOCAL_ONLY:
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000973 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +0800974 transitionTo(mLocalHotspotState);
975 break;
976 case STATE_TETHERED:
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000977 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +0800978 transitionTo(mTetheredState);
979 break;
980 default:
981 mLog.e("Invalid tethering interface serving state specified.");
982 }
983 break;
984 case CMD_INTERFACE_DOWN:
985 transitionTo(mUnavailableState);
986 break;
987 case CMD_IPV6_TETHER_UPDATE:
988 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
989 break;
990 default:
991 return NOT_HANDLED;
992 }
993 return HANDLED;
994 }
995 }
996
997 class BaseServingState extends State {
998 @Override
999 public void enter() {
1000 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001001 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001002 return;
1003 }
1004
1005 try {
markchien12c5bb82020-01-07 14:43:17 +08001006 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
1007 mIpv4Address.getPrefixLength());
1008 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchien6c2b7cc2020-02-15 11:35:00 +08001009 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
markchien74a4fa92019-09-09 20:50:49 +08001010 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +08001011 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001012 return;
1013 }
1014
1015 if (!startIPv6()) {
1016 mLog.e("Failed to startIPv6");
1017 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1018 return;
1019 }
1020 }
1021
1022 @Override
1023 public void exit() {
1024 // Note that at this point, we're leaving the tethered state. We can fail any
1025 // of these operations, but it doesn't really change that we have to try them
1026 // all in sequence.
1027 stopIPv6();
1028
1029 try {
markchien12c5bb82020-01-07 14:43:17 +08001030 NetdUtils.untetherInterface(mNetd, mIfaceName);
1031 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001032 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001033 mLog.e("Failed to untether interface: " + e);
1034 }
1035
1036 stopIPv4();
1037
1038 resetLinkProperties();
1039 }
1040
1041 @Override
1042 public boolean processMessage(Message message) {
1043 logMessage(this, message.what);
1044 switch (message.what) {
1045 case CMD_TETHER_UNREQUESTED:
1046 transitionTo(mInitialState);
1047 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1048 break;
1049 case CMD_INTERFACE_DOWN:
1050 transitionTo(mUnavailableState);
1051 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1052 break;
1053 case CMD_IPV6_TETHER_UPDATE:
1054 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1055 sendLinkProperties();
1056 break;
1057 case CMD_IP_FORWARDING_ENABLE_ERROR:
1058 case CMD_IP_FORWARDING_DISABLE_ERROR:
1059 case CMD_START_TETHERING_ERROR:
1060 case CMD_STOP_TETHERING_ERROR:
1061 case CMD_SET_DNS_FORWARDERS_ERROR:
markchienf1332572020-03-19 13:37:43 +08001062 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001063 transitionTo(mInitialState);
1064 break;
1065 default:
1066 return false;
1067 }
1068 return true;
1069 }
1070 }
1071
1072 // Handling errors in BaseServingState.enter() by transitioning is
1073 // problematic because transitioning during a multi-state jump yields
1074 // a Log.wtf(). Ultimately, there should be only one ServingState,
1075 // and forwarding and NAT rules should be handled by a coordinating
1076 // functional element outside of IpServer.
1077 class LocalHotspotState extends BaseServingState {
1078 @Override
1079 public void enter() {
1080 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001081 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001082 transitionTo(mInitialState);
1083 }
1084
1085 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1086 sendInterfaceState(STATE_LOCAL_ONLY);
1087 }
1088
1089 @Override
1090 public boolean processMessage(Message message) {
1091 if (super.processMessage(message)) return true;
1092
1093 logMessage(this, message.what);
1094 switch (message.what) {
1095 case CMD_TETHER_REQUESTED:
1096 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1097 break;
1098 case CMD_TETHER_CONNECTION_CHANGED:
1099 // Ignored in local hotspot state.
1100 break;
1101 default:
1102 return false;
1103 }
1104 return true;
1105 }
1106 }
1107
1108 // Handling errors in BaseServingState.enter() by transitioning is
1109 // problematic because transitioning during a multi-state jump yields
1110 // a Log.wtf(). Ultimately, there should be only one ServingState,
1111 // and forwarding and NAT rules should be handled by a coordinating
1112 // functional element outside of IpServer.
1113 class TetheredState extends BaseServingState {
1114 @Override
1115 public void enter() {
1116 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001117 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001118 transitionTo(mInitialState);
1119 }
1120
1121 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1122 sendInterfaceState(STATE_TETHERED);
1123 }
1124
1125 @Override
1126 public void exit() {
1127 cleanupUpstream();
1128 super.exit();
1129 }
1130
1131 private void cleanupUpstream() {
1132 if (mUpstreamIfaceSet == null) return;
1133
1134 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1135 mUpstreamIfaceSet = null;
Automerger Merge Workerf1194882020-02-25 04:04:44 +00001136 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001137 }
1138
1139 private void cleanupUpstreamInterface(String upstreamIface) {
1140 // Note that we don't care about errors here.
1141 // Sometimes interfaces are gone before we get
1142 // to remove their rules, which generates errors.
1143 // Just do the best we can.
1144 try {
markchien12c5bb82020-01-07 14:43:17 +08001145 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1146 } catch (RemoteException | ServiceSpecificException e) {
1147 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001148 }
1149 try {
markchien12c5bb82020-01-07 14:43:17 +08001150 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1151 } catch (RemoteException | ServiceSpecificException e) {
1152 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001153 }
1154 }
1155
1156 @Override
1157 public boolean processMessage(Message message) {
1158 if (super.processMessage(message)) return true;
1159
1160 logMessage(this, message.what);
1161 switch (message.what) {
1162 case CMD_TETHER_REQUESTED:
1163 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1164 break;
1165 case CMD_TETHER_CONNECTION_CHANGED:
1166 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1167 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1168 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1169 break;
1170 }
1171
1172 if (newUpstreamIfaceSet == null) {
1173 cleanupUpstream();
1174 break;
1175 }
1176
1177 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1178 cleanupUpstreamInterface(removed);
1179 }
1180
1181 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1182 // This makes the call to cleanupUpstream() in the error
1183 // path for any interface neatly cleanup all the interfaces.
1184 mUpstreamIfaceSet = newUpstreamIfaceSet;
1185
1186 for (String ifname : added) {
1187 try {
markchien12c5bb82020-01-07 14:43:17 +08001188 mNetd.tetherAddForward(mIfaceName, ifname);
1189 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1190 } catch (RemoteException | ServiceSpecificException e) {
1191 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001192 cleanupUpstream();
markchienf1332572020-03-19 13:37:43 +08001193 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001194 transitionTo(mInitialState);
1195 return true;
1196 }
1197 }
1198 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001199 case CMD_NEIGHBOR_EVENT:
1200 handleNeighborEvent((NeighborEvent) message.obj);
1201 break;
markchien74a4fa92019-09-09 20:50:49 +08001202 default:
1203 return false;
1204 }
1205 return true;
1206 }
1207
1208 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1209 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1210 if (mUpstreamIfaceSet != null && newIfaces != null) {
1211 return mUpstreamIfaceSet.equals(newIfaces);
1212 }
1213 return false;
1214 }
1215
1216 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1217 if (mUpstreamIfaceSet == null) return new HashSet<>();
1218
1219 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1220 removed.removeAll(newIfaces.ifnames);
1221 return removed;
1222 }
1223
1224 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1225 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1226 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1227 return added;
1228 }
1229 }
1230
1231 /**
1232 * This state is terminal for the per interface state machine. At this
1233 * point, the master state machine should have removed this interface
1234 * specific state machine from its list of possible recipients of
1235 * tethering requests. The state machine itself will hang around until
1236 * the garbage collector finds it.
1237 */
1238 class UnavailableState extends State {
1239 @Override
1240 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001241 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001242 sendInterfaceState(STATE_UNAVAILABLE);
1243 }
1244 }
1245
1246 // Accumulate routes representing "prefixes to be assigned to the local
1247 // interface", for subsequent modification of local_network routing.
1248 private static ArrayList<RouteInfo> getLocalRoutesFor(
1249 String ifname, HashSet<IpPrefix> prefixes) {
1250 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1251 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001252 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001253 }
1254 return localRoutes;
1255 }
1256
1257 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1258 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1259 final byte[] dnsBytes = localPrefix.getRawAddress();
1260 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1261 try {
1262 return Inet6Address.getByAddress(null, dnsBytes, 0);
1263 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001264 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001265 return null;
1266 }
1267 }
1268
1269 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1270 final byte random = (byte) (new Random()).nextInt();
1271 for (int value : excluded) {
1272 if (random == value) return dflt;
1273 }
1274 return random;
1275 }
1276}