blob: cf57e2fc2cda117534c3a79a932556eebdfc4c9c [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;
Lorenzo Colittie6107d22020-04-06 09:19:57 +000036import android.net.TetherOffloadRuleParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090037import android.net.TetheredClient;
markchien9b4d7572019-12-25 19:40:32 +080038import android.net.TetheringManager;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +000039import android.net.TetheringRequestParcel;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090040import android.net.dhcp.DhcpLeaseParcelable;
markchien74a4fa92019-09-09 20:50:49 +080041import android.net.dhcp.DhcpServerCallbacks;
42import android.net.dhcp.DhcpServingParamsParcel;
43import android.net.dhcp.DhcpServingParamsParcelExt;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090044import android.net.dhcp.IDhcpLeaseCallbacks;
markchien74a4fa92019-09-09 20:50:49 +080045import android.net.dhcp.IDhcpServer;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090046import android.net.ip.IpNeighborMonitor.NeighborEvent;
markchien74a4fa92019-09-09 20:50:49 +080047import android.net.ip.RouterAdvertisementDaemon.RaParams;
markchien12c5bb82020-01-07 14:43:17 +080048import android.net.shared.NetdUtils;
49import android.net.shared.RouteUtils;
markchien74a4fa92019-09-09 20:50:49 +080050import android.net.util.InterfaceParams;
51import android.net.util.InterfaceSet;
markchien74a4fa92019-09-09 20:50:49 +080052import android.net.util.SharedLog;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090053import android.os.Handler;
markchien74a4fa92019-09-09 20:50:49 +080054import android.os.Looper;
55import android.os.Message;
56import android.os.RemoteException;
57import android.os.ServiceSpecificException;
58import android.util.Log;
markchien74a4fa92019-09-09 20:50:49 +080059import android.util.SparseArray;
60
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090061import androidx.annotation.NonNull;
62
markchien74a4fa92019-09-09 20:50:49 +080063import com.android.internal.util.MessageUtils;
markchien74a4fa92019-09-09 20:50:49 +080064import com.android.internal.util.State;
65import com.android.internal.util.StateMachine;
66
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090067import java.io.IOException;
markchien74a4fa92019-09-09 20:50:49 +080068import java.net.Inet4Address;
69import java.net.Inet6Address;
70import java.net.InetAddress;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090071import java.net.NetworkInterface;
markchien74a4fa92019-09-09 20:50:49 +080072import java.net.UnknownHostException;
73import java.util.ArrayList;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090074import java.util.Arrays;
75import java.util.Collections;
markchien74a4fa92019-09-09 20:50:49 +080076import java.util.HashSet;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +090077import java.util.LinkedHashMap;
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +090078import java.util.List;
markchien74a4fa92019-09-09 20:50:49 +080079import java.util.Objects;
80import java.util.Random;
81import java.util.Set;
82
83/**
84 * Provides the interface to IP-layer serving functionality for a given network
85 * interface, e.g. for tethering or "local-only hotspot" mode.
86 *
87 * @hide
88 */
89public class IpServer extends StateMachine {
90 public static final int STATE_UNAVAILABLE = 0;
91 public static final int STATE_AVAILABLE = 1;
92 public static final int STATE_TETHERED = 2;
93 public static final int STATE_LOCAL_ONLY = 3;
94
95 /** Get string name of |state|.*/
96 public static String getStateString(int state) {
97 switch (state) {
98 case STATE_UNAVAILABLE: return "UNAVAILABLE";
99 case STATE_AVAILABLE: return "AVAILABLE";
100 case STATE_TETHERED: return "TETHERED";
101 case STATE_LOCAL_ONLY: return "LOCAL_ONLY";
102 }
103 return "UNKNOWN: " + state;
104 }
105
106 private static final byte DOUG_ADAMS = (byte) 42;
107
108 private static final String USB_NEAR_IFACE_ADDR = "192.168.42.129";
109 private static final int USB_PREFIX_LENGTH = 24;
110 private static final String WIFI_HOST_IFACE_ADDR = "192.168.43.1";
111 private static final int WIFI_HOST_IFACE_PREFIX_LENGTH = 24;
112 private static final String WIFI_P2P_IFACE_ADDR = "192.168.49.1";
113 private static final int WIFI_P2P_IFACE_PREFIX_LENGTH = 24;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900114 private static final String ETHERNET_IFACE_ADDR = "192.168.50.1";
115 private static final int ETHERNET_IFACE_PREFIX_LENGTH = 24;
markchien74a4fa92019-09-09 20:50:49 +0800116
117 // TODO: have PanService use some visible version of this constant
118 private static final String BLUETOOTH_IFACE_ADDR = "192.168.44.1";
119 private static final int BLUETOOTH_DHCP_PREFIX_LENGTH = 24;
120
121 // TODO: have this configurable
122 private static final int DHCP_LEASE_TIME_SECS = 3600;
123
124 private static final String TAG = "IpServer";
125 private static final boolean DBG = false;
126 private static final boolean VDBG = false;
127 private static final Class[] sMessageClasses = {
128 IpServer.class
129 };
130 private static final SparseArray<String> sMagicDecoderRing =
131 MessageUtils.findMessageNames(sMessageClasses);
132
133 /** IpServer callback. */
134 public static class Callback {
135 /**
136 * Notify that |who| has changed its tethering state.
137 *
138 * @param who the calling instance of IpServer
139 * @param state one of STATE_*
markchien9b4d7572019-12-25 19:40:32 +0800140 * @param lastError one of TetheringManager.TETHER_ERROR_*
markchien74a4fa92019-09-09 20:50:49 +0800141 */
markchien9d353822019-12-16 20:15:20 +0800142 public void updateInterfaceState(IpServer who, int state, int lastError) { }
markchien74a4fa92019-09-09 20:50:49 +0800143
144 /**
145 * Notify that |who| has new LinkProperties.
146 *
147 * @param who the calling instance of IpServer
148 * @param newLp the new LinkProperties to report
149 */
markchien9d353822019-12-16 20:15:20 +0800150 public void updateLinkProperties(IpServer who, LinkProperties newLp) { }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900151
152 /**
153 * Notify that the DHCP leases changed in one of the IpServers.
154 */
155 public void dhcpLeasesChanged() { }
markchien74a4fa92019-09-09 20:50:49 +0800156 }
157
158 /** Capture IpServer dependencies, for injection. */
markchien9d353822019-12-16 20:15:20 +0800159 public abstract static class Dependencies {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900160 /** Create an IpNeighborMonitor to be used by this IpServer */
161 public IpNeighborMonitor getIpNeighborMonitor(Handler handler, SharedLog log,
162 IpNeighborMonitor.NeighborEventConsumer consumer) {
163 return new IpNeighborMonitor(handler, log, consumer);
164 }
165
markchien74a4fa92019-09-09 20:50:49 +0800166 /** Create a RouterAdvertisementDaemon instance to be used by IpServer.*/
167 public RouterAdvertisementDaemon getRouterAdvertisementDaemon(InterfaceParams ifParams) {
168 return new RouterAdvertisementDaemon(ifParams);
169 }
170
171 /** Get |ifName|'s interface information.*/
172 public InterfaceParams getInterfaceParams(String ifName) {
173 return InterfaceParams.getByName(ifName);
174 }
175
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900176 /** Get |ifName|'s interface index. */
177 public int getIfindex(String ifName) {
178 try {
179 return NetworkInterface.getByName(ifName).getIndex();
180 } catch (IOException | NullPointerException e) {
181 Log.e(TAG, "Can't determine interface index for interface " + ifName);
182 return 0;
183 }
184 }
markchien9d353822019-12-16 20:15:20 +0800185 /** Create a DhcpServer instance to be used by IpServer. */
186 public abstract void makeDhcpServer(String ifName, DhcpServingParamsParcel params,
187 DhcpServerCallbacks cb);
markchien74a4fa92019-09-09 20:50:49 +0800188 }
189
markchien74a4fa92019-09-09 20:50:49 +0800190 // request from the user that it wants to tether
markchien6cf0e552019-12-06 15:24:53 +0800191 public static final int CMD_TETHER_REQUESTED = BASE_IPSERVER + 1;
markchien74a4fa92019-09-09 20:50:49 +0800192 // request from the user that it wants to untether
markchien6cf0e552019-12-06 15:24:53 +0800193 public static final int CMD_TETHER_UNREQUESTED = BASE_IPSERVER + 2;
markchien74a4fa92019-09-09 20:50:49 +0800194 // notification that this interface is down
markchien6cf0e552019-12-06 15:24:53 +0800195 public static final int CMD_INTERFACE_DOWN = BASE_IPSERVER + 3;
markchien74a4fa92019-09-09 20:50:49 +0800196 // notification from the master SM that it had trouble enabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800197 public static final int CMD_IP_FORWARDING_ENABLE_ERROR = BASE_IPSERVER + 4;
markchien74a4fa92019-09-09 20:50:49 +0800198 // notification from the master SM that it had trouble disabling IP Forwarding
markchien6cf0e552019-12-06 15:24:53 +0800199 public static final int CMD_IP_FORWARDING_DISABLE_ERROR = BASE_IPSERVER + 5;
markchien74a4fa92019-09-09 20:50:49 +0800200 // notification from the master SM that it had trouble starting tethering
markchien6cf0e552019-12-06 15:24:53 +0800201 public static final int CMD_START_TETHERING_ERROR = BASE_IPSERVER + 6;
markchien74a4fa92019-09-09 20:50:49 +0800202 // notification from the master SM that it had trouble stopping tethering
markchien6cf0e552019-12-06 15:24:53 +0800203 public static final int CMD_STOP_TETHERING_ERROR = BASE_IPSERVER + 7;
markchien74a4fa92019-09-09 20:50:49 +0800204 // notification from the master SM that it had trouble setting the DNS forwarders
markchien6cf0e552019-12-06 15:24:53 +0800205 public static final int CMD_SET_DNS_FORWARDERS_ERROR = BASE_IPSERVER + 8;
markchien74a4fa92019-09-09 20:50:49 +0800206 // the upstream connection has changed
markchien6cf0e552019-12-06 15:24:53 +0800207 public static final int CMD_TETHER_CONNECTION_CHANGED = BASE_IPSERVER + 9;
markchien74a4fa92019-09-09 20:50:49 +0800208 // new IPv6 tethering parameters need to be processed
markchien6cf0e552019-12-06 15:24:53 +0800209 public static final int CMD_IPV6_TETHER_UPDATE = BASE_IPSERVER + 10;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900210 // new neighbor cache entry on our interface
211 public static final int CMD_NEIGHBOR_EVENT = BASE_IPSERVER + 11;
markchien74a4fa92019-09-09 20:50:49 +0800212
213 private final State mInitialState;
214 private final State mLocalHotspotState;
215 private final State mTetheredState;
216 private final State mUnavailableState;
217
218 private final SharedLog mLog;
markchien74a4fa92019-09-09 20:50:49 +0800219 private final INetd mNetd;
markchien74a4fa92019-09-09 20:50:49 +0800220 private final Callback mCallback;
221 private final InterfaceController mInterfaceCtrl;
222
223 private final String mIfaceName;
224 private final int mInterfaceType;
225 private final LinkProperties mLinkProperties;
226 private final boolean mUsingLegacyDhcp;
227
228 private final Dependencies mDeps;
229
230 private int mLastError;
231 private int mServingMode;
232 private InterfaceSet mUpstreamIfaceSet; // may change over time
233 private InterfaceParams mInterfaceParams;
234 // TODO: De-duplicate this with mLinkProperties above. Currently, these link
235 // properties are those selected by the IPv6TetheringCoordinator and relayed
236 // to us. By comparison, mLinkProperties contains the addresses and directly
237 // connected routes that have been formed from these properties iff. we have
238 // succeeded in configuring them and are able to announce them within Router
239 // Advertisements (otherwise, we do not add them to mLinkProperties at all).
240 private LinkProperties mLastIPv6LinkProperties;
241 private RouterAdvertisementDaemon mRaDaemon;
242
243 // To be accessed only on the handler thread
244 private int mDhcpServerStartIndex = 0;
245 private IDhcpServer mDhcpServer;
246 private RaParams mLastRaParams;
markchien12c5bb82020-01-07 14:43:17 +0800247 private LinkAddress mIpv4Address;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000248
249 private LinkAddress mStaticIpv4ServerAddr;
250 private LinkAddress mStaticIpv4ClientAddr;
251
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900252 @NonNull
253 private List<TetheredClient> mDhcpLeases = Collections.emptyList();
markchien74a4fa92019-09-09 20:50:49 +0800254
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900255 private int mLastIPv6UpstreamIfindex = 0;
256
257 private class MyNeighborEventConsumer implements IpNeighborMonitor.NeighborEventConsumer {
258 public void accept(NeighborEvent e) {
259 sendMessage(CMD_NEIGHBOR_EVENT, e);
260 }
261 }
262
263 static class Ipv6ForwardingRule {
264 public final int upstreamIfindex;
265 public final int downstreamIfindex;
266 public final Inet6Address address;
267 public final MacAddress srcMac;
268 public final MacAddress dstMac;
269
270 Ipv6ForwardingRule(int upstreamIfindex, int downstreamIfIndex, Inet6Address address,
271 MacAddress srcMac, MacAddress dstMac) {
272 this.upstreamIfindex = upstreamIfindex;
273 this.downstreamIfindex = downstreamIfIndex;
274 this.address = address;
275 this.srcMac = srcMac;
276 this.dstMac = dstMac;
277 }
278
279 public Ipv6ForwardingRule onNewUpstream(int newUpstreamIfindex) {
280 return new Ipv6ForwardingRule(newUpstreamIfindex, downstreamIfindex, address, srcMac,
281 dstMac);
282 }
Lorenzo Colittie6107d22020-04-06 09:19:57 +0000283
284 // Don't manipulate TetherOffloadRuleParcel directly because implementing onNewUpstream()
285 // would be error-prone due to generated stable AIDL classes not having a copy constructor.
286 public TetherOffloadRuleParcel toTetherOffloadRuleParcel() {
287 final TetherOffloadRuleParcel parcel = new TetherOffloadRuleParcel();
288 parcel.inputInterfaceIndex = upstreamIfindex;
289 parcel.outputInterfaceIndex = downstreamIfindex;
290 parcel.destination = address.getAddress();
291 parcel.prefixLength = 128;
292 parcel.srcL2Address = srcMac.toByteArray();
293 parcel.dstL2Address = dstMac.toByteArray();
294 return parcel;
295 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900296 }
297 private final LinkedHashMap<Inet6Address, Ipv6ForwardingRule> mIpv6ForwardingRules =
298 new LinkedHashMap<>();
299
300 private final IpNeighborMonitor mIpNeighborMonitor;
301
markchien74a4fa92019-09-09 20:50:49 +0800302 public IpServer(
303 String ifaceName, Looper looper, int interfaceType, SharedLog log,
junyulai5864a3f2019-12-03 14:34:13 +0800304 INetd netd, Callback callback, boolean usingLegacyDhcp, Dependencies deps) {
markchien74a4fa92019-09-09 20:50:49 +0800305 super(ifaceName, looper);
306 mLog = log.forSubComponent(ifaceName);
markchien12c5bb82020-01-07 14:43:17 +0800307 mNetd = netd;
markchien74a4fa92019-09-09 20:50:49 +0800308 mCallback = callback;
309 mInterfaceCtrl = new InterfaceController(ifaceName, mNetd, mLog);
310 mIfaceName = ifaceName;
311 mInterfaceType = interfaceType;
312 mLinkProperties = new LinkProperties();
313 mUsingLegacyDhcp = usingLegacyDhcp;
314 mDeps = deps;
315 resetLinkProperties();
markchien9b4d7572019-12-25 19:40:32 +0800316 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800317 mServingMode = STATE_AVAILABLE;
318
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900319 mIpNeighborMonitor = mDeps.getIpNeighborMonitor(getHandler(), mLog,
320 new MyNeighborEventConsumer());
321 if (!mIpNeighborMonitor.start()) {
322 mLog.e("Failed to create IpNeighborMonitor on " + mIfaceName);
323 }
324
markchien74a4fa92019-09-09 20:50:49 +0800325 mInitialState = new InitialState();
326 mLocalHotspotState = new LocalHotspotState();
327 mTetheredState = new TetheredState();
328 mUnavailableState = new UnavailableState();
329 addState(mInitialState);
330 addState(mLocalHotspotState);
331 addState(mTetheredState);
332 addState(mUnavailableState);
333
334 setInitialState(mInitialState);
335 }
336
337 /** Interface name which IpServer served.*/
338 public String interfaceName() {
339 return mIfaceName;
340 }
341
342 /**
markchien9b4d7572019-12-25 19:40:32 +0800343 * Tethering downstream type. It would be one of TetheringManager#TETHERING_*.
markchien74a4fa92019-09-09 20:50:49 +0800344 */
345 public int interfaceType() {
346 return mInterfaceType;
347 }
348
349 /** Last error from this IpServer. */
350 public int lastError() {
351 return mLastError;
352 }
353
354 /** Serving mode is the current state of IpServer state machine. */
355 public int servingMode() {
356 return mServingMode;
357 }
358
359 /** The properties of the network link which IpServer is serving. */
360 public LinkProperties linkProperties() {
361 return new LinkProperties(mLinkProperties);
362 }
363
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900364 /**
365 * Get the latest list of DHCP leases that was reported. Must be called on the IpServer looper
366 * thread.
367 */
368 public List<TetheredClient> getAllLeases() {
369 return Collections.unmodifiableList(mDhcpLeases);
370 }
371
markchien74a4fa92019-09-09 20:50:49 +0800372 /** Stop this IpServer. After this is called this IpServer should not be used any more. */
373 public void stop() {
374 sendMessage(CMD_INTERFACE_DOWN);
375 }
376
377 /**
378 * Tethering is canceled. IpServer state machine will be available and wait for
379 * next tethering request.
380 */
381 public void unwanted() {
382 sendMessage(CMD_TETHER_UNREQUESTED);
383 }
384
385 /** Internals. */
386
387 private boolean startIPv4() {
388 return configureIPv4(true);
389 }
390
391 /**
392 * Convenience wrapper around INetworkStackStatusCallback to run callbacks on the IpServer
393 * handler.
394 *
395 * <p>Different instances of this class can be created for each call to IDhcpServer methods,
396 * with different implementations of the callback, to differentiate handling of success/error in
397 * each call.
398 */
399 private abstract class OnHandlerStatusCallback extends INetworkStackStatusCallback.Stub {
400 @Override
401 public void onStatusAvailable(int statusCode) {
402 getHandler().post(() -> callback(statusCode));
403 }
404
405 public abstract void callback(int statusCode);
406
407 @Override
408 public int getInterfaceVersion() {
409 return this.VERSION;
410 }
Paul Trautrimbbfcd542020-01-23 14:55:57 +0900411
412 @Override
413 public String getInterfaceHash() {
414 return this.HASH;
415 }
markchien74a4fa92019-09-09 20:50:49 +0800416 }
417
418 private class DhcpServerCallbacksImpl extends DhcpServerCallbacks {
419 private final int mStartIndex;
420
421 private DhcpServerCallbacksImpl(int startIndex) {
422 mStartIndex = startIndex;
423 }
424
425 @Override
426 public void onDhcpServerCreated(int statusCode, IDhcpServer server) throws RemoteException {
427 getHandler().post(() -> {
428 // We are on the handler thread: mDhcpServerStartIndex can be read safely.
429 if (mStartIndex != mDhcpServerStartIndex) {
430 // This start request is obsolete. When the |server| binder token goes out of
431 // scope, the garbage collector will finalize it, which causes the network stack
432 // process garbage collector to collect the server itself.
433 return;
434 }
435
436 if (statusCode != STATUS_SUCCESS) {
437 mLog.e("Error obtaining DHCP server: " + statusCode);
438 handleError();
439 return;
440 }
441
442 mDhcpServer = server;
443 try {
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900444 mDhcpServer.startWithCallbacks(new OnHandlerStatusCallback() {
markchien74a4fa92019-09-09 20:50:49 +0800445 @Override
446 public void callback(int startStatusCode) {
447 if (startStatusCode != STATUS_SUCCESS) {
448 mLog.e("Error starting DHCP server: " + startStatusCode);
449 handleError();
450 }
451 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900452 }, new DhcpLeaseCallback());
markchien74a4fa92019-09-09 20:50:49 +0800453 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800454 throw new IllegalStateException(e);
markchien74a4fa92019-09-09 20:50:49 +0800455 }
456 });
457 }
458
459 private void handleError() {
markchien9b4d7572019-12-25 19:40:32 +0800460 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800461 transitionTo(mInitialState);
462 }
463 }
464
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900465 private class DhcpLeaseCallback extends IDhcpLeaseCallbacks.Stub {
466 @Override
467 public void onLeasesChanged(List<DhcpLeaseParcelable> leaseParcelables) {
468 final ArrayList<TetheredClient> leases = new ArrayList<>();
469 for (DhcpLeaseParcelable lease : leaseParcelables) {
470 final LinkAddress address = new LinkAddress(
Automerger Merge Worker0010ca02020-03-16 04:06:46 +0000471 intToInet4AddressHTH(lease.netAddr), lease.prefixLength,
472 0 /* flags */, RT_SCOPE_UNIVERSE /* as per RFC6724#3.2 */,
473 lease.expTime /* deprecationTime */, lease.expTime /* expirationTime */);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900474
475 final MacAddress macAddress;
476 try {
477 macAddress = MacAddress.fromBytes(lease.hwAddr);
478 } catch (IllegalArgumentException e) {
479 Log.wtf(TAG, "Invalid address received from DhcpServer: "
480 + Arrays.toString(lease.hwAddr));
481 return;
482 }
483
484 final TetheredClient.AddressInfo addressInfo = new TetheredClient.AddressInfo(
Automerger Merge Worker0010ca02020-03-16 04:06:46 +0000485 address, lease.hostname);
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900486 leases.add(new TetheredClient(
487 macAddress,
488 Collections.singletonList(addressInfo),
489 mInterfaceType));
490 }
491
492 getHandler().post(() -> {
493 mDhcpLeases = leases;
494 mCallback.dhcpLeasesChanged();
495 });
496 }
497
498 @Override
499 public int getInterfaceVersion() {
500 return this.VERSION;
501 }
502
503 @Override
504 public String getInterfaceHash() throws RemoteException {
505 return this.HASH;
506 }
507 }
508
markchien74a4fa92019-09-09 20:50:49 +0800509 private boolean startDhcp(Inet4Address addr, int prefixLen) {
510 if (mUsingLegacyDhcp) {
511 return true;
512 }
513 final DhcpServingParamsParcel params;
514 params = new DhcpServingParamsParcelExt()
515 .setDefaultRouters(addr)
516 .setDhcpLeaseTimeSecs(DHCP_LEASE_TIME_SECS)
517 .setDnsServers(addr)
518 .setServerAddr(new LinkAddress(addr, prefixLen))
519 .setMetered(true);
520 // TODO: also advertise link MTU
521
522 mDhcpServerStartIndex++;
523 mDeps.makeDhcpServer(
524 mIfaceName, params, new DhcpServerCallbacksImpl(mDhcpServerStartIndex));
525 return true;
526 }
527
528 private void stopDhcp() {
529 // Make all previous start requests obsolete so servers are not started later
530 mDhcpServerStartIndex++;
531
532 if (mDhcpServer != null) {
533 try {
534 mDhcpServer.stop(new OnHandlerStatusCallback() {
535 @Override
536 public void callback(int statusCode) {
537 if (statusCode != STATUS_SUCCESS) {
538 mLog.e("Error stopping DHCP server: " + statusCode);
markchien9b4d7572019-12-25 19:40:32 +0800539 mLastError = TetheringManager.TETHER_ERROR_DHCPSERVER_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800540 // Not much more we can do here
541 }
Remi NGUYEN VANb9379a52020-02-13 09:16:19 +0900542 mDhcpLeases.clear();
543 getHandler().post(mCallback::dhcpLeasesChanged);
markchien74a4fa92019-09-09 20:50:49 +0800544 }
545 });
546 mDhcpServer = null;
547 } catch (RemoteException e) {
markchien12c5bb82020-01-07 14:43:17 +0800548 mLog.e("Error stopping DHCP", e);
549 // Not much more we can do here
markchien74a4fa92019-09-09 20:50:49 +0800550 }
551 }
552 }
553
554 private boolean configureDhcp(boolean enable, Inet4Address addr, int prefixLen) {
555 if (enable) {
556 return startDhcp(addr, prefixLen);
557 } else {
558 stopDhcp();
559 return true;
560 }
561 }
562
563 private void stopIPv4() {
564 configureIPv4(false);
565 // NOTE: All of configureIPv4() will be refactored out of existence
566 // into calls to InterfaceController, shared with startIPv4().
567 mInterfaceCtrl.clearIPv4Address();
markchien12c5bb82020-01-07 14:43:17 +0800568 mIpv4Address = null;
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000569 mStaticIpv4ServerAddr = null;
570 mStaticIpv4ClientAddr = null;
markchien74a4fa92019-09-09 20:50:49 +0800571 }
572
markchien74a4fa92019-09-09 20:50:49 +0800573 private boolean configureIPv4(boolean enabled) {
574 if (VDBG) Log.d(TAG, "configureIPv4(" + enabled + ")");
575
576 // TODO: Replace this hard-coded information with dynamically selected
577 // config passed down to us by a higher layer IP-coordinating element.
markchien12c5bb82020-01-07 14:43:17 +0800578 final Inet4Address srvAddr;
markchien74a4fa92019-09-09 20:50:49 +0800579 int prefixLen = 0;
markchien12c5bb82020-01-07 14:43:17 +0800580 try {
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000581 if (mStaticIpv4ServerAddr != null) {
582 srvAddr = (Inet4Address) mStaticIpv4ServerAddr.getAddress();
583 prefixLen = mStaticIpv4ServerAddr.getPrefixLength();
584 } else if (mInterfaceType == TetheringManager.TETHERING_USB
Milim Lee45a971b2019-10-17 05:02:33 +0900585 || mInterfaceType == TetheringManager.TETHERING_NCM) {
markchien12c5bb82020-01-07 14:43:17 +0800586 srvAddr = (Inet4Address) parseNumericAddress(USB_NEAR_IFACE_ADDR);
587 prefixLen = USB_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800588 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI) {
markchien12c5bb82020-01-07 14:43:17 +0800589 srvAddr = (Inet4Address) parseNumericAddress(getRandomWifiIPv4Address());
590 prefixLen = WIFI_HOST_IFACE_PREFIX_LENGTH;
markchien9b4d7572019-12-25 19:40:32 +0800591 } else if (mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800592 srvAddr = (Inet4Address) parseNumericAddress(WIFI_P2P_IFACE_ADDR);
593 prefixLen = WIFI_P2P_IFACE_PREFIX_LENGTH;
Remi NGUYEN VAN0ef3b752020-01-24 22:57:09 +0900594 } else if (mInterfaceType == TetheringManager.TETHERING_ETHERNET) {
595 // TODO: randomize address for tethering too, similarly to wifi
596 srvAddr = (Inet4Address) parseNumericAddress(ETHERNET_IFACE_ADDR);
597 prefixLen = ETHERNET_IFACE_PREFIX_LENGTH;
markchien12c5bb82020-01-07 14:43:17 +0800598 } else {
599 // BT configures the interface elsewhere: only start DHCP.
600 // TODO: make all tethering types behave the same way, and delete the bluetooth
601 // code that calls into NetworkManagementService directly.
602 srvAddr = (Inet4Address) parseNumericAddress(BLUETOOTH_IFACE_ADDR);
603 mIpv4Address = new LinkAddress(srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
604 return configureDhcp(enabled, srvAddr, BLUETOOTH_DHCP_PREFIX_LENGTH);
605 }
606 mIpv4Address = new LinkAddress(srvAddr, prefixLen);
607 } catch (IllegalArgumentException e) {
608 mLog.e("Error selecting ipv4 address", e);
609 if (!enabled) stopDhcp();
610 return false;
markchien74a4fa92019-09-09 20:50:49 +0800611 }
612
markchien12c5bb82020-01-07 14:43:17 +0800613 final Boolean setIfaceUp;
Jimmy Chenea902f62019-12-03 11:37:09 +0800614 if (mInterfaceType == TetheringManager.TETHERING_WIFI
615 || mInterfaceType == TetheringManager.TETHERING_WIFI_P2P) {
markchien12c5bb82020-01-07 14:43:17 +0800616 // The WiFi stack has ownership of the interface up/down state.
617 // It is unclear whether the Bluetooth or USB stacks will manage their own
618 // state.
619 setIfaceUp = null;
620 } else {
621 setIfaceUp = enabled;
622 }
623 if (!mInterfaceCtrl.setInterfaceConfiguration(mIpv4Address, setIfaceUp)) {
624 mLog.e("Error configuring interface");
625 if (!enabled) stopDhcp();
626 return false;
627 }
markchien74a4fa92019-09-09 20:50:49 +0800628
markchien74a4fa92019-09-09 20:50:49 +0800629 // Directly-connected route.
markchien12c5bb82020-01-07 14:43:17 +0800630 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
631 mIpv4Address.getPrefixLength());
markchien6cf0e552019-12-06 15:24:53 +0800632 final RouteInfo route = new RouteInfo(ipv4Prefix, null, null, RTN_UNICAST);
markchien74a4fa92019-09-09 20:50:49 +0800633 if (enabled) {
markchien12c5bb82020-01-07 14:43:17 +0800634 mLinkProperties.addLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800635 mLinkProperties.addRoute(route);
636 } else {
markchien12c5bb82020-01-07 14:43:17 +0800637 mLinkProperties.removeLinkAddress(mIpv4Address);
markchien74a4fa92019-09-09 20:50:49 +0800638 mLinkProperties.removeRoute(route);
639 }
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000640
641 return configureDhcp(enabled, srvAddr, prefixLen);
markchien74a4fa92019-09-09 20:50:49 +0800642 }
643
644 private String getRandomWifiIPv4Address() {
645 try {
646 byte[] bytes = parseNumericAddress(WIFI_HOST_IFACE_ADDR).getAddress();
647 bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF);
648 return InetAddress.getByAddress(bytes).getHostAddress();
649 } catch (Exception e) {
650 return WIFI_HOST_IFACE_ADDR;
651 }
652 }
653
654 private boolean startIPv6() {
655 mInterfaceParams = mDeps.getInterfaceParams(mIfaceName);
656 if (mInterfaceParams == null) {
657 mLog.e("Failed to find InterfaceParams");
658 stopIPv6();
659 return false;
660 }
661
662 mRaDaemon = mDeps.getRouterAdvertisementDaemon(mInterfaceParams);
663 if (!mRaDaemon.start()) {
664 stopIPv6();
665 return false;
666 }
667
668 return true;
669 }
670
671 private void stopIPv6() {
672 mInterfaceParams = null;
673 setRaParams(null);
674
675 if (mRaDaemon != null) {
676 mRaDaemon.stop();
677 mRaDaemon = null;
678 }
679 }
680
681 // IPv6TetheringCoordinator sends updates with carefully curated IPv6-only
682 // LinkProperties. These have extraneous data filtered out and only the
683 // necessary prefixes included (per its prefix distribution policy).
684 //
685 // TODO: Evaluate using a data structure than is more directly suited to
686 // communicating only the relevant information.
687 private void updateUpstreamIPv6LinkProperties(LinkProperties v6only) {
688 if (mRaDaemon == null) return;
689
690 // Avoid unnecessary work on spurious updates.
691 if (Objects.equals(mLastIPv6LinkProperties, v6only)) {
692 return;
693 }
694
695 RaParams params = null;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900696 int upstreamIfindex = 0;
markchien74a4fa92019-09-09 20:50:49 +0800697
698 if (v6only != null) {
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900699 final String upstreamIface = v6only.getInterfaceName();
700
markchien74a4fa92019-09-09 20:50:49 +0800701 params = new RaParams();
Maciej Żenczykowskida0fb1b2020-02-19 01:24:39 -0800702 // We advertise an mtu lower by 16, which is the closest multiple of 8 >= 14,
703 // the ethernet header size. This makes kernel ebpf tethering offload happy.
704 // This hack should be reverted once we have the kernel fixed up.
705 // Note: this will automatically clamp to at least 1280 (ipv6 minimum mtu)
706 // see RouterAdvertisementDaemon.java putMtu()
707 params.mtu = v6only.getMtu() - 16;
markchien74a4fa92019-09-09 20:50:49 +0800708 params.hasDefaultRoute = v6only.hasIpv6DefaultRoute();
709
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900710 if (params.hasDefaultRoute) params.hopLimit = getHopLimit(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800711
712 for (LinkAddress linkAddr : v6only.getLinkAddresses()) {
713 if (linkAddr.getPrefixLength() != RFC7421_PREFIX_LENGTH) continue;
714
715 final IpPrefix prefix = new IpPrefix(
716 linkAddr.getAddress(), linkAddr.getPrefixLength());
717 params.prefixes.add(prefix);
718
719 final Inet6Address dnsServer = getLocalDnsIpFor(prefix);
720 if (dnsServer != null) {
721 params.dnses.add(dnsServer);
722 }
723 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900724
725 upstreamIfindex = mDeps.getIfindex(upstreamIface);
markchien74a4fa92019-09-09 20:50:49 +0800726 }
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900727
markchien74a4fa92019-09-09 20:50:49 +0800728 // If v6only is null, we pass in null to setRaParams(), which handles
729 // deprecation of any existing RA data.
730
731 setRaParams(params);
732 mLastIPv6LinkProperties = v6only;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900733
734 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, upstreamIfindex, null);
735 mLastIPv6UpstreamIfindex = upstreamIfindex;
markchien74a4fa92019-09-09 20:50:49 +0800736 }
737
738 private void configureLocalIPv6Routes(
739 HashSet<IpPrefix> deprecatedPrefixes, HashSet<IpPrefix> newPrefixes) {
740 // [1] Remove the routes that are deprecated.
741 if (!deprecatedPrefixes.isEmpty()) {
742 final ArrayList<RouteInfo> toBeRemoved =
743 getLocalRoutesFor(mIfaceName, deprecatedPrefixes);
markchien12c5bb82020-01-07 14:43:17 +0800744 // Remove routes from local network.
745 final int removalFailures = RouteUtils.removeRoutesFromLocalNetwork(
746 mNetd, toBeRemoved);
747 if (removalFailures > 0) {
748 mLog.e(String.format("Failed to remove %d IPv6 routes from local table.",
749 removalFailures));
markchien74a4fa92019-09-09 20:50:49 +0800750 }
751
752 for (RouteInfo route : toBeRemoved) mLinkProperties.removeRoute(route);
753 }
754
755 // [2] Add only the routes that have not previously been added.
756 if (newPrefixes != null && !newPrefixes.isEmpty()) {
757 HashSet<IpPrefix> addedPrefixes = (HashSet) newPrefixes.clone();
758 if (mLastRaParams != null) {
759 addedPrefixes.removeAll(mLastRaParams.prefixes);
760 }
761
762 if (!addedPrefixes.isEmpty()) {
763 final ArrayList<RouteInfo> toBeAdded =
764 getLocalRoutesFor(mIfaceName, addedPrefixes);
765 try {
markchien12c5bb82020-01-07 14:43:17 +0800766 // It's safe to call networkAddInterface() even if
767 // the interface is already in the local_network.
768 mNetd.networkAddInterface(INetd.LOCAL_NET_ID, mIfaceName);
769 try {
770 // Add routes from local network. Note that adding routes that
771 // already exist does not cause an error (EEXIST is silently ignored).
772 RouteUtils.addRoutesToLocalNetwork(mNetd, mIfaceName, toBeAdded);
773 } catch (IllegalStateException e) {
774 mLog.e("Failed to add IPv6 routes to local table: " + e);
775 }
776 } catch (ServiceSpecificException | RemoteException e) {
777 mLog.e("Failed to add " + mIfaceName + " to local table: ", e);
markchien74a4fa92019-09-09 20:50:49 +0800778 }
779
780 for (RouteInfo route : toBeAdded) mLinkProperties.addRoute(route);
781 }
782 }
783 }
784
785 private void configureLocalIPv6Dns(
786 HashSet<Inet6Address> deprecatedDnses, HashSet<Inet6Address> newDnses) {
787 // TODO: Is this really necessary? Can we not fail earlier if INetd cannot be located?
788 if (mNetd == null) {
789 if (newDnses != null) newDnses.clear();
790 mLog.e("No netd service instance available; not setting local IPv6 addresses");
791 return;
792 }
793
794 // [1] Remove deprecated local DNS IP addresses.
795 if (!deprecatedDnses.isEmpty()) {
796 for (Inet6Address dns : deprecatedDnses) {
797 if (!mInterfaceCtrl.removeAddress(dns, RFC7421_PREFIX_LENGTH)) {
798 mLog.e("Failed to remove local dns IP " + dns);
799 }
800
801 mLinkProperties.removeLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
802 }
803 }
804
805 // [2] Add only the local DNS IP addresses that have not previously been added.
806 if (newDnses != null && !newDnses.isEmpty()) {
807 final HashSet<Inet6Address> addedDnses = (HashSet) newDnses.clone();
808 if (mLastRaParams != null) {
809 addedDnses.removeAll(mLastRaParams.dnses);
810 }
811
812 for (Inet6Address dns : addedDnses) {
813 if (!mInterfaceCtrl.addAddress(dns, RFC7421_PREFIX_LENGTH)) {
814 mLog.e("Failed to add local dns IP " + dns);
815 newDnses.remove(dns);
816 }
817
818 mLinkProperties.addLinkAddress(new LinkAddress(dns, RFC7421_PREFIX_LENGTH));
819 }
820 }
821
822 try {
823 mNetd.tetherApplyDnsInterfaces();
824 } catch (ServiceSpecificException | RemoteException e) {
825 mLog.e("Failed to update local DNS caching server");
826 if (newDnses != null) newDnses.clear();
827 }
828 }
829
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900830 private void addIpv6ForwardingRule(Ipv6ForwardingRule rule) {
831 try {
Lorenzo Colittie6107d22020-04-06 09:19:57 +0000832 mNetd.tetherOffloadRuleAdd(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900833 mIpv6ForwardingRules.put(rule.address, rule);
834 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000835 mLog.e("Could not add IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900836 }
837 }
838
839 private void removeIpv6ForwardingRule(Ipv6ForwardingRule rule, boolean removeFromMap) {
840 try {
Lorenzo Colittie6107d22020-04-06 09:19:57 +0000841 mNetd.tetherOffloadRuleRemove(rule.toTetherOffloadRuleParcel());
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900842 if (removeFromMap) {
843 mIpv6ForwardingRules.remove(rule.address);
844 }
845 } catch (RemoteException | ServiceSpecificException e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000846 mLog.e("Could not remove IPv6 downstream rule: ", e);
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900847 }
848 }
849
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000850 private void clearIpv6ForwardingRules() {
851 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
852 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
853 }
854 mIpv6ForwardingRules.clear();
855 }
856
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900857 // Convenience method to replace a rule with the same rule on a new upstream interface.
858 // Allows replacing the rules in one iteration pass without ConcurrentModificationExceptions.
859 // Relies on the fact that rules are in a map indexed by IP address.
860 private void updateIpv6ForwardingRule(Ipv6ForwardingRule rule, int newIfindex) {
861 addIpv6ForwardingRule(rule.onNewUpstream(newIfindex));
862 removeIpv6ForwardingRule(rule, false /*removeFromMap*/);
863 }
864
865 // Handles all updates to IPv6 forwarding rules. These can currently change only if the upstream
866 // changes or if a neighbor event is received.
867 private void updateIpv6ForwardingRules(int prevUpstreamIfindex, int upstreamIfindex,
868 NeighborEvent e) {
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000869 // If we no longer have an upstream, clear forwarding rules and do nothing else.
870 if (upstreamIfindex == 0) {
871 clearIpv6ForwardingRules();
872 return;
873 }
874
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900875 // If the upstream interface has changed, remove all rules and re-add them with the new
876 // upstream interface.
877 if (prevUpstreamIfindex != upstreamIfindex) {
878 for (Ipv6ForwardingRule rule : mIpv6ForwardingRules.values()) {
879 updateIpv6ForwardingRule(rule, upstreamIfindex);
880 }
881 }
882
883 // If we're here to process a NeighborEvent, do so now.
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000884 // mInterfaceParams must be non-null or the event would not have arrived.
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900885 if (e == null) return;
886 if (!(e.ip instanceof Inet6Address) || e.ip.isMulticastAddress()
887 || e.ip.isLoopbackAddress() || e.ip.isLinkLocalAddress()) {
888 return;
889 }
890
Automerger Merge Workerf1194882020-02-25 04:04:44 +0000891 Ipv6ForwardingRule rule = new Ipv6ForwardingRule(upstreamIfindex,
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +0900892 mInterfaceParams.index, (Inet6Address) e.ip, mInterfaceParams.macAddr,
893 e.macAddr);
894 if (e.isValid()) {
895 addIpv6ForwardingRule(rule);
896 } else {
897 removeIpv6ForwardingRule(rule, true /*removeFromMap*/);
898 }
899 }
900
901 private void handleNeighborEvent(NeighborEvent e) {
902 if (mInterfaceParams != null
903 && mInterfaceParams.index == e.ifindex
904 && mInterfaceParams.hasMacAddress) {
905 updateIpv6ForwardingRules(mLastIPv6UpstreamIfindex, mLastIPv6UpstreamIfindex, e);
906 }
907 }
908
markchien74a4fa92019-09-09 20:50:49 +0800909 private byte getHopLimit(String upstreamIface) {
910 try {
911 int upstreamHopLimit = Integer.parseUnsignedInt(
912 mNetd.getProcSysNet(INetd.IPV6, INetd.CONF, upstreamIface, "hop_limit"));
913 // Add one hop to account for this forwarding device
914 upstreamHopLimit++;
915 // Cap the hop limit to 255.
916 return (byte) Integer.min(upstreamHopLimit, 255);
917 } catch (Exception e) {
918 mLog.e("Failed to find upstream interface hop limit", e);
919 }
920 return RaParams.DEFAULT_HOPLIMIT;
921 }
922
923 private void setRaParams(RaParams newParams) {
924 if (mRaDaemon != null) {
925 final RaParams deprecatedParams =
926 RaParams.getDeprecatedRaParams(mLastRaParams, newParams);
927
928 configureLocalIPv6Routes(deprecatedParams.prefixes,
929 (newParams != null) ? newParams.prefixes : null);
930
931 configureLocalIPv6Dns(deprecatedParams.dnses,
932 (newParams != null) ? newParams.dnses : null);
933
934 mRaDaemon.buildNewRa(deprecatedParams, newParams);
935 }
936
937 mLastRaParams = newParams;
938 }
939
940 private void logMessage(State state, int what) {
941 mLog.log(state.getName() + " got " + sMagicDecoderRing.get(what, Integer.toString(what)));
942 }
943
944 private void sendInterfaceState(int newInterfaceState) {
945 mServingMode = newInterfaceState;
946 mCallback.updateInterfaceState(this, newInterfaceState, mLastError);
947 sendLinkProperties();
948 }
949
950 private void sendLinkProperties() {
951 mCallback.updateLinkProperties(this, new LinkProperties(mLinkProperties));
952 }
953
954 private void resetLinkProperties() {
955 mLinkProperties.clear();
956 mLinkProperties.setInterfaceName(mIfaceName);
957 }
958
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000959 private void maybeConfigureStaticIp(final TetheringRequestParcel request) {
960 if (request == null) return;
961
962 mStaticIpv4ServerAddr = request.localIPv4Address;
963 mStaticIpv4ClientAddr = request.staticClientAddress;
964 }
965
markchien74a4fa92019-09-09 20:50:49 +0800966 class InitialState extends State {
967 @Override
968 public void enter() {
969 sendInterfaceState(STATE_AVAILABLE);
970 }
971
972 @Override
973 public boolean processMessage(Message message) {
974 logMessage(this, message.what);
975 switch (message.what) {
976 case CMD_TETHER_REQUESTED:
markchien9b4d7572019-12-25 19:40:32 +0800977 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +0800978 switch (message.arg1) {
979 case STATE_LOCAL_ONLY:
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000980 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +0800981 transitionTo(mLocalHotspotState);
982 break;
983 case STATE_TETHERED:
Automerger Merge Worker9462a3c2020-03-17 16:59:57 +0000984 maybeConfigureStaticIp((TetheringRequestParcel) message.obj);
markchien74a4fa92019-09-09 20:50:49 +0800985 transitionTo(mTetheredState);
986 break;
987 default:
988 mLog.e("Invalid tethering interface serving state specified.");
989 }
990 break;
991 case CMD_INTERFACE_DOWN:
992 transitionTo(mUnavailableState);
993 break;
994 case CMD_IPV6_TETHER_UPDATE:
995 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
996 break;
997 default:
998 return NOT_HANDLED;
999 }
1000 return HANDLED;
1001 }
1002 }
1003
1004 class BaseServingState extends State {
1005 @Override
1006 public void enter() {
1007 if (!startIPv4()) {
markchien9b4d7572019-12-25 19:40:32 +08001008 mLastError = TetheringManager.TETHER_ERROR_IFACE_CFG_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001009 return;
1010 }
1011
1012 try {
markchien12c5bb82020-01-07 14:43:17 +08001013 final IpPrefix ipv4Prefix = new IpPrefix(mIpv4Address.getAddress(),
1014 mIpv4Address.getPrefixLength());
1015 NetdUtils.tetherInterface(mNetd, mIfaceName, ipv4Prefix);
markchien6c2b7cc2020-02-15 11:35:00 +08001016 } catch (RemoteException | ServiceSpecificException | IllegalStateException e) {
markchien74a4fa92019-09-09 20:50:49 +08001017 mLog.e("Error Tethering: " + e);
markchien9b4d7572019-12-25 19:40:32 +08001018 mLastError = TetheringManager.TETHER_ERROR_TETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001019 return;
1020 }
1021
1022 if (!startIPv6()) {
1023 mLog.e("Failed to startIPv6");
1024 // TODO: Make this a fatal error once Bluetooth IPv6 is sorted.
1025 return;
1026 }
1027 }
1028
1029 @Override
1030 public void exit() {
1031 // Note that at this point, we're leaving the tethered state. We can fail any
1032 // of these operations, but it doesn't really change that we have to try them
1033 // all in sequence.
1034 stopIPv6();
1035
1036 try {
markchien12c5bb82020-01-07 14:43:17 +08001037 NetdUtils.untetherInterface(mNetd, mIfaceName);
1038 } catch (RemoteException | ServiceSpecificException e) {
markchien9b4d7572019-12-25 19:40:32 +08001039 mLastError = TetheringManager.TETHER_ERROR_UNTETHER_IFACE_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001040 mLog.e("Failed to untether interface: " + e);
1041 }
1042
1043 stopIPv4();
1044
1045 resetLinkProperties();
1046 }
1047
1048 @Override
1049 public boolean processMessage(Message message) {
1050 logMessage(this, message.what);
1051 switch (message.what) {
1052 case CMD_TETHER_UNREQUESTED:
1053 transitionTo(mInitialState);
1054 if (DBG) Log.d(TAG, "Untethered (unrequested)" + mIfaceName);
1055 break;
1056 case CMD_INTERFACE_DOWN:
1057 transitionTo(mUnavailableState);
1058 if (DBG) Log.d(TAG, "Untethered (ifdown)" + mIfaceName);
1059 break;
1060 case CMD_IPV6_TETHER_UPDATE:
1061 updateUpstreamIPv6LinkProperties((LinkProperties) message.obj);
1062 sendLinkProperties();
1063 break;
1064 case CMD_IP_FORWARDING_ENABLE_ERROR:
1065 case CMD_IP_FORWARDING_DISABLE_ERROR:
1066 case CMD_START_TETHERING_ERROR:
1067 case CMD_STOP_TETHERING_ERROR:
1068 case CMD_SET_DNS_FORWARDERS_ERROR:
markchienf1332572020-03-19 13:37:43 +08001069 mLastError = TetheringManager.TETHER_ERROR_INTERNAL_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001070 transitionTo(mInitialState);
1071 break;
1072 default:
1073 return false;
1074 }
1075 return true;
1076 }
1077 }
1078
1079 // Handling errors in BaseServingState.enter() by transitioning is
1080 // problematic because transitioning during a multi-state jump yields
1081 // a Log.wtf(). Ultimately, there should be only one ServingState,
1082 // and forwarding and NAT rules should be handled by a coordinating
1083 // functional element outside of IpServer.
1084 class LocalHotspotState extends BaseServingState {
1085 @Override
1086 public void enter() {
1087 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001088 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001089 transitionTo(mInitialState);
1090 }
1091
1092 if (DBG) Log.d(TAG, "Local hotspot " + mIfaceName);
1093 sendInterfaceState(STATE_LOCAL_ONLY);
1094 }
1095
1096 @Override
1097 public boolean processMessage(Message message) {
1098 if (super.processMessage(message)) return true;
1099
1100 logMessage(this, message.what);
1101 switch (message.what) {
1102 case CMD_TETHER_REQUESTED:
1103 mLog.e("CMD_TETHER_REQUESTED while in local-only hotspot mode.");
1104 break;
1105 case CMD_TETHER_CONNECTION_CHANGED:
1106 // Ignored in local hotspot state.
1107 break;
1108 default:
1109 return false;
1110 }
1111 return true;
1112 }
1113 }
1114
1115 // Handling errors in BaseServingState.enter() by transitioning is
1116 // problematic because transitioning during a multi-state jump yields
1117 // a Log.wtf(). Ultimately, there should be only one ServingState,
1118 // and forwarding and NAT rules should be handled by a coordinating
1119 // functional element outside of IpServer.
1120 class TetheredState extends BaseServingState {
1121 @Override
1122 public void enter() {
1123 super.enter();
markchien9b4d7572019-12-25 19:40:32 +08001124 if (mLastError != TetheringManager.TETHER_ERROR_NO_ERROR) {
markchien74a4fa92019-09-09 20:50:49 +08001125 transitionTo(mInitialState);
1126 }
1127
1128 if (DBG) Log.d(TAG, "Tethered " + mIfaceName);
1129 sendInterfaceState(STATE_TETHERED);
1130 }
1131
1132 @Override
1133 public void exit() {
1134 cleanupUpstream();
1135 super.exit();
1136 }
1137
1138 private void cleanupUpstream() {
1139 if (mUpstreamIfaceSet == null) return;
1140
1141 for (String ifname : mUpstreamIfaceSet.ifnames) cleanupUpstreamInterface(ifname);
1142 mUpstreamIfaceSet = null;
Automerger Merge Workerf1194882020-02-25 04:04:44 +00001143 clearIpv6ForwardingRules();
markchien74a4fa92019-09-09 20:50:49 +08001144 }
1145
1146 private void cleanupUpstreamInterface(String upstreamIface) {
1147 // Note that we don't care about errors here.
1148 // Sometimes interfaces are gone before we get
1149 // to remove their rules, which generates errors.
1150 // Just do the best we can.
1151 try {
markchien12c5bb82020-01-07 14:43:17 +08001152 mNetd.ipfwdRemoveInterfaceForward(mIfaceName, upstreamIface);
1153 } catch (RemoteException | ServiceSpecificException e) {
1154 mLog.e("Exception in ipfwdRemoveInterfaceForward: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001155 }
1156 try {
markchien12c5bb82020-01-07 14:43:17 +08001157 mNetd.tetherRemoveForward(mIfaceName, upstreamIface);
1158 } catch (RemoteException | ServiceSpecificException e) {
1159 mLog.e("Exception in disableNat: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001160 }
1161 }
1162
1163 @Override
1164 public boolean processMessage(Message message) {
1165 if (super.processMessage(message)) return true;
1166
1167 logMessage(this, message.what);
1168 switch (message.what) {
1169 case CMD_TETHER_REQUESTED:
1170 mLog.e("CMD_TETHER_REQUESTED while already tethering.");
1171 break;
1172 case CMD_TETHER_CONNECTION_CHANGED:
1173 final InterfaceSet newUpstreamIfaceSet = (InterfaceSet) message.obj;
1174 if (noChangeInUpstreamIfaceSet(newUpstreamIfaceSet)) {
1175 if (VDBG) Log.d(TAG, "Connection changed noop - dropping");
1176 break;
1177 }
1178
1179 if (newUpstreamIfaceSet == null) {
1180 cleanupUpstream();
1181 break;
1182 }
1183
1184 for (String removed : upstreamInterfacesRemoved(newUpstreamIfaceSet)) {
1185 cleanupUpstreamInterface(removed);
1186 }
1187
1188 final Set<String> added = upstreamInterfacesAdd(newUpstreamIfaceSet);
1189 // This makes the call to cleanupUpstream() in the error
1190 // path for any interface neatly cleanup all the interfaces.
1191 mUpstreamIfaceSet = newUpstreamIfaceSet;
1192
1193 for (String ifname : added) {
1194 try {
markchien12c5bb82020-01-07 14:43:17 +08001195 mNetd.tetherAddForward(mIfaceName, ifname);
1196 mNetd.ipfwdAddInterfaceForward(mIfaceName, ifname);
1197 } catch (RemoteException | ServiceSpecificException e) {
1198 mLog.e("Exception enabling NAT: " + e.toString());
markchien74a4fa92019-09-09 20:50:49 +08001199 cleanupUpstream();
markchienf1332572020-03-19 13:37:43 +08001200 mLastError = TetheringManager.TETHER_ERROR_ENABLE_FORWARDING_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001201 transitionTo(mInitialState);
1202 return true;
1203 }
1204 }
1205 break;
Lorenzo Colitti5e15d7b2020-02-14 01:06:35 +09001206 case CMD_NEIGHBOR_EVENT:
1207 handleNeighborEvent((NeighborEvent) message.obj);
1208 break;
markchien74a4fa92019-09-09 20:50:49 +08001209 default:
1210 return false;
1211 }
1212 return true;
1213 }
1214
1215 private boolean noChangeInUpstreamIfaceSet(InterfaceSet newIfaces) {
1216 if (mUpstreamIfaceSet == null && newIfaces == null) return true;
1217 if (mUpstreamIfaceSet != null && newIfaces != null) {
1218 return mUpstreamIfaceSet.equals(newIfaces);
1219 }
1220 return false;
1221 }
1222
1223 private Set<String> upstreamInterfacesRemoved(InterfaceSet newIfaces) {
1224 if (mUpstreamIfaceSet == null) return new HashSet<>();
1225
1226 final HashSet<String> removed = new HashSet<>(mUpstreamIfaceSet.ifnames);
1227 removed.removeAll(newIfaces.ifnames);
1228 return removed;
1229 }
1230
1231 private Set<String> upstreamInterfacesAdd(InterfaceSet newIfaces) {
1232 final HashSet<String> added = new HashSet<>(newIfaces.ifnames);
1233 if (mUpstreamIfaceSet != null) added.removeAll(mUpstreamIfaceSet.ifnames);
1234 return added;
1235 }
1236 }
1237
1238 /**
1239 * This state is terminal for the per interface state machine. At this
1240 * point, the master state machine should have removed this interface
1241 * specific state machine from its list of possible recipients of
1242 * tethering requests. The state machine itself will hang around until
1243 * the garbage collector finds it.
1244 */
1245 class UnavailableState extends State {
1246 @Override
1247 public void enter() {
markchien9b4d7572019-12-25 19:40:32 +08001248 mLastError = TetheringManager.TETHER_ERROR_NO_ERROR;
markchien74a4fa92019-09-09 20:50:49 +08001249 sendInterfaceState(STATE_UNAVAILABLE);
1250 }
1251 }
1252
1253 // Accumulate routes representing "prefixes to be assigned to the local
1254 // interface", for subsequent modification of local_network routing.
1255 private static ArrayList<RouteInfo> getLocalRoutesFor(
1256 String ifname, HashSet<IpPrefix> prefixes) {
1257 final ArrayList<RouteInfo> localRoutes = new ArrayList<RouteInfo>();
1258 for (IpPrefix ipp : prefixes) {
markchien6cf0e552019-12-06 15:24:53 +08001259 localRoutes.add(new RouteInfo(ipp, null, ifname, RTN_UNICAST));
markchien74a4fa92019-09-09 20:50:49 +08001260 }
1261 return localRoutes;
1262 }
1263
1264 // Given a prefix like 2001:db8::/64 return an address like 2001:db8::1.
1265 private static Inet6Address getLocalDnsIpFor(IpPrefix localPrefix) {
1266 final byte[] dnsBytes = localPrefix.getRawAddress();
1267 dnsBytes[dnsBytes.length - 1] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1));
1268 try {
1269 return Inet6Address.getByAddress(null, dnsBytes, 0);
1270 } catch (UnknownHostException e) {
markchien6cf0e552019-12-06 15:24:53 +08001271 Log.wtf(TAG, "Failed to construct Inet6Address from: " + localPrefix);
markchien74a4fa92019-09-09 20:50:49 +08001272 return null;
1273 }
1274 }
1275
1276 private static byte getRandomSanitizedByte(byte dflt, byte... excluded) {
1277 final byte random = (byte) (new Random()).nextInt();
1278 for (int value : excluded) {
1279 if (random == value) return dflt;
1280 }
1281 return random;
1282 }
1283}